Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the "new " keyword in .net actually do?

I know that the new keyword is calling the class constructor but at which stage do we allocate memory for the class?

In my understanding it should correspond to the GCHandle.Alloc(Object) method but I'm unable to find the connection.

like image 991
Sergey Kravchenko Avatar asked Jul 16 '12 13:07

Sergey Kravchenko


People also ask

What does new keyword do C#?

It is used to create objects and invoke a constructor. Using the "new" operator, we can create an object or instantiate an object, in other words with the "new" operator we can invoke a constructor.

What is the new keyword used for?

New keyword in JavaScript is used to create an instance of an object that has a constructor function. On calling the constructor function with 'new' operator, the following actions are taken: A new empty object is created.

Why do we need new in C#?

The new operator is used to create an object or instantiate an object. Here in the example an object is created for the class using the new.

What is the use of new keyword in VB net?

The New keyword is also used in type parameter lists to specify that the supplied type must expose an accessible parameterless constructor. For more information about type parameters and constraints, see Type List. To create a constructor procedure for a class, set the name of a Sub procedure to the New keyword.


1 Answers

The new operator is implemented in the CLR. It allocates memory from the garbage collected heap and executes the class constructor.

GCHandle.Alloc() is not the same. That takes advantage of a separate mechanism in the GC to create references to objects, references that are stored in a separate table and scanned in addition to object references found normally during a garbage collection. You must pass Alloc() an existing object reference, it adds another. Useful to create weak and pinning references and a mechanism to allow unmanaged code to store a reference to a managed object and keep it alive. The gcroot<> template class in C++/CLI takes advantage of it.

like image 152
Hans Passant Avatar answered Oct 20 '22 18:10

Hans Passant