I am looking at the Head First C # book, and I cannot understand why they used the following method of creating a property. It just seems incompatible with the convention, which I see throughout the book itself.
I understand that the template for creating properties is:
private int myVar; public int MyProperty { get { return myVar; } set { myVar = value; } }
Based on the above template, I would write my code as follows:
private decimal cost; public decimal Cost { get { cost = CalculateCostOfDecorations() + (CalculateCostOfBeveragesPerPerson() + CostOfFoodPerPerson) * NumberOfPeople; if (HealthyOption) { cost *= .95M; } return cost; } }
The book presents the following:
public decimal Cost { get { decimal totalCost = CalculateCostOfDecorations(); totalCost += (CalculateCostOfBeveragesPerPerson() + CostOfFoodPerPerson)*NumberOfPeople; if (HealthyOption) { totalCost *= .95M; } return totalCost; } }
Both codes work fine in the program. What is the best practice for creating such properties? Is the decimal totalCost inside the private property? If so, why is it not declared before creating the property?
Also, what's the point of creating two lines of code:
decimal totalCost = CalculateCostOfDecorations(); totalCost += (CalculateCostOfBeveragesPerPerson() + CostOfFoodPerPerson)*NumberOfPeople;
when you can accomplish the same thing by writing:
cost = CalculateCostOfDecorations() + (CalculateCostOfBeveragesPerPerson() + CostOfFoodPerPerson) * NumberOfPeople;
alegz source share