Can I convert long to int?

inspite picture inspite · May 13, 2009 · Viewed 218.1k times · Source

I want to convert long to int.

If the value of long > int.MaxValue, I am happy to let it wrap around.

What is the best way?

Answer

Mehrdad Afshari picture Mehrdad Afshari · May 13, 2009

Just do (int)myLongValue. It'll do exactly what you want (discarding MSBs and taking LSBs) in unchecked context (which is the compiler default). It'll throw OverflowException in checked context if the value doesn't fit in an int:

int myIntValue = unchecked((int)myLongValue);