C# Casting Objects to Types

In .Net C# there are 3 ways to cast an object to a specific type. Implicit, Explicit and As. So what is the difference and why do I need to know?

Implicit Casting: this is where the system takes care of the casting for you with no extra code on your part. Implicit Casting happens when one type such as an Int is cast to a Double. Because an Integer is a whole number (having no decimal place) and a Double is a floating point number (having a decimal place) the conversion of lets say the Integer 5 to a double of 5.0 no information about the original Integer is lost (5 == 5.0). Because there is no loss of data the .Net system has no issue with making the conversion without warning you.

Code Example:
{
    int i = 5;
    double d = i;
}

Explicit Casting: in this case there is the possibility data may be lost in the conversion from one type to another and the system therefore will not take care of the cast itself, it requires you to make sure you know what you are doing and specifically tell it you are fine if data is lost in the conversion. Taking our previous example and just switching it around a Double 5.25 cast to a Integer of 5 causes a loss of data and thus a loss in precision because of this .Net requires you to verify its OK to dump the .25 from the Double.

Code Example:
{
    double d = 5.25;
    int i = (int)d;
}

Both of the above Casting options will return an exception if the casting is not possible for any reason at all, thus casting needs to take place within a Try-Catch block in order to handle these situations. If you don’t want to handle exceptions thrown by these 2 Casting options there is one more that is rarely used by developers, the AS keyword.

AS: the as keyword in .Net allows you to specify an Explicit Cast needs to happen but instead of an Exception being thrown if the cast is not possible a null value is simply returned. Now you only need to check if the value is null before continuing on with your code, if it is you then have the option to do some more processing to get the value you need. This limits the overhead and code that is needed to handle casting exceptions. Now there is a limitation to the use of the as operator, unfortunately it only performs reference conversions or boxing conversions.  It cannot perform conversions like user-defined conversions for these you will need to use Explicit Casting.

Code Example:
{
    double d = 5.25;
    int i = d as int;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s