This article uses the picture to introduce the C # How to check foreach
whether it is null
, we do not say the following words, directly to see the content.
1, a foreach traversal list or array, if list
or array null
, it will be an error, the following figure:
2, do not know foreach
why the Microsoft package does not first check to traverse the object is null
, this leads to, we write code, traversing the list must first judge whether the list is null
, the following figure:
3. In order to simplify the process of this judgment null
, I wrote an extension method, because the list and arrays all inherit the IEnumerable
interface, so the extension method is extended on the IEnumerable
type, and for general purpose, the method is written as a generic method, as shown in the following diagram:
4, so in the traversal list of places do not first judge the list or whether the array is null
, directly with this extension method can be, the following figure:
5, the array can also yo, the following figure:
6, summary
I have limited technology, to achieve this simple extension method, I hope that we can help, if you have questions or better solutions can be message exchange.