13 January 2016 Not Set C#, .NET

Intro

Recently I've come across the checked keyword. To be honest, I don't use this keyword very often. I used it only few times in algorithmic challenges and that's all. I belive most people use unchecked frequently, but don't know much about checked.

Code

By default, C# does not throw an exception if a narrowing conversion results in an error for integer or floating point types, but you can force C# to throw an exception for invalid narrowing integer conversion like this:

checked
{
    int big = 1000000;
    short small = (short)big;
}

Within this block, the program throws an OverflowException, because conversion from int to short fails. A very important thing to remember is that a checked block does not protect code inside methods called within the block. So if you call a method inside a checked block it won't affect code inside that method.

Summary

In any case, it is good idea to avoid a narrowing conversion when it is possible.


;