Should I prefer the "is" or "how" operator?

Possible duplicate:
casting vs using the keyword 'as' in the common language runtime

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(); } } 
+4
source share
5 answers

The second is preferable when you throw 1 time

+16
source

I prefer the third option:

 foreach(var i in x.OfType<IMy>()) { i.M1(); } 
+10
source

The second, since only one does it. Or you can use OfType method:

 foreach (IMy i in x.OfType<IMy>()) { i.M1(); } 
+8
source

Secondly, it is preferable since you throw only once.

This article may also help to understand this. The operation "how" checks "is" and returns either a cast object or zero - it does all the work for you.

+3
source

Second. The same number of lines of code, but you avoid throwing twice.

Note that while the second is preferable, it would not work, the type was the value type. You can use either for reference or null types.

+3
source

Source: https://habr.com/ru/post/1344830/


All Articles