Memory allocation of structure by new
operator in C#: heap or stack?
When a class is instantiated using the new
operator, memory is allocated on the heap. However, the behavior of the new
operator on structures depends on the specific scenario. Let’s explore the differences:
Constructor with parameters
When calling the parameterized constructor of a structure using new
, memory is allocated on the stack. This is similar to assigning a value to a local variable of a value type.
<code class="language-csharp">Guid local = new Guid("");</code>
The assigned IL code uses newobj
to allocate memory on the stack and initialize the value using the provided string.
Constructor without parameters
When calling the parameterless constructor of a structure using new
, the behavior depends on the context:
No memory will be allocated on the stack. Instead use initobj
to initialize an existing storage location (field or local variable). Value types are constructed in-place.
<code class="language-csharp">Guid field; ... field = new Guid();</code>
Allocate a temporary local variable on the stack and initialize it using initobj
. This value is then passed as a parameter to the method.
<code class="language-csharp">MethodTakingGuid(new Guid());</code>
No memory will be allocated on the stack. Value types are constructed directly at the storage location of the instance or static variable.
<code class="language-csharp">myInstance.GuidProperty = new Guid();</code>
Conclusion
The assignment behavior of thenew
operator when used with a structure depends on the context. For constructors with parameters, memory is always allocated on the stack. For parameterless constructors, memory may not be allocated on the stack, depending on the context. This behavior depends heavily on the IL directives generated by the compiler when converting C# code.
The above is the detailed content of Heap or Stack: Where Does `new` Allocate Structs in C#?. For more information, please follow other related articles on the PHP Chinese website!