CHAPTER 5 UNDERSTANDING ENCAPSULATION
class Garage
{
// The hidden int backing field is set to zero!
public int NumberOfCars { get; set; }
}
// The hidden Car backing field is set to null!
public Car MyAuto { get; set; }
Given C#’s default values for field data, you would be able to print out the value of NumberOfCars as is
(as it is automatically assigned the value of zero), but if you directly invoke MyAuto, you will receive a
“null reference exception” at runtime, as the Car member variable used in the background has not been
assigned to a new object:
static void Main(string[] args)
{
...
Garage g = new Garage();
// OK, prints default value of zero.
Console.WriteLine("Number of Cars: {0}", g.NumberOfCars);
// Runtime error! Backing field is currently null!
Console.WriteLine(g.MyAuto.PetName);
Console.ReadLine();
}
Given that the private backing fields are created at compile time, you will be unable to make use of
C# field initialization syntax to allocate the reference type directly with the new keyword. Therefore, this
work will need to be done with class constructors to ensure the object comes to life in a safe manner. For
example:
class Garage
{
// The hidden backing field is set to zero!
public int NumberOfCars { get; set; }
// The hidden backing field is set to null!
public Car MyAuto { get; set; }
}
202
// Must use constructors to override default
// values assigned to hidden backing fields.
public Garage()
{
MyAuto = new Car();
NumberOfCars = 1;
}
public Garage(Car car, int number)
{
MyAuto = car;
NumberOfCars = number;
}