I want to make "somehow" the following work:
public class GenericsTest<T> where T: ISomeInterface
{
private List<T> someList = new List<T>();
public List<ISomeInterface> GetList()
{
return someList; //of course this doesn't even compile
}
}
Is there a way to do this (like the wildcards in Java) and I just missed it? Or it just can't be done?
EDIT: First of all thank you all for the interest and your answers/comments. Second, sure there are ways to do that, and probably the simplest and most performance effective (not sure for that though) is to create a new list of the proper type and iteratively add the elements of the other list (someList in our case). Question is with all those new variance things, the "ins" and the "outs" if there is a way to do it the "generics way". In Java that could be:
public class GenericsTest<T extends SomeInterface> {
private List<T> someList = new ArrayList<>();
public List<? extends SomeInterface> getList() {
return someList;
}
}
So I was wandering if there is the ? extends equivalent in C#. I could accept a "no" as a short answer, I just thought I should ask first.
EDIT 2:
Some users believe and some others insist that this is a duplicate of a question that has to do with casting. Since I marked the most suitable for me answer, for the sake of clarity I explain. Guys, I don't want to cast. I am simply looking for an equivalent of the Java wildcard with the extends constraint. Of course Java has compile time only generics, which might make the difference. If the equivalent in C# is done with casting fine, but I am aware of the problem of "having a Dog object in Cat list", so my question is different.
I believe this would do the trick:
public List<ISomeInterface> GetList()
{
return someList.Cast<ISomeInterface>().ToList();
}
You could also do:
public List<ISomeInterface> GetList()
{
return someList.OfType<ISomeInterface>().ToList();
}
The difference is that the first option will do a hard cast, which means that if one of the elements does not implement ISomeInterface an exception will be thrown. The second version will only return instances that implement ISomeInterface and will just skip over instances that don't.
In your example, you can safely use the Cast option as you are guaranteed that all instances implement ISomeInterface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With