interface IFoo
{
public ICollection<ICollection<string>> GetWords();
}
class Foo : IFoo
{
public ICollection<ICollection<string>> GetWords()
{
return new List<List<string>>() { new List<string>() { "word" } };
}
}
Is not allowed ("Cannot implicitly convert type...")
How can I save myself having to type cast everything when the interface is defined in terms of interfaces (generics?), and the implementation is of course using implementations of the types.
I feel like implementors should have choice in which implementation of ICollection
they use to provide the functionality, so that's why I'd like the type in the interface to remain ICollection
and callers can know they're working with some ICollection
, but the interface shouldn't force implementors to use a certain implementation of ICollection nor should I have to deal with (redundant?) explicit subtype to supertype typecasts everywhere.
I'm using generic types and in my case I get the error:
Cannot implicitly convert type 'System.Collections.Generic.Dictionary<int, System.Collections.Generic.List>' to 'System.Collections.Generic.Dictionary<int, System.Collections.Generic.ICollection>'
I don't believe that a fabled lack of support for covariance is the explanation, and if it is please explain to me how. I don't agree with an explanation from the comments:
interface ... defines a method return type of
SomeBase
, and derived class overrides with a method returningSomeDerived
. It is not currently supported
Because this fiddle (no nested generics) does exactly that successfully: dotnetfiddle.net/qkpxN8
And this page: https://learn.microsoft.com/en-us/dotnet/standard/generics/covariance-and-contravariance also says that
You can assign an instance of IEnumerable to a variable of type IEnumerable.
>` does not inherit from `ICollection>`, nor is it that type.
– Lasse V. Karlsen Oct 12 '21 at 18:45>` typed into `ICollection>`. Why? Because this would allow the caller to add *any* type into the outer list, as long as that type implements `ICollection`, yet your underlying actual collection only accepts `List`. So, return a `List>`.
– Lasse V. Karlsen Oct 12 '21 at 18:52