Reputation: 131
I'm trying to understand implicit casts on generic types. The following lines of codes won't compile:
class Dataset : Dictionary<string, string>
{
}
class Section : List<Dataset>
{
public List<Dictionary<string, string>> ToBase()
{
return this;
}
}
However, if I add the following implicit operator to the Section class they compile.
public static implicit operator List<Dictionary<string, string>>(Section section)
{
return section;
}
What do these lines really change? (By the way: ReSharper now shows an "Conversion to base class" error, but I couldn't find anything about it.
Could anyone please explain to me what's going on here?? Thanks!!
Upvotes: 0
Views: 266
Reputation: 111940
You can't cast a List<Dataset>
to a List<Dictionary<string, string>>
, because List<T>
isn't covariant (and only interfaces in C# can be covariant, so you would need a IList<T>
, but IList<T>
isn't covariant)
Note that this:
public IEnumerable<Dictionary<string, string>> ToBase()
{
return this;
}
is legal, because IEnumerable<>
is covariant, so you can cast a IEnumerable<subclass>
to a IEnumerable<baseclass>
To give some examples:
Section section = new Section();
List<Dataset> sectionAsList = section; // Legal
List<Dictionary<string, string>> sectionAsListDictionary = section; // Illegal
IList<Dictionary<string, string>> sectionAsIListDictionary = section; // Illegal
IEnumerable<Dictionary<string, string>> sectionAsIEnumerableDictionary = section; // Legal
Upvotes: 1