1. When foreach iterates through a list or array, if the list or array is null, an error is encountered, such as:
2, do not know the Microsoft Encapsulation foreach why do not first check whether the object to be traversed is null, so that we can write code, when we go through the list to determine whether the list is null, such as:
3, in order to simplify this decision is null process, I wrote an extension method, because the list and arrays are inherited IEnumerable interface, so the extension method is extended on the IEnumerable type, for general purposes, this method is written as a generic method, such as:
4, so in the place to traverse the list do not first determine whether the list or array is null, directly with this extension method can be, such as:
5, arrays can also yo, such as:
6. Summary
I have limited technology, to achieve this simple extension method, I hope that everyone can help, can recommend the words better, thank you.
C # Check that foreach is null-judged