Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts


Understanding Boxing and Unboxing in C#

Boxing is the process of converting a value type to the type object. Unboxing extracts the value type from the object. Let’s see how boxing and unboxing works.



Boxing: This is an implicit process. That means developer doesn’t need do any type casting.
See below line of code:
int boxingInteger = 123;

This will create a block on stack memory area for variable of type int.

Stack

boxingInteger


Now see below line of code:
object myObject = boxingInteger; // boxing

This is the step where boxing is occurring. When above line is executed, two things will occur at backend.
1.       An object will be created on heap area that will hold value of boxingInteger.
2.       Reference type myObject will get created that will point to memory area allocate in above step.
Note: It will not affect boxingInteger variable on stack. The entry on stack will be there after boxing.



Unboxing: It is reversing of boxing. But it is explicit. Developer need to do type casting explicitly. It will type case object on heap to the value type.
From above example,
int unboxingInteger = (int)myObject;  // unboxing

It will convert value at my object from object type to type int and it will assign this value to variable unboxingInteger which will get created on stack area.

Stack

unboxingInteger
boxingInteger



Myth about Boxing:
Myth: Below code does boxing.
string sMyString = “Box”;
object myObject =   sMyString

Truth: string is not a value type variable. It is a reference type variable. So when you are assigning sMyString to myObject, you are just copying reference. There is no value type to object type conversion is happening here.


To get depth knowledge check this:
http://www.codeguru.com/Csharp/Csharp/cs_syntax/article.php/c5883



Update value against the same key in hashtable using C# code

There are two ways you can add data to your Hashtable as shown below:
ohashtable[Key1] = Value1;
ohashtable[Key2] =  Value2;
ohashtable[Key3] = Value3;

Or like this:
ohashtable.Add(Key1, Value1);
ohashtable.Add(Key2, Value2);
ohashtable.Add(Key3, Value3);

There is a difference between these two ways. 
Using Add method, you can't have update the value against existing Key. But you can, if you use the square brackets. 

For example,
ohashtable.Add(Key1, Value1);
ohashtable.Add(Key1, Value2); //this will throw exception at run time

Whereas,
ohashtable[Key1] = Value1;
ohashtable[Key1] =  Value2; // this will allow the entry in hashtable
It won't add a new key but will update the value against the existing key.