In the DLR's LINQ Expressions, what is the difference between this:
Expression.Convert(SomeVariableExpression, typeof(T));
and this:
Expression.Unbox(SomeVariableExpression, typeof(T));
The documentation on this seems a bit sketchy.
And more to the point, which one of these is equivalent to this C# code:
(ClassA)InstanceOfClassB
Where ClassB has an implicit or explicit operator to cast to ClassA?
Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the common language runtime (CLR) boxes a value type, it wraps the value inside a System. Object instance and stores it on the managed heap. Unboxing extracts the value type from the object.
If I look up what unboxing and boxing does you see that the difference is that boxing allocates memory on the heap and unboxing moves a value-type variable to the stack. Accesing the stack is faster than the heap and therefore unboxing is in your case faster.
Boxing is the process of converting a value type to an object type. When the common language runtime boxes a value type, it wraps the value inside a system. object instance and stores it on the managed heap. Unboxing involves manually extracting the value type from the object.
Boxing and unboxing are important concepts in C#. The C# Type System contains three data types: Value Types (int, char, etc), Reference Types (object) and Pointer Types. Basically, Boxing converts a Value Type variable into a Reference Type variable, and Unboxing achieves the vice-versa.
The important thing Unbox is that it gives you the address of the boxed value. This ensures that you can call a method on the unboxed value. If that method mutates the value type then it's mutating the boxed version instead of a new copy. If you merely did Convert then you'd actually have made a copy of the boxed value type and then calling a method on it would mutate the copy and not the original value.
Well the main difference is that Epression.Unbox
is only needed for explicit unboxing of a value type off the heap. Expression.Convert
is the method you would want to use to hook into a user-defined conversion (whether implicit or explicit).
See Expression.Convert
:
If either expression.Type or type is a user-defined type that defines an implicit or explicit conversion operator, the
MethodInfo
that represents that operator is the implementing method.
and also:
If either expression.Type or type is a reference type and an explicit boxing, unboxing, or reference conversion exists from expression.Type to type, the implementing method is null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With