The new operator

The new operator allocates space for objects on the heap or stack and then calls the object’s constructor. In addition, the new operator sets all object’s member values to their default value.

Example – Calling the new operator on a class

newOperatorCode1

What happens when the new operator is called on a class ( reference type ) ? 
1. Space is allocated on the heap for MyClass
2. The value of MyInt is set to 0 ( which is the default value for System.Int32 value type )
3. MyObject remains uninitialized or  null ( which is the default value for System.Object reference type )
4. The value of the MyClass reference on the stack is set to the heap memory location on the stack

Example – Calling the new operator on a struct

newStruct

What happens when the new operator is called on a struct ( value type ) ?
1. 2 variables are added to the stack – MyInt and MyDouble
2. The value of MyInt is set to 0 ( which is the default value for System.Int32 value type )
3. The value of MyDouble is set to 0 ( which is the default value for System.Double value type )

Posted in Uncategorized

Leave a comment

Design a site like this with WordPress.com
Get started