C#: checked keyword


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 believe most people use unchecked much more frequently.


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

    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.


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