CHAPTER 5 UNDERSTANDING ENCAPSULATION
Revisiting the static Keyword: Defining Static Properties
Earlier in this chapter, you examined the role of the static keyword. Now that you understand the use of
C# property syntax, we can formalize static properties. In the StaticDataAndMembers project, our
SavingsAccount class had two public static properties to get and set the interest rate. However, it would
be more standard to wrap this data point in a property. Thus, if you would rather not have two methods
to get and set the interest rate, you could instead define this following class property (note the use of the
static keyword):
// A simple savings account class.
class SavingsAccount
{
// Instance-level data.
public double currBalance;
// A static point of data.
private static double currInterestRate = 0.04;
// A static property.
public static double InterestRate
{
get { return currInterestRate; }
set { currInterestRate = value; }
}
...
}
If you want to use this property in place of the previous static methods, you could update your
Main() method as so:
// Print the current interest rate via property.
Console.WriteLine("Interest Rate is: {0}", SavingsAccount.InterestRate);
Understanding Automatic Properties
When you are building properties to encapsulate your data, it is common to find that the set scopes have
code to enforce business rules of your program. However, in some cases you may not need any
implementation logic beyond simply getting and setting the value. This means you can end up with a lot
of code looking like the following:
// A Car type using standard property
// syntax.
class Car
{
private string carName = "";
public string PetName
{
get { return carName; }
set { carName = value; }
}
}
199