How to choose to use IEnumerable, ICollection, IList

Source: Internet
Author: User

IEnumerable, ICollection, IList, each interface is only suitable for some specific scenarios, how to use it differently?

The IEnumerable interface only provides a way to get iterators, which is why you can use a foreach traversal to implement the IEnumerable interface Collection.

public interface IEnumerable
{
    IEnumerator GetEnumerator ();
}

The ICollection implements the IEnumerable interface, so that in addition to the ability to have IEnumerable interfaces, other capabilities are included.

public interface Icollection:ienumerable
{
    int count{get;}
    BOOL Issynchronized{get;}
    Object Syncroot{get;}
    IEnumerator GetEnumerator ();
    void CopyTo (array array, int index);
}

IList implements both the ICollection and IEnumerable interfaces, which, on the basis of 2 interfaces, can add, remove, or empty the collection, and also provide access to the collection elements based on the index.

Public interface Ilist:icollection, IEnumerable
{
    BOOL Isfixedsize{get;}
    BOOL Isreadonly{get;}
    Object This[int index] {get;set;}
    int Add (Object value);
    void Clear ();
    BOOL Contains (Object value);
    int IndexOf (Object value);
    void Insert (int index, Object value);
    void Remove (Object value);
    void RemoveAt (int index);
}

Summarize:

If you only want to traverse the collection, use IEnumerable, ienumerable<t>
If you want to traverse, modify the collection, and the navigation properties that require lazy loading, use ICollection, icollection<t>
If you want to traverse, modify, add, empty, use an index, use IList, ilist<t>

How to choose to use IEnumerable, ICollection, IList

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.