c# is growing on me

October 25, 2004 under Computers, Programming

The hot water still isn’t fixed. I’m not in the mood for another “a world apart” joke today 😉 In the meantime, here’s a wicked feature from C# that I like.

It’s the ‘checked’ keyword and it can be used either within your code or as a switch for the command line compiler. It makes sure that a statement is a valid, sort of like C++’s ASSERT but a little bit stricter in terms of built in data types. For example, the largest possible value of a signed integer is 2147483647. So if you tried to store the sum of 2 billion multiplied by two, you could never get 4 billion as the result because signed integers on x86 hardware with 32-bit environments can’t hold a number larger than 2147483647. Instead, you’d end up with a weird value that is the difference of our intended 4 billion value and the maximium 32-bit value (that’s 4294967296). That sucks. But C#‘s ‘checked’ keyword will throw an exception if you try to do something crazy like that. Observe:

<br />class CheckedTest<br />{<br />    static void Main()<br />    {<br />       int a = 2000000000;<br /><br />       a *= 2;<br /><br />       // freaky-deaky value will be printed<br />       System.Console.WriteLine(a);<br />    }<br />}<br />

If we use the checked keyword (or the compiler switch), an overflow exception would be thrown:

<br />checked<br />{<br />   int a = 2000000000;<br />   a *= 2;<br />}<br />

That’ll make sure that we didn’t assign ‘a’ some value that’s too large, both when we declare it and when it’s multplied it by two. You can even use it on a single line:


int x;
x = checked(2000000000 * 2);

Nice 😉

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
comments: 0 »

Leave a Reply

Your email address will not be published. Required fields are marked *

Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>