C # boxing when casting in ValueType

I read about the ValueType class , and I wonder if, when something gets casted to ValueType, does it get a box? Example:

void DoSomething(ValueType valueType) { } DoSomething(5); 

Did you int represented by literal 5 when taken with the DoSomething method?

+4
source share
3 answers

Yes, he gets a box.

Think about it ... so that the value does not fall into the box, there must be some kind of general binary representation, which can be any type of value - including all built-in and any structure that you can define in the future.

Since such a binary representation does not exist, the value must be boxed.

Explanation:

When you call a method with parameters, the caller places the sequence of bits in a consistent place and in a consistent format, for example, int - 32 bits with negative numbers encoded as a 1-complement, double - 64 bits encoded in IEEE floating point, etc. .

You cannot have one method that can, with the exception of both unboxed int and double, because it would not know how many bits to read and how to decode them Χ₯

If you want the method to accept both parameters, you can give the function values ​​to the memory cell (the location itself has a known size and format, so the method knows how to decode it) and some metadata, so the method knows the actual type of value - wrapping the value with metadata and providing his memory location (surprise, surprise) "boxing"

So, anytime you pass a value using a parameter / variable / of what is not the exact type to which the system should indicate the value, or the receiver does not know a lot of memory that really uses the value, and how to decode this memory from a sequence of bits returns to a number or structure.

This applies only to value types, because reference types are always passed using a memory location (a memory location is called a "link" in .net).

+2
source

Yes it is, ValueType is a class (and thus a reference type that boxing will entail).

This question covers a similar basis:

Why is HasFlag Enum method needed for boxing?

+2
source

According to Mark Gravel in the MSDN article you are linking to.

it should be emphasized that although ValueType can be used to limit the value to value types, casting in ValueType (implicitly or explicitly) is still a boxing operation; only specific known value types ("DateTime", "int", etc.) can be processed directly as value types - ValueType itself is considered as a class (so boxing).

0
source

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


All Articles