clamp
clamp

Reputation: 34006

C# does new on structs ALWAYS allocate on the stack?

just wondering if i dont have to care about garbage collection if i allocate structs with new.

what if they are later casted to an object?

public object Func()
{
  SMyStruct bla = new SMyStruct();

  return bla;
}

Upvotes: 1

Views: 994

Answers (1)

Kirill Bestemyanov
Kirill Bestemyanov

Reputation: 11964

It will be "boxed" and will be allocated on Heap.

Richter CLR via C#:

It's possible to convert value type to a reference type by using mechanism called boxing. Internally, here's what heppens when an instance of valuetype is boxed:

  1. Memory is allocated from the managed heap. The amount of memory allocated is the size required by the value type's fields plus the two additional overhead members (the type object pointer and the sync block index) required by all objects on the managed heap.

  2. The value type's fields are copied to the newly allocated heap memory.

  3. The address of the object is returned. This address is now a reference to an object; the value type is now a reference type.

Upvotes: 1

Related Questions