C # Check that foreach is null-judged

Source: Internet
Author: User
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

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.