Implicit and explicit conversion in c#

Implicit conversion done by compiler when there is no loss of data while converting and not possibility of throwing exception during conversion.

When we convert int to float there is no any data loss and not any chance of throwing an exception, so in this case compiler uses implicit conversion

But take vice-versa we convert float value to int, fractional part is loss and also there is chance of throwing and exception like overflow exception. In this case we use explicit conversion

Implicit conversion:

int i = 10;

float f = i;

Explicit Conversion:

Explicit conversion can be done by using type casting.

float fi = 123.34f;

int ift = (int)fi;

Another way of type casting is like below:

float fi = 123.34f;

int ift = Convert.ToInt32(fi);



Post a Comment

0 Comments