Confusion over value types

I am confused at one point if I declare an instance of the Object class. It will be reserved on the heap, but when I declare, any instance of the primitive type obtained from System.ValueType, which is further obtained from the Object class, then part of it used by the Object class is also reserved on the stack.

Why is this, or is it so that the Object class does not take up space?

+3
source share
4 answers

Your reasoning is as follows:

  • System.Int32 obtained from System.Object
  • a derived type is always laid out in memory in the same way as its base type
  • therefore System.Int32 is laid out in memory in the same way as System.Object

Yes?

. . , ? , ?

UPDATE: , , .

, :

struct S { 
    public int x; 
    public override string ToString() { return "Hello!" + x; } 
}
...
S s = new S();
s.x = 0x00112233;
s.ToString();

? :

  • s.x.
  • 00 11 22 33 .
  • S.ToString, , .

-, s.x ? : , S, , . -, System.Object, . ", "; , .

+6

. Net: , . ?

, ,

, , .

, .

+3

, . : . , . System.ValueType System.Object, , : .

+2

, ValueType, -. , , .. .

The value type does not contain any additional data as an object. The object has a type identifier and a reference to the virtual method table, but the value type does not need any of them. Thus, Int32, for example, needs only four bytes for the actual data.

0
source

Source: https://habr.com/ru/post/1730593/


All Articles