Wednesday, April 11, 2012

Difference between integer Cast and Convert in C#

Technically speaking, Int64 and Long are equivalent in .NET
But if you convert one value into Int64, and cast the same value in Long the result is different.

Lets take one example:

(Long)27.5 returns 27
Whereas, Convert.ToInt64(27.5) returns 28
(Int64)27.5 returns 27

This is because, in C# (as well as in Java, and C++), the integer cast operation truncates - and so (Long)27.5 returns 27, whereas Convert has its own logic, and it rounds rather than truncating and so it returns 28.

No comments:

Post a Comment

Thanks for visiting my blog.
However, if this helped you in any way, please take a moment to write a comment.

Thanks
Nirman

Blog Archive