Free mag vol1 | Page 265

CHAPTER 5  UNDERSTANDING ENCAPSULATION Interacting with Automatic Properties Because the compiler will define the private backing field at compile time, the class defining automatic properties will always need to use property syntax to get and set the underlying value. This is important to note because many programmers make direct use of the private fields within a class definition, which is not possible in this case. For example, if the Car class were to provide a DisplayStats() method, it would need to implement this method using the property name: class Car { // Automatic properties! public string PetName { get; set; } public int Speed { get; set; } public string Color { get; set; } } public void DisplayStats() { Console.WriteLine("Car Name: {0}", PetName); Console.WriteLine("Speed: {0}", Speed); Console.WriteLine("Color: {0}", Color); } When you are using an object defined with automatic properties, you will be able to assign and obtain the values using the expected property syntax: static void Main(string[] args) { Console.WriteLine("***** Fun with Automatic Properties *****\n"); Car c = new Car(); c.PetName = "Frank"; c.Speed = 55; c.Color = "Red"; Console.WriteLine("Your car is named {0}? That's odd...", c.PetName); c.DisplayStats(); } Console.ReadLine(); Regarding Automatic Properties and Default Values When you use automatic properties to encapsulate numerical or Boolean data, you are able to use the autogenerated type properties straightaway within your code base, as the hidden backing fields will be assigned a safe default value that can be used directly. However, be very aware that if you use automatic property syntax to wrap another class variable, the hidden private reference type will also be set to a default value of null. Consider the following new class named Garage, which makes use of two automatic properties (of course, a real garage class would maintain a collection of Car objects; however, we will ignore that detail for the time being): 201