Free mag vol1 | Page 230

CHAPTER 5  UNDERSTANDING ENCAPSULATION Allocating Objects with the new Keyword As shown in the previous code example, objects must be allocated into memory using the new keyword. If you do not make use of the new keyword and attempt to make use of your class variable in a subsequent code statement, you will receive a compiler error. For example, the following Main() method will not compile: static void Main(string[] args) { Console.WriteLine("***** Fun with Class Types *****\n"); // Error! Forgot to use 'new' to create object! Car myCar; myCar.petName = "Fred"; } To correctly create an object using the new keyword, you may define and allocate a Car object on a single line of code: static void Main(string[] args) { Console.WriteLine("***** Fun with Class Types *****\n"); Car myCar = new Car(); myCar.petName = "Fred"; } As an alternative, if you wish to define and allocate a class instance on separate lines of code, you may do so as follows: static void Main(string[] args) { Console.WriteLine("***** Fun with Class Types *****\n"); Car myCar; myCar = new Car(); myCar.petName = "Fred"; } Here, the first code statement simply declares a reference to a yet-to-be-determined Car object. It is not until you assign a reference to an object that this reference points to a valid object in memory. In any case, at this point we have a trivial class that defines a few points of data and some basic operations. To enhance the functionality of the current Car class, we need to understand the role of constructors. Understanding Constructors Given that objects have state (represented by the values of an object’s member variables), a programmer will typically want to assign relevant values to the object’s field data before use. Currently, the Car class demands that the petName and currSpeed fields be assigned on a field-by-field basis. For the current example, this is not too problematic, given that we have only two public data points. However, it is not uncommon for a class to have dozens of fields to contend with. Clearly, it would be undesirable to author 20 initialization statements to set 20 points of data! Thankfully, C# supports the use of constructors, which allow the state of an object to be established at the time of creation. A constructor is a special method of a class that is called indirectly when creating 166