Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type of generics method return value

Tags:

c#

generics

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?

like image 261
AndySavage Avatar asked Jan 17 '26 23:01

AndySavage


1 Answers

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>();
like image 59
Paulo Lima Avatar answered Jan 20 '26 11:01

Paulo Lima