One of the things in VS 2008 that has intrigued me has been Extension Methods. I've been trying to think of ways to use these in my applications and coming up with ways to move functions associated with various processes to Extensions in our own APIs. ScottGu recently posted an interesting article on his weblog about writing an
Extension for creating JSON.
One thing I dislike doing and have to do fairly often is cast Object sender to various things to pull information out of it. The most common reason to do this is that I'm making my buttons dynamically and I need to know which button was pressed so that I can have the program act accordingly. Usually I do something like this:
Button b = (Button)sender;
Then grab something out of it like b.Text and use that value.
I dislike this because the casting is just straight up, no holds barred, you were one thing and now you're this. And, if I'm wrong I throw an exception. So, I should be doing some checking, some Exception handling, and what have you. But, I really don't want to clutter up the code with all that since the Event is only tied to these buttons. Of course, a nagging in the back of my mind asks if it will always be that way (probably) and another nagging asks if I'm compromising my ethics by not doing these checks.
Then along comes Extension methods in the VS 2008 (Orcas) Beta. I can do basically the same things using Extensions but hide some error checking behind the scenes without having to write the code over and over. I can also update my casting method in one place and it will be changed everywhere, because right now it is very basic. Here's what I have so far:
public static Button AsButton(this object o)
{
if (o is Button)
return (Button)o;
return null;
}
Then in the forms code:
Button btn = sender.AsButton() ?? new Button();
This is, of course, very simplistic, but it does allow me to create a place where I can handle this casting in one place, something I am
very fond of doing. Although I'm still contemplating whether or not returning null is the right answer. Basically what I'm saying is that it will always have to be a Button, and if it isn't a button... then its a Button. I'm not sure if I like that. But, that's not the the functionality of the Extension doing that, so what I do with that returned null can vary from place to place.