C# casting – Did you know?

I was reading through someone else’s C# code the other day when I saw something that wasn’t immediately clear. It went something like this:
Object o;
for (int i=0; i < myCollection.count; i++) { o = myCollection[i] as SomeObjectType; // Huh? if (o != null) { // Do something with 'o'... break; } } [/code] While the cast seems clear enough, there are a few things to be aware of. If the above cast fails, it assigns a null value to 'o'. If the null value is not handled immediately, you may not realize the problem until some time later when you run into the null reference. [code] Object o; // As-casting - Returns null if the cast fails! o = myCollection[i] as SomeObjectType; // Prefix casting - throws an exception if the cast fails! o = (SomeObjectType)myCollection[i]; [/code] There may be a performance benefit to the As-cast but I'm much more comfortable knowing that my cast exceptions were handled properly using the Java-esque Prefix cast.