6.3. Creating an object with the new operator

Like Java, there is only one way [4] to create a new object in C# – by using the new keyword.

[4] There are two ways to create a new object in C++. Car c(); (creates a Car object on the stack), and Car *c = new Car(); (creates a Car object on the heap). For the case of C#, you can only create an instance of an object using the new keyword. There is no way for the C# developer to control whether a new object is to be created on the heap or stack. All C# objects (reference types) are created on the heap, and all value types are created on the stack.

Like Java

Creating an object in C# is very similar to creating an object in Java. The following statement creates a new object object (object with a small 'o' is an alias for the System.Object class in C#):

new object();

The expression returns an object reference to the new object created on the heap, which you should assign to a variable of an appropriate reference type.

The following works fine:

object o = new object();

Unlike Java

In C#, the keyword new can also be used to create a method which hides a method of the same signature in a superclass. So, don't be surprised to see a method being declared like 'new public void DoSomething();' in C#. This is called 'name hiding', or in this case 'method hiding'.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.44.53