I had a great job interview for a great company on tuesday just gone, they are a Microsoft Gold Certified Partner so that suits me down to the ground since I am a Microsoft fanboy! I have a second stage interview with them that will be technical, so it would probably involve a test and lots of questions, so I have decided to put in some more study into my profession and brush up on stuff, starting with C#.
I think myself as a fairly good C# programmer, not the best, but fairly good, but, there are some things that I have never needed to learn, in this post I will look at the checked keyword. The checked keyword is used to control the overflow-checking context of integral-type arithmetic operations and conversions - cited from the msdn docs.
At first glance, since some things are not always clear to me, my thoughts are - what does this mean?
Well, if we take a byte, we know that a byte can only have maximum value of 255, so any greater value than 255 would result in an overflow.
So what checked does is - if you perform an arithmetic operation that results in an overflow, it will throw an OverflowException, the following example shows this.
class Program
{
static void Main()
{
byte a = 200;
byte b = 200;
byte c = checked((byte)(a + b));
Console.WriteLine(c);
}
}
Without the checked, the calculation would wrap giving c a value of 144.
I have never needed to use this yet, but I guess if an important calculation was being performed then I would consider it, for instance if it was going to lose a lot of money!