C#: Even implicit conversions of types are not safe

Recently, I ran into an issue involving implicit type conversion. Before this case, I expected that compiler took care of any implicit conversions it allowed. Apparently, it is not true.

Let’s demonstrate it with a code. We have a variable of a type long that was set to its max value. Then we set another variable of a type double using the value of the first variable and implicit conversion.

We can see that these two variables are not equal. It happened because the long to double conversion causes an accuracy loss.

Okay. Now I need to decrease the double type variable by 1. Can I? No, I can’t.

Despite of subtructing 1d the values are still equal.

What the heck? How much we need to subtruct to make a difference? Let’s find out.

512 is the minimal difference in this case.


Not only explicit conversions can cause information loss!

Leave a Reply

Your email address will not be published. Required fields are marked *