Previously I would cast object like so
try
{
Checkbox myCheckBox = (Checkbox)strangeObject;
//do some clever stuff
}
catch(Exception)
{}
- which works fine. My niggle with this that you’re getting towards using exceptions to manage the flow of code and the seven circle of hell is reserved for coders that indulge in this satanic practice. Enter the angelic keyword asLet’s do the same thing, this time with our new friend.
Checkbox myCheckBox = strangeObject as Checkbox;
if(myCheckBox != null)
{
//do something clever
}
The as casts the object but instead of spewing out an exception it gracefully nulls it. Therefore it’s same code but with no exception unpleasantness. I like this a lot better – it’s like wholemeal fibre vs. saturated fats. It’s just a lot better for you.
No comments:
Post a Comment