Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I implicitly convert a double to an int?

You can implicitly convert an int to a double: double x = 5;

You can explicitly convert an int to a double: double x = (double) 5;

You can explicitly convert a double to an int: int x = (int) 5.0;

Why can't you implicitly convert a double to an int?: int x = 5.0;

like image 933
Evorlor Avatar asked Nov 27 '22 23:11

Evorlor


2 Answers

The range of double is wider than int. That's why you need explicit cast. Because of the same reason you can't implicitly cast from long to int:

long l = 234;
int x = l; // error
like image 154
Selman Genç Avatar answered Nov 29 '22 12:11

Selman Genç


Implicit casting is only available when you're guaranteed that a loss of data will not occur as a result of a conversion. So you could cast an integer to a double, or an integer to a long data type. Casting from a double to an integer however, runs the risk of you losing data.

Console.WriteLine ((int)5.5);  
// Output > 5

This is why Microsoft didn't write an implicit cast for this specific conversion. The .NET framework instead forces you to use an explicit cast to ensure that you're making an informed decision by explicitly casting from one type to another.

The implicit keyword is used to declare an implicit user-defined type conversion operator. Use it to enable implicit conversions between a user-defined type and another type, if the conversion is guaranteed not to cause a loss of data.

Source > MSDN

like image 20
Aydin Avatar answered Nov 29 '22 13:11

Aydin