What’s the difference between (fictious):
public Test GetTest()
{
Object obj = new Test();
return (Test)obj;
}
And
public Test GetTest()
{
Object obj = new Test();
return obj as Test;
}
Is it right that the first approach throws an exception if obj == null? And the second doesn’t?
No; both approaches will succeed and return
nullifobjisnull. The difference lies in what happens ifobjis not an instance ofTest: the first approach will throw an exception, while the second one will succeed and returnnull.In other words: Use the first approach if you know that your object is a
Testor if you don’t know what it is, but you want an exception if it is not aTest. Use the second approach if you don’t know what your object is, but you just want a peacefulnullif it is not aTest. You can also useasfor type checking if you intend to do something special if the type check succeeds:instead of:
In that way, you don’t need to repeat the type name, although the second form is probably clearer and avoids leaking
tto the rest of the scope.Also, see @il_guru’s post for some additional caveats related to
as.