Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# generic constraints for IEnumerable

Tags:

c#

generics

public interface I {
}
public class A : I {
}

The compiler takes explicit IEnumerable<A> as IEnumerable<I> :

public void Test() {
    IEnumerable<A> a = new List<A>();
    new List<I>().AddRange(a);
}

But with generic constraints, we get:

public void Test<T>() where T : I {
    IEnumerable<T> t = new List<T>();
    new List<I>().AddRange(t);
}
                          ^^^
Argument 1: cannot convert from 'IEnumerable<T>' to 'IEnumerable<I>'

However, this compiles fine.

public void Test<T>(T t) where T : I {
    new List<I>().Add(t);
}

Hence the question: is this a correct behavior, or is it a bug?

like image 939
destator Avatar asked Jul 24 '12 12:07

destator


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.


2 Answers

The problem is that generic covariance only applies for reference types. For example, a List<int> is not* an IEnumerable<Comparable>, but a List<string> is.

So if you constrain T to be a reference type, it compiles:

public void Foo<T, I>() where T : class, I 
{
    IEnumerable<T> t = new List<T>();
    new List<I>().AddRange(t);
}
like image 74
Jon Skeet Avatar answered Sep 28 '22 07:09

Jon Skeet


This has to do with Covariance and Contravariance. Suffice to say it is not a bug, but a feature.

For an indepth look at this I recommend Eric Lippert's blog post series here:

http://blogs.msdn.com/b/ericlippert/archive/2007/10/16/covariance-and-contravariance-in-c-part-one.aspx

like image 41
samjudson Avatar answered Sep 28 '22 07:09

samjudson