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(); } }
The second is preferable when you throw 1 time
I prefer the third option:
foreach(var i in x.OfType<IMy>()) { i.M1(); }
The second, since only one does it. Or you can use OfType method:
OfType
foreach (IMy i in x.OfType<IMy>()) { i.M1(); }
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.
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.
Source: https://habr.com/ru/post/1344830/More articles:Getting locations from coordinates? - phpWhat does "constructors not inherit" mean? - javaWhy is OpenMP slow in this case? - c ++Android Auto-sync with user data - androidHow to change only the eye color in the image (uiimage)? - iosPHP files will not open in the browser - only download. What do I need to change for it to work correctly? - phpstrange error with jquery sorting: not a function - jqueryCalculation of recurrence relations in Haskell - recursionDoes anyone use Redis before MongoDB? - mongodbClip loading is very slow (unicorn) - ruby-on-rails-3All Articles