David Truxall

Adrift in .Net

<January 2009>
SuMoTuWeThFrSa
28293031123
45678910
11121314151617
18192021222324
25262728293031
1234567


Navigation

Other Good Blogs

My Other Articles on CodeProject

Subscriptions

News

Day of .Net October 18, 2008 - Be there!
View David Truxall's profile on LinkedIn
My presentations on SlideShare

Post Categories



Sunday, April 03, 2005 - Posts

The Wonderful AS Operator

I just recently discovered the AS operator in the C# language. The AS operator lets you perform a type of cast, but much more elegantly than the C-style cast. Previously I had been casting like mad. The AS keyword is espeically helpful when you are doing alot of event handling, since the sender in the event handler is typically sent in as a generic object:

void kidButton_Click(object sender, EventArgs e)
{
      Button whoClicked = sender as Button;
      //instead of Button whoClicked = (Button)sender;
}

Of course there are other advantages too. If the types don't match, instead of an exception, your object will be null instead. This is much less expensive to handle than an exception. The AS operator does not work on value types.

posted Sunday, April 03, 2005 10:28 AM by davetrux with 0 Comments




Powered by Dot Net Junkies, by Telligent Systems