IEnumerable Vs List

zeinab mokdad

Member
Joined
Dec 23, 2021
Messages
13
Programming Experience
5-10
public interface ITest { }

public class Test : ITest { }

public void get()
{
IEnumerable<ITest> test1 = new List<Test>();
List<ITest> test11 = new List<Test>();
}

writing this code line "IEnumerable<ITest> test1 = new List<Test>();" this work.
but when writing "List<ITest> test11 = new List<Test>();" it won't work, can someone please explain why the first line work?
 
Last edited:
List<ITest> is a specific generic type, to assign a List<Test> that is a different specific generic type, you have to convert one type of object to another.

IEnumerable<ITest> is an interface, since List<Test> implements it it can be cast as it.
 
public interface IInterface<T> { }

public class Interface<T> : IInterface<T> { }

public interface ITest { }

public class Test : ITest { }

public void get()
{
IInterface<ITest> test1 = new Interface<Test>();
}

so why in this case this line wont work : IInterface<ITest> test1 = new Interface<Test>();
 
Different to the other example where you have to convert, here you can cast explicitly:
C#:
IInterface<ITest> test2 = (IInterface<ITest>)new Interface<Test>();
The difference is that IInterface is a generic interface, you have to specify the type parameter for it to have a meaning, compiler can't guess that for you.
 
Different to the other example where you have to convert, here you can cast explicitly:
C#:
IInterface<ITest> test2 = (IInterface<ITest>)new Interface<Test>();
The difference is that IInterface is a generic interface, you have to specify the type parameter for it to have a meaning, compiler can't guess that for you.
Thank you so much.
 
That was a lackful response from me. IEnumerable<T> is of course a generic interface too. So what's with these, why can IEnumerable<T> do it and not IInterface<T> ?
C#:
IEnumerable<ITest> test1 = new List<Test>(); //ok
IInterface<ITest> test2 = new Interface<Test>(); //why not?
The difference is generic covariance, change your interface to this, and the second line implicit cast will be valid:
C#:
public interface IInterface<out T> { }
Read about it here: out keyword (generic modifier) - C# Reference
 
By the way, naming a class "Interface"? Welcome more confusion than need to be.
 
Dear John , yeah that was my mistake I shouldn't name a class Interface.
but based on your last response I did go to the implementation of IEnumerable and found out that it is : interface IEnumerable<out T> : IEnumerable
and based on that I have learned more about the out keyword and came to the same conclusion.
Thank you you have been helpful about this confusion to me.
 
Back
Top Bottom