How can I resolve the null object reference in c# [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I want to print all the products with a price between 10 and 50 euro.
I have created 2 products in main and I call the method from the class Product in order to make the verification.But it gives me the else branch everytime, "No products".I understand what I'm doing wrong, I create an object reference from the class Product, then I call the method but it gives me the wrong output because in the method I create another object and for this object this price is 0 so it shows me that thing.
But how can I resolve this?
Here there are the classes:
the product class:
class Product
{
public int ProductId;
public string SKU;
public string Name;
public decimal Price;
public string Description;
public string Producer;
public virtual decimal GetPrice()
{
return Price;
}
public virtual String GetName()
{
return Name;
}
public void PrintPrice()
{
Product f = new Product();
if (f.GetPrice() > 10 && f.GetPrice() < 50)
Console.WriteLine("Product: {0}", f.GetName());
else
Console.WriteLine("No products priced between 10 and 50 lei.");
}
public Product() { }
the main where I ve been creating the objects:
static void Main(string[] args)
{
Product f = new Food(1, "green", "Papa", 15, "Good Quality", "Sana");
Product f1 = new Food(2, "white", "Papa1", 45, "Bad Quality", "Ariel");
f.PrintPrice();
f1.PrintPrice();
}
and I have also the food class but it inherits only the Product class so it's not relevant here.So what can I do?Thank you.

public void PrintPrice()
{
Product f = new Product();
....
}
At the moment, f is a new Product without any properties (including no price)
You should do something like
public void PrintPrice()
{
if (this.GetPrice() > 10 && this.GetPrice() < 50)
Console.WriteLine("Product: {0}", this.GetName());
else
Console.WriteLine("No products priced between 10 and 50 lei.");
}

You did not assign a value to the Price, so it's 0 and then you have the "No products"..try to assign a value to the product first

Related

Cannot convert from '...Generic.List<Game02.Human>' to 'Game02.Human' [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm trying to make functions to "send" NPCs to specific rooms by adding them to the room's humansHere list, and one to get this list (and print it later, but I don't need help with that). But I get this error message:
Argument 1: cannot convert from 'System.Collections.Generic.List<Game02.Human>' to 'Game02.Human'
Once I get that fixed, I'm sure I'll figure out the rest, so feel free to ignore this: I need to know how to call this function for specific rooms. Something like:
LivingRoom.GetHumansHere() or Kitchen.SetHumansHere(_lyndonJohnson). Or will this work as it is?
public class Room
{
public int ID { get; set; }
[...]
private List<Human> humansHere;
public List<Human> GetHumansHere()
{
return humansHere;
}
public void SetHumansHere(List<Human> x)
{
humansHere.Add(x);
}
}
public class Human : LivingCreature
{
public int Gold { get; set; }
public List<InventoryItem> Inventory { get; set; }
public Human(string name, int currentHitPoints, int maximumHitPoints, int gold) : base(name, currentHitPoints, maximumHitPoints)
{
Gold = gold;
}
}
Thank you to Dmitry for making it work, and thank you to Jonathan for explaining the problem:
The problem is you are trying to add a LIST of humans to a list rather than a single human to a list
Two possibilities:
If you want to add one person only, change method's signature:
public void SetHumansHere(Human person)
{
if (null == person)
throw new ArgumentNullException(nameof(person));
humansHere.Add(person);
}
If you want to add a collection of persons in one go, use AddRange
// IEnumerable<Human> - let's generalize the method
// and allow to add not only List, but other collections, say, array
public void SetHumansHere(IEnumerable<Human> persons)
{
if (null == persons)
throw new ArgumentNullException(nameof(persons));
humansHere.AddRange(persons);
}
you need to use List.AddRange, Adds the elements of the specified collection to the end of the List.
public void SetHumansHere(List<Human> x)
{
humansHere.AddRange(x);
}

Object Oriented Programming help or advice? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I'm a novice programmer. I've been writing scripts for about 9 to 11 weeks. Any how I have been buying books per the posting that alot of you guys have recommended. I'm trying to learn "OOP", and it can be little challenging. I have worked the exercises in back of the book. The first exercise told me to make a Console Application program that prompts the user for a type of sport, and the coaches name.
My first question is, did I do this question right?
Are there other ways of doing the same thing, but in different process?
I do realize that I do not have any "try/catches", the exercise told me not to add to this exercise problem. So we will worry about this later.
My code:
static void Main(string[] args)
{
Sport sport01 = new Sport();
sport01.TypeOfSport = GetSportsName();
sport01.CoachesName = GetCoachesName();
Console.WriteLine();
Console.WriteLine(sport01.ToString());
System.Threading.Thread.Sleep(8000);
}
// Prompting user input for type of sport.
public static string GetSportsName()
{
string typeOfSport;
Console.Write("Enter Sports Name : ");
typeOfSport = Console.ReadLine();
return typeOfSport;
}
// Prompting user inout for coaches name.
public static string GetCoachesName()
{
string coachesName;
Console.Write("Enter Coaches Name : ");
coachesName = Console.ReadLine();
return coachesName;
}
class Sport
{
protected string typeOfSport;
protected string coachesName;
public Sport()
{
typeOfSport = "Not Given";
coachesName = "Not Given";
}
public Sport(string typeOS, string coachesN)
{
typeOfSport = typeOS;
coachesName = coachesN;
}
public string TypeOfSport
{
get { return typeOfSport; }
set { typeOfSport = value; }
}
public string CoachesName
{
get { return coachesName; }
set { coachesName = value; }
}
public override string ToString()
{
return "\n" + "\n" +
"\nSports Name : " + typeOfSport +
"\n" +
"\nCoaches Name : " + coachesName;
}
}
It is sometimes better to treat a class as immutable; once created, it never changes. For example:
class Sport
{
protected readonly string typeOfSport;
protected readonly string coachesName;
public Sport(string typeOfSport, string coachesName)
{
this.typeOfSport = typeOfSport;
this.coachesName = coachesName;
}
public string TypeOfSport
{
get { return typeOfSport; }
}
public string CoachesName
{
get { return coachesName; }
}
public override string ToString()
{
return "\n" + "\n" +
"\nSports Name : " + typeOfSport +
"\n" +
"\nCoaches Name : " + coachesName;
}
}
Now you don't have to deal with a Sport that might not have a coach's name or type, and you can get rid of those ugly "Not Given" values:
static void Main(string[] args)
{
var typeOfSport = GetSportsName();
var coachesName = GetCoachesName();
var sport = new Sport(typeOfSport, coachesName);
Console.WriteLine();
Console.WriteLine(sport.ToString());
System.Threading.Thread.Sleep(8000);
}
Notice at no time does a Sport exist that is not valid.
This approach does create more temporary variables, but that is not necessarily a bad thing, and in trade you never have to worry about validating a Sport before using it.
If you do want to keep the class as mutable, as in your original code, I'd advise against using a magic number (i.e. "Not Given") as these are considered a code smell. It would break, for example, if someone ever named their child "Not Given" and he grew up to be a coach. To represent a missing value, the convention is to simply use null.
Also, in general it is advisable to declare a variable the first time you use it, like this:
public static string GetSportsName()
{
Console.Write("Enter Sports Name : ");
var typeOfSport = Console.ReadLine();
return typeOfSport;
}
You'll also notice I changed most of the variable declarations to use var, which allows the compiler to infer the type from the value being assigned.
As a final note, it is poor form to name a variable with a number (e.g. sport01). If you have more than one, put them in an array or List. If you don't have more than one, don't just put an 01 on there, as developers may expect that there is an 02 or 03 somewhere. If you do need two instances that don't logically belong in a list together, give them names describing their purpose, e.g. morningSport and eveningSport or something.

Is there any kind of exception to sum up two variables from functions in C#? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am a very beginner in C#, and OOP also.
Here I am feeling an interesting matter while summing up two static variables from outer functions in C#.
Here is my code.
using System;
namespace StaticFun
{
class StaticFun
{
public static int a;
public static int b;
public void count()
{
a++;
}
public void mount()
{
b++;
}
public static int getsum()
{
return a + b;
}
}
class Program
{
static void Main(String[] args)
{
StaticFun obj = new StaticFun();
obj.count();
obj.count();
obj.count();
Console.WriteLine("Value of a for obj : {0}.", StaticFun.a);
obj.mount();
obj.mount();
Console.WriteLine("\na = {0}\nb = {0}\nSum : {0}.", StaticFun.a, StaticFun.b, StaticFun.getsum());
Console.ReadKey();
}
}
}
When I compiled this program, I get outputs like below.
Value of a for obj : 3.
a = 3
b = 3
Sum : 3
I can understand first two values from the output. But for b, it might be 2! Isn't it? In class StaticFun I made a function public void mount() to increment the value of b by 1. Since b being a static variable, its initial value was 0. Then after calling that function two times, it value would be 2. How the value can be 3, I can't understand that fact. Also, the sum might be 3+2=5, as my assumption. But it made the same value as the variable a and b as well.
I thought it happened for their static behavior. But astonishingly, it gave same output for non-static variable also!
Here is my Second code ,
using System;
namespace StaticFun
{
class StaticFun
{
public int a;
public int b;
public void count()
{
a++;
}
public void mount()
{
b++;
}
public int getsum()
{
return a + b;
}
}
class Program
{
static void Main(String[] args)
{
StaticFun obj = new StaticFun();
obj.count();
obj.count();
obj.count();
Console.WriteLine("Value of a for obj : {0}.", obj.a);
obj.mount();
obj.mount();
Console.WriteLine("\na = {0}\nb = {0}\nSum : {0}.", obj.a, obj.b, obj.getsum());
Console.ReadKey();
}
}
}
And the output as well,
Value of a for obj : 3.
a = 3
b = 3
Sum : 3
I completely misunderstand this fact. Is there anyone to make my concepts clear about those outputs?
The problem isn't your summing stuff - it's the way you print it:
Console.WriteLine("\na = {0}\nb = {0}\nSum : {0}.", StaticFun.a, StaticFun.b, StaticFun.getsum());
Your actually printing the same object three times in a row. You should increase the number in the brackets:
Console.WriteLine("\na = {0}\nb = {1}\nSum : {2}.", StaticFun.a, StaticFun.b, StaticFun.getsum());
For more information about string formatting read this: https://msdn.microsoft.com/de-de/library/system.string.format(v=vs.110).aspx
By the way, I'd suggest using string interpolation - it'd work like that:
Console.WriteLine($"\na = {StaticFun.a}\nb = {StaticFun.b}\nSum : {StaticFun.getsum()}.");
If you want to know more about string interpolation, take a look at this: https://msdn.microsoft.com/en-us/library/dn961160.aspx.
don't discount this either since its part of C# 6 and higher now too
Console.WriteLine($"\na = {StaticFun.a}\nb = {StaticFun.b}\nSum : {StaticFun.getsum()}.");

List Item gets altered [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am pretty sure that somewhere this question was answered but i could not find it.
I am looking up Objects from a list with name and quantity. The same Item can come up several times with different quantities. I want to add up the quantities.
bool addtolist = true; //the item is not part of the list
Item currentItem = FindItem(currentMats.Name); //Find the Item in the Catalogue
currentItem.Calc(currentMats.NeededQuantity, product.Runns, product.Level + 1); //Add quantities ect
CompleteList.Add(currentItem);
Here is the problem:
The first time the Algorithm runs all is ok.
The Problem comes up at the second run: the quantity is overridden the moment it hits line 2.
How can i force a new object and not a reference to the one in the storage?
A new instance of an object is only created when the new keyword is used. To get a copy, you'll have to create one
You could create a copy constructor and then a clone method on Item
public Item(Item otherItem){
variable1 = otherItem.variable1;
variable2 = otherItem.variable2;
...
}
public Item Clone(){
return new Item(this);
}
Then when you get the item, clone it
bool addtolist = true; //the item is not part of the list
Item currentItem = FindItem(currentMats.Name).Clone(); //Find the Item in the Catalogue
currentItem.Calc(currentMats.NeededQuantity, product.Runns, product.Level + 1); //Add quantities ect
CompleteList.Add(currentItem);`
Basically what you are doing is a histogram. LINQ has a built in method called GroupBy() that does this. See sample code below:
public class Material
{
public Material(string name, int quantity)
{
this.Name=name;
this.Quantity=quantity;
}
public string Name { get; private set; }
public int Quantity { get; private set; }
}
class Program
{
static void Main(string[] args)
{
List<Material> list=new List<Material>();
list.Add(new Material("AAA", 10));
list.Add(new Material("BBB", 20));
list.Add(new Material("CCC", 5));
list.Add(new Material("AAA", 5));
list.Add(new Material("CCC", 20));
Console.WriteLine("{0,6} {1,6}", "Mat", "Qty");
foreach(var item in list.GroupBy((mat) => mat.Name))
{
Console.WriteLine("{0,6} {1,6}", item.Key, item.Sum((mat) => mat.Quantity));
}
// Mat Qty
// AAA 15
// BBB 20
// CCC 25
}
}

Chaining Constructors [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to better understand chaining of constructors in C# and I have run into the following issue.
class Item
{
private string _name;
private string _category;
private int _sku;
private double _price;
// default values
public Item()
{
_name = "";
_category = "Sale Item";
_sku = 123;
_price = 1.99;
}
public Item(string name, double price) : this()
{
this._name = name;
this._price = price;
}
public Item(string name, string category, int sku, double price)
{
this._name = name;
this._category = category;
this._sku = sku;
this._price = price;
}
public string Name
{
get { return this._name; }
}
public string Category
{
get { return this._category; }
}
public int SKU
{
get { return this._sku; }
public double Price
{
get { return this._price; }
}
}
My idea was to use the parameterless constructor to set default values and use the parametrized constructors to only change those values which need to be updated.
Unfortunately this does not work. The code does not compile. The error message is 1729: there is no constructor that takes 2 arguments. I realize that this is not how constructors are normally chained but I do not understand why this fails to compile as the parameterless constructor Item() is called first before the second constructor Item(string name, double price) is called.
Any insight and sugegstions would be greatly appreciated.
Nothing wrong with the chaining constructors per se, the error you get is related to other code instantiating it with 2 specific paramaters which their is no specific constructor provided.
You need to add another 2 parameter constructor which matches that signature to fix that error.

Categories

Resources