the comparison between as and cast

Possible Duplicate:
Direct casting vs 'as' operator?

Anyone can give a comparison between as and cast?


A straight cast will fail if the object being casted is not of the type requested. An as -cast will instead return null. For example:

object obj = new object();
string str = (string)obj; // Throws ClassCastException

However:

object obj = new object();
string str = obj as string; // Sets str to null

When the object being casted is of the type you are casting to, the result is the same for either syntax: the object is successfully casted.

Note specifically that you should avoid the "as-and-invoke" pattern:

(something as SomeType).Foo();

Because if the cast fails, you will throw a NullReferenceException instead of a ClassCastException. This may cause you to chase down the reason that something is null, when it's actually not! The uglier, but better code

((SomeType)something).Foo();

Will throw a ClassCastException when the object referenced by something cannot be converted to SomeType , and a NullReferenceException when something is null.


"as" don't throw exception and return null if cast is failed.

It works similar this code:

if (objectForCasting is CastingType)
{
   result = (CastingType)objectForCasting;
}
else
{
   result = null;
}

The good practice is to use checking for null after using as statement:

CastingType resultVar = sourceVar as CastingType;

if (resultVar == null)
{
   //Handle null result here...
}
else
{
   // Do smth with resultVar...
}

Performing an explicit cast differs from using the as operator in three major aspects.

The as operator…

  • returns a null if the variable being converted is not of the requested type nor present in its inheritance chain. On the other hand, a cast would throw an exception.
  • can be applied only to reference type variables being converted to reference types.
  • cannot perform user-defined conversions—eg, explicit or implicit conversion operators. A cast could perform these types of conversions.
  • 链接地址: http://www.djcxy.com/p/73732.html

    上一篇: (int)值或值为int?

    下一篇: as和cast之间的比较