Developing on Staxmanade

C# (checked) keyword – Learn something new every day

I’ve been programming against the .net framework since the late beta of version 1.0 came out. (I had a couple year hiatus when I took a job doing some Linux & C++) however, suffice it to say, I’ve been using the language a long time. I still find it amazing that there are features in the language that have been a round a long time and still manage stumbling across things I’ve never seen before.

Today’s newly learned feature I saw in a blog by bogardj over at LostTechies where he wrote up a little Expressions Cheat Sheet.

In his blog, I notice the “checked” keyword had the blue syntax highlighting. (which usually means it’s a C# keyword)

image

So, to verify, I copied the word into my C# editor and what do you know… It is a C# keyword. This is probably something most if not all C# programmers out there already know and I, for some reason have missed this.

Here’s a blurb about it on the stack overflow “Hidden features of C#”.image

And of course you can get the official details @ http://msdn.microsoft.com/en-us/library/74b4xzyw(VS.71).aspx

I decided to explore this a little. As an academic exercise I wanted to see what the difference would be between using the checked keyword with a cast operation and compare that to the System.Convert.ToByte operation.
image
Will generate the following error. System.OverflowException : Arithmetic operation resulted in an overflow.

image
While using the System.Convert class will generate a different error. System.OverflowException : Value was either too large or too small for an unsigned byte. 

And last experiment I threw both of the conversion attempts in a loop and fired up the ANTS Profiler which shows that using the built in checked keyword with a cast operation is faster than using the BCL conversion.

image 

As to which one is better I would probably have to dig deeper into other side affects that one may have over the other… Up front I don’t see any issue with the cast and checked keyword combo.

Comments

justinmchase
Good to know. Actually I did know about it but I think I had it backwards, I thought that it was checked by default and therefore the keyword was only useful if used in an explicitly unchecked block. Your tests here seem to disprove that, so thanks for the info.