3

Possible Duplicates:
Direct casting vs 'as' operator?
casting vs using the 'as' keyword in the CLR

I know I can do the following:

if(someObject is Bar)
{
    Bar b = (Bar)someObject;
    //Use b
}

and also:

Bar b = someObject as Bar;
if(b != null)
{
    //Use b
}

Is one preferable over the other, if I assume I'm just going to reference the someObject in another variable?

EDIT: By preferable, I'm meaning following conventions, performance, chance for bugs, and readability.

Community
  • 1
  • 1
PrettyPrincessKitty FS
  • 6,117
  • 5
  • 36
  • 51

1 Answers1

1

The first version has two checks, whereas the second one has only one check.
--> The second one is preferable.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443