Jan 15, 2008

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 contructor 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...