Reputation: 5
So, each struct contains only values for value types, and/or references to reference types, which are of a known size.
So a demo struct:
struct demo
{
public int a = 7;
public string b = "test";
}
Would appear in memory (vaguely) like this:
struct demo
{
public int a = 00000000000000000000000000000111
public string b = 0x80484f0
}
And as a result, the struct is a value type that stores its contents in memory allocated on the stack.
I just needed to clarify this, as I'm not sure how else a struct can be a value type.
Upvotes: 0
Views: 1167
Reputation: 68660
Structs can be treated as value types (as in, they are copied when passed as arguments, and stored inline in an array, etc) because their size is known at the jitter's compile time (or, to be more precise, because their size can be inferred from a variable/field's declared type).
Whyyy is their size known at compile time? It's not because "each struct contains only values for value types, and/or references to reference types, which are of a known size." - the same could be said for reference types.
Their size is known at compile time because inheritance is disallowed. If you could subclass demo
, then a variable of type demo
could point to an object much larger than demo
.
Pretend for a second you could subclass structs, and remember that value types are stored inline in an array:
//4 bytes (1 integer)
public struct A {int x;}
//8 bytes (2 integers)
public struct B : A {int y;}
//An array of A's with enough space for 1 instance of A, that is, 4 bytes
A[] array = new A[1];
//instances of B don't fit in the array
a[0] = new B();
As Matthew points out in the comments, C++ allows you to do this, but field B.y
will be trimmed and lost.
Upvotes: 3
Reputation: 2956
As you say it stores its content on the stack and not on the heap. Thus it has to be a value type.
Upvotes: 0