implicit & explicit conversion in C#


In C#, we often need to convert one type of data into another type. A simple example is like converting an integer value into a double (or may be even to string, when assigning to a textbox) and vice-versa. This type of conversion may or may not require us to specify the source and the target data type So this can be done in two different ways :

Implicit conversion : As the name suggests, implicit conversion is, when we need NOT to specify the target data type, to which the source data type is to be converted. This type of conversion prevents any lost in data, as the target data type is always a kind of super set of the source data type and compiler knows that the conversion will not cause any loss of data.

For example, storing any integer type value into a larger data type like double or assigning a derived class instance to a base class, as the derived class is always a subset of base class. This type of conversion does not requires us to specify any target data type for the source and there is no loss of data.

Explicit Conversion : On the other hand, explicit conversion requires us to specify the target data type, to which the source is to be converted and there can be loss of data in the conversion. Explicit conversion is done by specifying a casting operator which is nothing but the target data type to which we want to convert the source data into. This is known as Cast. From MSDN :

A cast is a way of explicitly informing the compiler that you intend to make the conversion and that you are aware that data loss might occur

In such kind of conversion, compiler gives a compile time error if we do not  specify any target data type. Even if we explicitly perform the casting, there are chances that there can be run-time exceptions, due to invalid casting operation. For example, converting a string to an integer using the Convert method. This would compile, but there will be run time exception.

 So this is about the concept of type conversion in C#.

Advertisements

About Jasminder

.Net developer and blogger by profession, keen to learn new technologies, love nature, music and cricket.
This entry was posted in C#. Bookmark the permalink.

I have a suggestion..

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s