I have one generic interface in c#, and almost always I use it with one of the types. I want to create a non-generic interface for that type and use it.
Let’s say, I’ve the following code:
public interface IMyGenericList<out T> where T : IItem
{
IEnumerable<T> GetList();
}
public class MyList<T> : IMyGenericList<T> where T : IItem
{
public IEnumerable<T> GetList()
{
return null;
}
}
it works well. Most times I need IMyGenericList<IItem>, so i try the following:
public interface IMyItemsList : IMyGenericList<IItem>
{
}
but I can’t make MyList implement IMyItemsList for some reason. The following code returns an error
public class MyList<T> : IMyItemsList, IMyGenericList<T> where T : IItem
{
public IEnumerable<T> GetList()
{
return null;
}
}
saying that IEnumerable<IItem> is not implemented.
Why is it so/what can I do with this?
Thanks.
Ok, thanks to your answers I figured out it’s impossible to do it exactly as I wanted initially. I will post another question on why this is impossible 🙂
Here it is: One function implementing Generic and non-generic interface
You specific example wouldn’t work, as your class:
is trying to implement both a
IEnumerable<IItem> GetList()and anIEnumerable<T> GetList(), which are two different things. This first is explicitly an enumerable ofIItem(as required by yourIMyItemsListinterface), and the second is an enumerable ofT.In this scenario
Tis of typeIItembut is not explicitlyIItem. Therefore at compile time, theIEnumerable<IItem> GetList()is notIEnumerable<T> GetList()so the compiler will correctly throw an error telling you thatIEnumerable<IItem> GetList()is not implemented.The other problem you will run into, is what happens when somebody does:
The compiler will try and create an a concrete implementation of
MyList<IItem>which will have two definitions ofIEnumerable<IItem> GetList().I would reconsider your design to evaluate a singular
IEnumerable<T> GetList().Also, and just picky on my part: “enumerable” != “list” 😛