Possible Duplicate:
casting vs using the 'as' keyword in the CLR
As someone new to C# I was wondering if there is any important difference between this:
object o = SomeFunction();
if (o is MyClass)
{
MyClass myObject = (MyClass) o;
myObject.MyFunction();
}
and this:
object o = SomeFunction();
MyClass myObject = o as MyClass;
if (myObject != null)
myObject.MyFunction();
When is one preferred over the other? In the code I work with, both seem to be used randomly.
You should use what gives the most readable code. So it really depends on what you are doing.
IMHO, the
iskeyword is evil. It invites you to break the Liskov substitution principle.