Wednesday, August 24, 2005

Friendly casting using 'as'

Running this code will NOT cause a runtime error if 'b' is not of type 'myclass'. 'a' will simply be assigned null :

myclass a;

a = b as myclass;

if(a == null)
Console.WriteLine("Oh well. b is not a myclass.");
else
Console.WriteLine("Hey, guess what! b is a myclass! Wow!");


This code will throw an invalid cast exception:


myclass a;
someotherclass b;

a = (myclass) b;


One might say "What's so cool about using 'as'? I can do this with roughly the same amount of code. Like this...":

myclass a;
someotherclass b;

try{
a = (myclass) b;
Console.WriteLine("Hey, guess what! b is a myclass! Wow!");
}
catch{
Console.WriteLine("Oh well. b is not a myclass.");
}


That's neat, but guess what? That's using the .Net framework's exception handling mechanism for flow control. In all the examples above the implication is that there is not just the possibility that 'b' is not a myclass but rather there is some likelihood that 'b' is not a myclass. Using the exception handling for flow control is very bad form and a bad habit to get into. Its very slow and can make the debugger stop for no good reason. Don't do it!

No comments:

C# Sucks!

JK!! Seriously, though, somewhere around C#-3 we should have inculcated ourselves with the question: "Does 'CAN' == 'SHOULD...