📜 ⬆️ ⬇️

Interesting moments in C # (boxing unboxing)

In this article we will briefly go through the little-known features of boxing / unboxing.

Previous article on foreach
Previous article on Array

A typical question on the interview about packing and unpacking is as follows - "What will happen when you run this code, and if it does not work then how to fix it?".
')
Test code:
object box = (int)42; long unbox = (long)box; 

The answer may be the following - “When unpacking, the first operator is not a type conversion, but a type unpacking; accordingly, it must correspond to the type of the value in the packed form.”.

Correct answer:
 object box = (int)42; long unbox = (long)(int)box; 

This is usually considered the correct answer, but it is not quite so ...

Unboxing and Enum


Imagine the surprise of a person when you write him another correct version.

The second correct answer is:
 public enum EnumType { None } ... object box = (int)42; long unbox = (long)(EnumType)box; 

Let me remind you that enum is not a fundamental type and does not inherit it, it is a structure containing a fundamental type (basic). This suggests that .NET has explicit support for such unpacking. It is also easy to verify that decompression does not use explicit and implicit conversion operators, and the IConvertible interface and its type cannot be deployed from someone else's type.
When unpacking enum, its base type is used and the next unpacking will not work.

Wrong option:
 public enum EnumType : short { None } ... object box = (int)42; long unbox = (long)(EnumType)box; 

Unpacking for enum'ov weakened extremely.

Extract the int from the enum:
 public enum EnumType { None } ... object box = EnumType.None; long unbox = (long)(int)box; 

Extract one enum from the other:
 public enum EnumType { None } public enum EnumType2 { None } ... object box = EnumType.None; long unbox = (long)(EnumType2)box; 

Unboxing and Nullable


Unpacking also supports Nullable types, which seems more logical.

Unpacking Nullable type from the usual:
 object box = (int)42; long unbox = (long)(int?)box; 

Unpacking the usual type of nullable:
 object box = (int?)42; long unbox = (long)(int)box; 

Let me remind you that Nullable is a structure with one generalized value type and is intended for storing data and a data presence flag. This suggests that C # has explicit support for unpacking Nullable types. In the new versions of C # for this structure appeared alias "?".

Nullable:
 public struct Nullable<T> where T : struct { public bool HasValue { get; } public T Value { get; } } 

Equivalent records:
 Nullable<int> value; int? value; 

Thank you all for your attention!

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


All Articles