3

Possible Duplicate:
Direct casting vs 'as' operator?

Anyone can give a comparison between as and cast?

Community
  • 1
  • 1
user496949
  • 83,087
  • 147
  • 309
  • 426

3 Answers3

10

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.

cdhowie
  • 158,093
  • 24
  • 286
  • 300
  • 3
    +1 my usual advice is: If you are doing an "as" then the next line should be a null check. – Simon Nov 16 '10 at 07:05
  • @Simon: Good point. I think that's what I usually do, but I've never simplified it to that simple statement. – cdhowie Nov 16 '10 at 07:07
1

"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...
}
acoolaum
  • 2,132
  • 2
  • 15
  • 24
0

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

The as operator…

  1. 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.
  2. can be applied only to reference type variables being converted to reference types.
  3. cannot perform user-defined conversions—e.g., explicit or implicit conversion operators. A cast could perform these types of conversions.
Nanda
  • 604
  • 8
  • 20
  • 2
    Point 2 is incorrect. You can use it for nullable value types too. – Jon Skeet Nov 16 '10 at 06:58
  • Copied verbatim without attribution from one of the answers here: https://social.msdn.microsoft.com/Forums/vstudio/en-US/2631380f-b926-4633-ba42-d3c019605e5b/cast-which-is-the-correct-way?forum=csharpgeneral – Disillusioned Nov 15 '17 at 06:13