AndySavage
AndySavage

Reputation: 1769

Type of generics method return value

It seems to me like I should be able to do this? But I can't.

public Dictionary<Type, List<ParserRuleContext>> Contexts { get; private set; }

public IEnumerable<T> GetAllContextsOfType<T>() where T:ParserRuleContext
{
    return (List<T>)Contexts[typeof(T)];
}

This produces the error:

Cannot convert type 'System.Collections.Generic.List<ParserRuleContext>' 
to 'System.Collections.Generic.List<T>'

Given that List is constrained to be List<ParserRuleContext> by the where clause, I don't understand this?

Upvotes: 3

Views: 107

Answers (2)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239714

Just because you know that, for a particular Type, you're only going to store objects of that specific type in the List<ParserRuleContext> stored here1:

public Dictionary<Type, List<ParserRuleContext>> Contexts

There's not enough information for the type system to also know that fact. So far as it's concerned, each of those lists could contain all kinds of objects, all deriving from ParserRuleContext. Such a list obviously couldn't be directly cast to any more specific type of list.

And generic types don't (generally) mirror any inheritence structure that their type parameters do. So it's not like you might have stored a List<TypeDerivedFromParserRuleContext> in this dictionary - because List<TypeDerivedFromParserRuleContext> doesn't inherit from List<ParserRuleContext>.


1At least, I assume that that's the assumption by which you believe that the rest of this code "made sense"

Upvotes: 4

Paulo Lima
Paulo Lima

Reputation: 1238

I believe that should be the fact that the instance of the list being with a different tipage the list in the dictionary, if you make a cast with linq is to solve

return Contexts[typeof(T)].Cast<T>();

or

return Contexts[typeof(T)].ToList<T>();

Upvotes: 6

Related Questions