Junior — Middle
Selgitage erinevusi väärtuste pakkimise ja lahtipakkimise protsesside vahel programmeerimiskeeles.
sobes.tech AI
Vastus AI-lt
In C#, boxing is the process of converting a value type (e.g., int, bool) into an object of type System.Object or into the interface it implements. During boxing, the value is copied to the managed heap and wrapped in an object.
Unboxing is the reverse process, where an object containing a boxed value is converted back to the original value type. During unboxing, a type check is performed, and the value is copied from the object to a value-type variable.
Example:
int x = 123; // value type
object obj = x; // boxing
int y = (int)obj; // unboxing
Boxing and unboxing affect performance because they require memory allocation and data copying. Therefore, they should be minimized, especially in critical parts of the code.