C #: Understanding of Ienumerable<out t> in C#4

Source: Internet
Author: User

Ienumerable<out T> This interface is very common, it is the most basic generic collection interface, representing the sequence of items that can be iterated.

But the strange thing is why do generic parameters take an "out"?

After some information, it is found that the "out" of the "Out" and "out" type parameters in C # is not a meaning.

Ienumerable<out in t> indicates that this interface supports "covariance".

What is "covariance"?

The simple understanding is that "T" can change to the base type of T. Say so much, feel is still very abstract, with a piece of code to express it.

ienumerable<int> collection1 = new list<string>();ienumerable<object> collection2 = Collection1 ;

Before c#4.0, because the ienumerable<t> declaration does not contain the "out" keyword, the above code cannot be compiled, and the compiler will tell you that the type conversion failed because the collection2 corresponds to a type of IEnumerable <object>, while collection1 corresponds to a type of ienumerable<int>. In fact, this problem is not how deep, because now most of the C # developers are using C # 5, it will be "natural" feel that Collection1 can be converted into collection2. I did, too, until the keyword "out" of the data study found the reason why such conversions could be achieved.



Reprint statement: This article is reproduced from http://www.zhoumy.cn/?p=16

C #: Understanding of Ienumerable<out t> in C#4

Related Article

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.