Unsafe.Unbox<T>(Object) Method
Definition
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Returns a mutable ref
to a boxed value.
public:
generic <typename T>
where T : value class static T % Unbox(System::Object ^ box);
public static ref T Unbox<T> (object box) where T : struct;
static member Unbox : obj -> 'T (requires 'T : struct)
Public Shared Function Unbox(Of T As Structure) (box As Object) As T
Type Parameters
- T
The type to be unboxed.
Parameters
- box
- Object
The value to unbox.
Returns
A mutable ref
to the boxed value box
.
Exceptions
box
is null
, and T
is a non-nullable value type.
T
cannot be found.
Remarks
The Unbox<T>
method is simply a wrapper for the IL unbox instruction. It is useful as a performance optimization. Whenever an API that takes an Object needs to be called repeatedly with different values of a value type, the same box object can be reused rather than a new one created each time.
The Unbox<T>
method has an important usage constraint that is not enforced by language compilers and that is the responsibility of the caller. The IL unbox
instruction returns a controlled-mutability managed pointer. Because .NET and .NET language compilers cannot represent this constraint, the Unbox<T>
method returns a normal mutable ref T
. However developers must not mutate the returned reference unless they are certain that T
is a mutable struct type. For example, because the numeric primitives such as Int32 are not mutable struct types, the following code is not suppported:
// The following line is NOT SUPPORTED.
Unsafe.Unbox<int>(obj) = 30;
In contrast, a type such as Point is a mutable struct with public property setters, so mutating the boxed value by calling the property setters is supported:
// The following lines are legal and supported.
Unsafe.Unbox<System.Drawing.Point>(obj).X = 50;
Unsafe.Unbox<System.Drawing.Point>(obj).Y = 70;
However, replacing the entire reference wholesale is not supported, even if the reference is to a mutable struct type.
// Resetting the reference to default(T) is NOT SUPPORTED.
Unsafe.Unbox<System.Drawing.Point>(obj) = default(System.Drawing.Point);
// Setting the reference to a completely new value is NOT SUPPORTED.
Unsafe.Unbox<System.Drawing.Point>(obj) = new System.Drawing.Point(50, 70);
For more information, including detailed discussion of the usage constraints of this instruction, see sections III.1.8.1.2.2 ("Controlled-mutability managed pointers") and III.4.32 ("unbox -- convert boxed value type to its raw form") in ECMA-335: Common Language Infrastructure (CLI).