6

I'm wondering, in which case would you use C#'s 'as' keyword, as opposed to casting and checking for an exception? Consider this example:

Parent obj = new Child();

// Method 1:
try
{
    Child result1 = (Child)obj;
}
catch (InvalidCastException)
{
    // Handle failed cast
}

// Method 2:
if(obj is Child)
{
    Child result2 = obj as Child;
}
else
{
    // Handle failed cast
}

Both Method 1 and Method 2 produce, as far as I'm aware, the exact same result. I know that, when they fail, the as keyword will produce null, while a cast will throw a ClassCastException, but to me, that doesn't seem like enough of a reason to have two nearly identical ways to cast an object. So I'm wondering, why did the C# language designers go trough the trouble of adding the 'as' keyword?

Johan Geluk
  • 149
  • 2
  • 8
  • 3
    Exceptions are magnitudes slower than doing a check in a `if`, you should always avoid exceptions where you can predict where one would have been thrown and you are planning on handling the failure case. Exceptions should only be for ***Exception***-al circumstances. – Scott Chamberlain Dec 25 '13 at 02:48

3 Answers3

3

Exceptions can be costly and have an implicit goto behavior.

I would do case 2 as this and you save yourself some instructions and clarity.

Child result2 = obj as Child;
if(result2 != null)
{

}
else
{
    // Handle failed cast
}
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
3

Exceptions are rather expensive, so when you expect one you should use logic to avoid throwing in the first place. But neither of your code snippets is recommended style. Try one of these:

// Method 2b
if(obj is Child)
{
    Child result2 = (Child)obj;
}
else
{
    // Handle failed cast
}

// Method 3:
Child result3 = obj as Child;
if(result3 != null)
{

}
else
{
    // Handle failed cast
}

The as followed by null also neatly handles the case where obj was null to begin with.

You can think of as vs cast being the same as TryParse vs Parse. It lets you handle failure cheaply using normal program flow instead of throwing an exception.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
0

From The C# Reference

The as operator is like a cast operation. However, if the conversion isn't possible, as returns null instead of raising an exception.

And the example;

expression as type

is equivalent to this (but with one evaluation only);

expression is type ? (type)expression : (type)null
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249