Saturday 10 May 2014

Essence of the "new" Keyword - Name Three Things It Does

What does the new keyword in C# actually do?

It calculates the TOTAL number of bytes the object needs (including its instance members) and then allocates the relevant amount of memory.

There are some additional bookkeeping items though.

For one thing, the type object pointer is initialised. This is a pointer to the object's description needed to perform virtual function invocation (i.e. to allow dynamic binding). The description is obtained using GetType which is nonvirtual to prevent object type spoofing.

The second thing is the sync block index, which is an index into a table of synchronisation blocks.

Then the instance constructor is called, passing in arguments specified in the new statement. Most compilers will then call the base class constructors all the way to System.Object.

No comments: