Introduction
In C#, boxing and unboxing are necessary mechanisms to coordinate the different behaviors of value types and reference types. However, their purpose and use cases can be confusing to programmers. This guide explains why these concepts are critical and provides examples of their practical application.
The Importance of Packing and Unboxing
Boxing and unboxing allow C# to maintain a unified type system so that value types and reference types can interact and be processed consistently. Value types, such as short and int, store their data directly in variables. In contrast, reference types refer to the underlying object located elsewhere in memory.
To facilitate seamless interaction between these different data structures, boxing creates a wrapper object that contains the value type data so that it can be treated like a reference type. This makes it easy to store and manipulate value types in data structures designed for reference types.
Application scenarios of boxing and unboxing
A classic use case forboxing is using legacy collections, which only accept objects. These collections require boxing to store value types, as shown in the ArrayList example:
<code class="language-c#">short s = 25; object objshort = s; // 装箱</code>
In the modern generics era, the need for boxing has decreased. However, it is still crucial in certain scenarios:
<code class="language-c#">double e = 2.718281828459045; int ee = (int)e; // 从double到int的隐式转换(需要装箱)</code>
<code class="language-c#">double e = 2.718281828459045; object o = e; // 装箱 int ee = (int)(double)o; // 拆箱和显式转换</code>
Details that need attention
<code class="language-c#">double e = 2.718281828459045; object o1 = e; object o2 = e; Console.WriteLine(o1 == o2); // False</code>
<code class="language-c#">[struct|class] Point { ... } Point p = new Point(1, 1); object o = p; p.x = 2; Console.WriteLine(((Point)o).x); // 输出:1(如果为结构体)/ 2(如果为类)</code>
The above is the detailed content of C# Boxing and Unboxing: When and Why Do We Need Them?. For more information, please follow other related articles on the PHP Chinese website!