Web design portfolio - CHAPTER 3 C# LANGUAGE FUNDAMENTALS 71 Figure
CHAPTER 3 C# LANGUAGE FUNDAMENTALS 71 Figure 3-4. Simple constructor logic // Default constructor. public HelloClass() { Console.WriteLine(”Default ctor called!”); } // This custom constructor assigns state data // to a user-supplied value. public HelloClass (string msg) { Console.WriteLine(”Custom ctor called!”); userMessage = msg; } // Program entry point. public static int Main(string[] args) { // Call default constructor. HelloClass c1 = new HelloClass(); Console.WriteLine(”Value of userMessage: {0}n”, c1.userMessage); // Call parameterized constructor. HelloClass c2; c2 = new HelloClass(”Testing, 1, 2, 3″); Console.WriteLine(”Value of userMessage: {0}”, c2.userMessage); Console.ReadLine(); return 0; } } Note Technically speaking, when a type defines identically named members (including constructors) that differ only in the number of or type of parameters, the member in question is overloaded. Chapter 4 examines member overloading in detail. On examining the program s output, you can see that the default constructor has assigned the string field to its default value (empty), while the custom constructor has assigned the member data to the user-supplied value (see Figure 3-4). Note As soon as you define a custom constructor for a class type, the free default constructor is removed. If you wish to allow your object users to create an instance of your type using the default constructor, you will need to explicitly redefine it as in the preceding example.
If you are looking for affordable and reliable webhost to host and run your business application visit our ftp web hosting services.