I don't think that this is a duplicate, because the situations on the general text written about null reference exceptions talk about situations in which either the instance was not initialized or it was dereferenced and the programmer didn't realize it. In this case, there are 4 variables of the object which are used with the initialized instance and all are "working" fine(which I think proves that the object is not set to null and is referenced. But a forth variable of the same instance is throwing the exception. I'm studying C# with Head First and I built a Program in which a Property is used to set a "read-only" public variable from another class. The class in which the Property is defined has a defined constructor. When I run the program, I'm getting the 'NullReference Exception unhandled" message.
The property is this:
public decimal Cost
{
get
{
decimal totalCost = CalculateCostOfDecorations();
totalCost += ((CalculateCostOfBeveragesPerPerson() + CostOfFoodPerPerson) * NumberOfPeople);
if (HealthyOption)
{
totalCost *= .95M;
return totalCost;
}
return totalCost;
}
}
The constructor is:
public DinnerParty(int numberOfPeople, bool healthyOption, bool fancyDecorations)
{
NumberOfPeople = numberOfPeople;
HealthyOption = healthyOption;
FancyDecorations = fancyDecorations;
}
The strange thing is that in the Form.cs class where the object "dinnerParty" is initialized, all the variables from the constructor are used and assigned, no exception appeared because of any of them, but the "Cost" variable in:
private void DisplayDinnerPartyCost()
{
decimal Cost = dinnerParty.Cost;
label1.Text = Cost.ToString("c");
}
which is part of the same dinnerParty initialized instance and is suggested by Intellisense when I type the instance name, is throwing the exception. I read in microsoft's documentation that this could be caused even if the object was in fact initialized, if it is set to null, but the code that passes the value to the instance variable should be the one assigning the "null" value in this case. But since I didn't declare any nullable variables, how can this be happening?