Monday, April 29, 2013

Casting and Type Conversions in C#


Casting or type conversion is a method by which a data is converted from one data type to another. There are 2 types of type casting.

Implicit type casting.
Implicit casts are the casts that do not require any special syntax and it’s done by complier by its own. There is not data loss in implicit conversion. However there are some rules by which are followed by complier for performing the casting.

a. Derived class to base class.

If we try to assign a value from derived class to a base class it will work. That is because a derived class always is-a base class. Also, from a memory perspective,  a derive class object contain the base class object in it and it can be access by a base class object without any problem. For example following code work without any problem..

class Base
{

}
class Derived : Base

}
class Program
{
    static void Main(string[] args)
    {
        Derived d = new Derived();
        Base b = d;     // object b can access base class part of object d
    }
}

b. Primitive types.
Since the complier has intimate knowledge about the primitive types it’s apply some special rules of type casting. The things here to remember is it allows the narrow type to be assign to wider type. Since this there is no chance to data loss this is consider as safe typing and hence no cast operator is expected from programmer.

static void TestCasting()
{
    int i = 10;
    float f = 0;
    f = i;  // An implicit conversion, no data will be lost.
 
}


Explicit type casting.
In explicit type casting there is possibilities type data loss hence it is essential for programmer to mention this to compiler by special syntax.

a. Base class to derive class.
C# compiler require the programmer to explicitly cast an object of a base type to an object of its derived type as there is possibility of failure at run time.

Base b = new Base();
Derived d = (Derived)b;

b. Primitive types.
Programmer also needs to explicitly mention the cast in case he needs to cast a wider type to narrow type. The reason here is these type of conversion might result in data loss and hence it unsafe.

static void TestCasting()
{
    int i = 0;
    float f = 0.5F;
    i = (int)f;  // An explicit conversion. Information will be lost.
}

2 comments: