12.6 In C++, the code "MyClass ht;" creates an object ht on the stack frame. But in C#, this same code compiles, but gives a runtime error. Why?


MyClass ht; does not create any object. Instead, it creates a variable (a reference) of type MyClass, and sets its value to null. No object is created. To create an object, you need to explicitly call the class constructor with a new.

     
     MyClass ht = new MyClass();


You can also use ht to refer to an instance of MyClass that has been created (with a new) at some other point in your code.

     
     MyClass myClass = new MyClass();
     ......
     MyClass ht;
     ......
     ht = myClass; // both ht and myClass are references to the same object...


© 2001-2010 Copyright Syncfusion Inc. All rights reserved.  |  Privacy Policy  |  Contact  |  Sitemap