C # Methods for checking whether a foreach interpretation is null _c# tutorial

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.