Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

difference between boxing and unboxing in c#

/*
Boxing: The process of converting a value type instance to an object refrence.
When boxing happens CLR creates an object in the Heap and then creates a
a reference in the stack. So the value stroed in the heap along with an 
object refernce in the stack when boxing.
*/
//boxing:
int a = 10;
object obj = a;
// or 
object obj = 10;

/*
Unboxing: Is the opposition of boxing; Now when we cast an object to an integer
unboxing happens and the result is we get a new variable on the stack called
number with value of 10. 
*/
object obj = 10;
int number = (int) ob;
/*
Both boxing and unboxing have a performance penalty because of that extra 
object creation. And that's someting you should avoid if possible.
It's better to use a generic implemention of that class if it exists.
*/
Source by www.tutorialspoint.com #
 
PREVIOUS NEXT
Tagged: #difference #boxing #unboxing
ADD COMMENT
Topic
Name
7+5 =