Casting in C#

Main Principal

First of all, what is the main principal to cast ?

To answer this question I have make a simple diagram to illustrate this concept.
 
Now first I will explain what I mean by small and big types.
  • Small Type: Small types means that int, short, byte etc. These are all small data types in C#.

  • Big Type: Big types means that long, double, float. decimal etc. These are all big types in C#. 
So, the main thing is that whenever you are going to cast you first have to check what is the type of which you are casting and what is the type to which you are casting. If you are casting Small Types to Big Types then it is cast "Explicitly." But when you are casting Big Types to Small Types you have to cast Implicitly, because Big Types may contain more data than the max stored in the cast to which you are casting. Therefore the compiler will generate an error on compile time here.
 
Now, let's take an example here.
Converting "String" to "Numeric:"
  1. string s1 = "123";  
  2. int i3 = Convert.toInt32(s1);  
  3. string s2 = Convert.toString(i3);  
In this way you have to cast the data types from string to int. Now many times it happen that starter programmer in C# always faces an error during casting. So for them I am going to give you the Golden Principal.

Golden Principal

If data type is not of that type which can be cast then it gives error on runtime. Mainly not on compile time.

Boxing and Unboxing in C#

Boxing and Unboxing are the most important concepts in C#. I will try to explain them both.
  • Boxing

    Implicit conversion of value type to reference type is known as boxing. During the process of Boxing value type is being allocated on the heap other than stack.
     
  • Unboxing

    Explicit conversion of the same reference type back to value type is known as Unboxing. 
Example:
  1. int omer = 10; //Here int is created on the stack(Value Type)  
  2. object abc = omer; //Here Boxing is done. Int is created on the heap.  
  3. int omer2 = (int) abc;  
Points to Remember:
  • Sometimes boxing is necessary. But it should be avoided if possible because it consumes memory and also it slowsdown the process.

  • If you create  an integer with null value then Box it to some object type and try to Unbox, it will give an exception of NullReference because int was made but nothing was assigned to it.

  • If you create an int type variable box it into object type and then Inbox it into other type rather than int it will give InvalidCast exception.