I am going through the Head First C# book and I can't figure out why they used the following way to create a property. It just seems inconsistent with the convention I'm seeing everywhere else and in the book itself too.
I understand that the pattern for creating properties is:
private int myVar;
public int MyProperty
{
get { return myVar; }
set { myVar = value; }
}
Based on the above pattern I would have written my code like this:
private decimal cost;
public decimal Cost
{
get
{
cost = CalculateCostOfDecorations() + (CalculateCostOfBeveragesPerPerson() + CostOfFoodPerPerson) * NumberOfPeople;
if (HealthyOption)
{
cost *= .95M;
}
return cost;
}
}
In the book it is presented like the following:
public decimal Cost
{
get
{
decimal totalCost = CalculateCostOfDecorations();
totalCost += (CalculateCostOfBeveragesPerPerson() + CostOfFoodPerPerson)*NumberOfPeople;
if (HealthyOption)
{
totalCost *= .95M;
}
return totalCost;
}
}
Both codes work just fine in the program. What is the best practice to create such properties? Is the decimal totalCost inside the property private? If so, why is it not declared before creating the property instead?
Also, what is the point of creating two lines of code:
decimal totalCost = CalculateCostOfDecorations();
totalCost += (CalculateCostOfBeveragesPerPerson() + CostOfFoodPerPerson)*NumberOfPeople;
when you can accomplish the exact same thing by writing:
cost = CalculateCostOfDecorations() + (CalculateCostOfBeveragesPerPerson() + CostOfFoodPerPerson) * NumberOfPeople;
cost
as a backing field because it is recalculated each time the getter is called. ThetotalCost
is a local variable, it doesn't exist outside the scope of the getter, its temporary for holding the calculation result until the value is returned. Usingdecimal
with the same variable name twice is a syntax error and will give you an error when you try to compile. – Lavalley