Monday, April 30, 2012

UnBoxing Conversions


UnBoxing is the explicit conversion from a reference type to a value type or from an
interface type to a value type that implements the interface.
When unboxing occurs, memory is copied from the managed heap to the stack. For an
unboxing conversion to a given value type to succeed at run time, the value of the source
argument must be a reference to an object that was previously created by boxing a value
of that value type otherwise an exception is thrown.


Example:
int n = 10;
int j;
Object obj;
obj = n;
j = (int)obj;



Explanation:
In the above code segment, another integer variable j is declared. The last statement
performs explicit conversion of object-type to value-type i.e. integer.
Boxing and UnBoxing have performance implications. Every time a value type is boxed,
a new reference type is created and the value type is copied onto the managed heap.
Depending on the size of the value type and the number of times value types are boxed
and unboxed, the CLR can spend a lot of CPU cycles just doing these conversions.
It is recommended to perform boxing and unboxing in a scenario where you have to pass
a value parameter multiple times to a method that accepts a reference parameter. In such
a case, it is advantageous to box the value parameter once before passing it multiple times
to methods that accept reference methods.


No comments:

Using Authorization with Swagger in ASP.NET Core

 Create Solution like below LoginModel.cs using System.ComponentModel.DataAnnotations; namespace UsingAuthorizationWithSwagger.Models {     ...