Boxing / Unboxing in .NET

The big deal seems to be made from boxing and unboxing. Are there so many uses of the object type that we really need to know about this?

What are very practical cases when boxing / unpacking is required?

+3
source share
2 answers

It depends.

I think that at present he has fewer problems than before. If you make sure that you use shared collections inside the frame (that is: use List<T>instead ArrayList), then this probably will not be a serious problem for you.

.NET 1.1, object, . .NET 1.1 , int, , , , , , . , . , , .


:

.NET 1.1 - ArrayList:

ArrayList list = new ArrayList();

list.Add(1); // These are all boxing - the integer is getting boxed to add
list.Add(2);   
list.Add(3);

foreach(object item in list)
{
    // Unboxing required here:
    int value = (int)item;
    Console.WriteLine(value);
}

, , , unbox :

foreach(object item in list)
{
    // Trying to unboxing into the wrong type here...
    // This will raise an exception at runtime, but compile fine!
    double value = (double)item;
    Console.WriteLine(value);
}

.NET 2 :

List<int> list = new List<int>();


list.Add(1); // No boxing now, since it using generics!
list.Add(2);   
list.Add(3);

foreach(int value in list) // This is now typesafe, and doesn't cause an unboxing operation
{
    Console.WriteLine(value);
}

. , Reflection object, , , FieldInfo.SetValue.

+13

/ , (, , ), ( .) , , . - . .

, .NET 1.0/1.1, ; , . , , .

+2

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


All Articles