5

Possible Duplicate:
casting vs using the 'as' keyword in the CLR

foreach (MyClass i in x)
{
        if (i is IMy)
        {
                IMy a = (IMy)i;
                a.M1();
        }
}

or

foreach (MyClass i in x)
{
        IMy a = i as IMy;
        if (a != null)
        {
                a.M1();
        }

}
Community
  • 1
  • 1
johnny
  • 1,241
  • 1
  • 15
  • 32

5 Answers5

16

Second is more preferable as you cast 1 time

Stecya
  • 22,896
  • 10
  • 72
  • 102
  • Yes, the second is preferred of the two given, but frankly there is a better third option: http://stackoverflow.com/questions/5397311/should-i-prefer-the-is-or-as-operator/5397384#5397384 – jason Mar 22 '11 at 20:40
  • you can use the inline is keyword : foreach (MyClass i in x) if (i is IMy a) a.M1(); – Derek Tremblay Aug 23 '17 at 22:54
10

I prefer a third option:

foreach(var i in x.OfType<IMy>()) {
    i.M1();
}
jason
  • 236,483
  • 35
  • 423
  • 525
8

The second, as that only does one cast. Or you can use the OfType method:

foreach (IMy i in x.OfType<IMy>()) {
  i.M1();
}
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
3

Second is preferable, as you're casting only once.

This article can also help understand this. 'as' operation does the 'is' check and returns either a casted object or a null - does all the work for you.

Kon
  • 27,113
  • 11
  • 60
  • 86
3

The second. It's the same number of lines of code but you avoid doing the cast twice.

Note that whilst the second is preferable it wouldn't have worked it the type had been a value type. You can only use as on reference or nullable types.

Sean
  • 60,939
  • 11
  • 97
  • 136