Yes, it's a trivial piece of code to write, but I still wonder if there's a built-in replacement.
Here's the code:
/**
* Cast x to int, throw an exception if there's loss of information
*/
public static int safeLongToInt(long x)
{
int result = (int) x;
if (result != x)
throw new RuntimeException("long doesn't fit in an int: " + x);
return result;
}
The code in C# would be:
int foo;
long bar = ...;
checked
{
foo = bar;
}