tvolf
tvolf

Reputation: 309

Why C# does not require explicit casting for convert Long To Double?

At first, sorry for my bad english. I have fragment of code:

long x = 9223372036854775807L;
double f = x;
Console.WriteLine(x);           
Console.WriteLine(f);

Output is:

9223372036854775807
9,22337203685478E+18

I'm not getting any errors while compiling and execution this code. We have a loss of precision while converting Long to Double. Why C# does not require explicit casting in that case ?

Thanks all.

Upvotes: 12

Views: 17590

Answers (2)

Rawad Trablsy
Rawad Trablsy

Reputation: 39

try this

long x = 9223372036854775807L;
decimal f = x;
Console.WriteLine(x);
Console.WriteLine(f);

Upvotes: 0

John Koerner
John Koerner

Reputation: 38077

The language has some implicit conversion built into it.

The following table is from the documentation, which is why you are allowed to assign the value without an explicit cast or conversion:

From        To
===============================================================================
sbyte       short , int, long, float, double, or decimal
byte        short , ushort, int, uint, long, ulong, float, double, or decimal
short       int , long, float, double, or decimal
ushort      int , uint, long, ulong, float, double, or decimal
int         long , float, double, or decimal
uint        long , ulong, float, double, or decimal
long        float , double, or decimal
char        ushort , int, uint, long, ulong, float, double, or decimal
float       double
ulong       float , double, or decimal

And in the documentation it states (emphasis mine):

Precision but not magnitude might be lost in the conversions from int, uint, long, or ulong to float and from long or ulong to double.

Upvotes: 15

Related Questions