Boxing for the intended purpose of ValueType?

If I assign a simple value type (e.g. int) to an attribute of type ValueType, then this value is then put into a box?

For example, if I do this:

int i = 4; ValueType test = i; 

Will a value be entered?

+2
source share
3 answers

Yes it will. This is because each type takes up a constant amount of memory at runtime ( int takes, for example, 4 bytes). The structure will take up as much space as is required to place all the fields in memory.

Since you can store any type of value in ValueType , and since ValueType must be exactly the same size as the type you assign to test , the ValueType type is actually a reference type.

Consider:

 int a = 0; long b = 1; ValueType test; test = a; test = b; 

This is absolutely correct code. test should occupy a fixed size on the stack, and a and b be different sizes. Hopefully this explains why a ValueType cannot be a value type. (This is due to why you cannot deduce value types.)

+6
source

Yes, it will be in a box - ValueType is a reference type (class), quite confusing :) It is just a type from which each type of value "inherits" (directly in the case of structures and indirectly in the case of enumerations).

Boxing occurs at any time when you assign a value of a value type to a variable of a reference type, including object , ValueType , Enum and any interfaces. (This also happens when using a value of type value as an argument, where the parameter is one of these types, etc.)

+4
source

ValueType is a reference type. IL generated in this assignment actually blocks the structure.

Here is an example command line when assigning to an object:

 void Main() { object o = 1; Console.Write(o); } IL_0000: ldc.i4.1 IL_0001: box System.Int32 IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call System.Console.Write 

And when assigning ValueType :

 void Main() { ValueType o = 1; Console.Write(o); } IL_0000: ldc.i4.1 IL_0001: box System.Int32 IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call System.Console.Write 
0
source

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


All Articles