Wednesday, December 1, 2010

.NET-- Explicit Cast or Use "as"?

In .NET there are 2 different ways to cast an object from one to another-- by explicitly casting like (OtherObject)startObject (I call this the explicit cast) or by using the as keyword like startObject as OtherObject. What are the advantages/drawbacks of using one or the other?

Why You Should Use "as"

Do you know what goes on behind an explicit cast? If the type to be converted does not match the wanted type at runtime, it tries to use any user defined conversions to create a completely new type. Also, if the explicit cast doesn't work it throws an error.

The "as" keyword doesn't have these drawbacks. If the cast fails, the newly created object is null; there's no error. And again, no conversion/new object creation occurs. Win-win.

"As" does have a downside though--it cannot be used on value types. Doesn't really come as a surprise though, remembering that it will not do new object creation...

No comments:

Post a Comment