CSharp - Implicit Casting vs. Explicit Casting


With casting, we can convert one data type to another.

There are two types of casting: implicit and explicit.

Implicit casting is automatic.

We need cast operators for explicit casting.

In implicit casting, the conversion is small to large integral types, or derived types to base types.

int a = 1;
//Implicit casting
double b = a;//ok

With explicit casting, consider the reverse case. If you write something like this:

int c = b;//Error

So, you need to write something like this:

//Explicit casting
int c = (int)b;//Ok

You use casting if one type is convertible to another type; that is, you cannot assign a string to an integer.

Implicit casting is type safe.

There is no data loss during the implicit casting since we go from a small container to a large container.

Explicit conversion is not type safe because the data is moving from a large container to a small container.

Related Topic