Business web site - CHAPTER 3 70 C# LANGUAGE FUNDAMENTALS using
CHAPTER 3 70 C# LANGUAGE FUNDAMENTALS using System; class HelloClass { public static int Main(string[] args) { // Error! Use of unassigned local variable! Must use ‘new’. HelloClass c1; c1.SomeMethod(); … } } To illustrate the proper procedures for object creation, observe the following update: using System; class HelloClass { public static int Main(string[] args) { // You can declare and create a new object in a single line… HelloClass c1 = new HelloClass(); // …or break declaration and creation into two lines. HelloClass c2; c2 = new HelloClass(); … } } The new keyword is in charge of calculating the correct number of bytes for the specified object and acquiring sufficient memory from the managed heap. Here, you have allocated two objects of the HelloClass class type. Understand that C# object variables are really a reference to the object in memory, not the actual object itself. Thus, in this light, c1 and c2 each reference a unique HelloClass object allocated on the managed heap. The Role of Constructors The previous HelloClass objects have been constructed using the default constructor, which by definition never takes arguments. Every C# class is automatically provided with a free default constructor, which you may redefine if need be. The default constructor ensures that all member data is set to an appropriate default value (this behavior is true for all constructors). Contrast this to C++, where uninitialized state data points to garbage (sometimes the little things mean a lot). Typically, classes provide additional constructors beyond the default. In doing so, you provide the object user with a simple way to initialize the state of an object at the time of creation. Like in Java and C++, in C# constructors are named identically to the class they are constructing, and they never provide a return value (not even void). Here is the HelloClass type once again, with a custom constructor, a redefined default constructor, and a point of public string data: // HelloClass, with constructors. using System; class HelloClass { // A point of state data. public string userMessage;
Note: In case you are looking for affordable and reliable webhost to host and run your j2ee application check Vision J2ee Web Hosting services.