Possible Duplicate:
Casting vs using the ‘as’ keyword in the CLR
I recently learned about a different way to cast. Rather than using
SomeClass someObject = (SomeClass) obj;
one can use this syntax:
SomeClass someObject = obj as SomeClass;
which seems to return null if obj isn't a SomeClass, rather than throwing a class cast exception.
I see that this can lead to a NullReferenceException if the cast failed and I try to access the someObject variable. So I'm wondering what's the rationale behind this method? Why should one use this way of casting rather than the (old) one - it only seems to move the problem of a failed cast "deeper" into the code.