Free mag vol1 | Page 233

CHAPTER 5  UNDERSTANDING ENCAPSULATION The Default Constructor Revisited As you have just learned, all classes are provided with a free default constructor. Thus, if you insert a new class into your current project named Motorcycle, defined like so: class Motorcycle { public void PopAWheely() { Console.WriteLine("Yeeeeeee Haaaaaeewww!"); } } you are able to create an instance of the Motorcycle type via the default constructor out of the box: static void Main(string[] args) { Console.WriteLine("***** Fun with Class Types *****\n"); Motorcycle mc = new Motorcycle(); mc.PopAWheely(); ... } However, as soon as you define a custom constructor with any number of parameters, the default constructor is silently removed from the class and is no longer available! Think of it this way: if you do not define a custom constructor, the C# compiler grants you a default in order to allow the object user to allocate an instance of your type with field data set to the correct default values. However, when you define a unique constructor, the compiler assumes you have taken matters into your own hands. Therefore, if you wish to allow the object user to create an instance of your type with the default constructor, as well as your custom constructor, you must explicitly redefine the default. To this end, understand that in a vast majority of cases, the implementation of the default constructor of a class is intentionally empty, as all you require is the ability to create an object with default values. Consider the following update to the Motorcycle class: class Motorcycle { public int driverIntensity; public void PopAWheely() { for (int i = 0; i <= driverIntensity; i++) { Console.WriteLine("Yeeeeeee Haaaaaeewww!"); } } // Put back the default constructor, which will // set all data members to default vaules. public Motorcycle() {} // Our custom constructor. public Motorcycle(int intensity) { 169