Search code examples
c#structheap-memoryvalue-type

How value types differ from each other?


if size of two different structs are exactly same, how do they differ when they are being executed? there should be a little information about what type they are shouldn't be?

In stack, I could imagine this information can be stored without allocating extra memory (in some place like header or something). how ever In Heap, when struct is not boxed, does it allocate extra memory for its type information?

for example how AnInt differs from int, or other alike structs.

struct AnInt
{ 
    int _int;
}

Solution

  • Bear in mind that there's no inheritance for value types. This means that the variables for value types are enough to encode the type information. You know you're dealing with an AnInt because you're accessing it via an AnInt field, property or local variable.

    In turn, this means that during compilation, the compiler knows exactly what methods, etc are the ones to call on that variable, and (again, because no inheritance) there's no virtual dispatch to consider.