Monday, July 13, 2009

Checked C# overflow

Using the 'checked' keyword in C#, you can check for an overflow.

checked
{
int a = someInt * someOtherInt;
}

This will check if there is an overflow.

You cannot check a nested method or something similar.

checked
{
int a = SomeMethod(b, c);
}

This will not check for overflow.

If you nest the check block in a try-catch. You can catch the overflow error.

try
{
checked
{
int a = someInt * someOtherInt;
}
}
catch (OverflowException)
{
// do something.
}

This is how to check for an overflow.

No comments:

Post a Comment