Relation between List<> and IEnumerable<> open type

  • A+

Is there any relationship between the open types List<> and IEnumerable<>?


var type1 = typeof(List<>); var type2 = typeof(IEnumerable<>);  //return false type2.IsAssignableFrom(type1); 

Is there any method to check the relationship between two open type, or the relationship only exist on closed type?


List<> and IEnumerable<> are not types; they are type definitions. As such it doesn't really make sense to ask if one is assignable to the other. Neither can be assigned to. You can't declare a variable List<> a = null, for example-- you will get a compilation error "Unexpected use of an unbound generic name."

A type definition becomes a generic type when you specify the type parameter. At that point, it is a type and can be assigned to. So for example List<string> can be assigned to IEnumerable<string>.

If you have a type definition in mind and you want to do a type-compatibility check, just use <object> (or a suitable type if there is a type constraint) instead of <>:

var type1 = typeof(List<object>); var type2 = typeof(IEnumerable<object>);  //returns true type2.IsAssignableFrom(type1); 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: