5

How can I detect if type x is assignable from type y not only through inheritance hierarchy but also through covariance and contravariance?

Alwyn
  • 8,079
  • 12
  • 59
  • 107

1 Answers1

9

IsAssignableFrom does check covariance and contravariance, you don't need anything else:

// Covariance
typeof(IEnumerable<object>).IsAssignableFrom(typeof(IEnumerable<string>)).Dump(); // true
typeof(IEnumerable<string>).IsAssignableFrom(typeof(IEnumerable<object>)).Dump(); // false

// Contravariance
typeof(Action<string>).IsAssignableFrom(typeof(Action<object>)).Dump(); // true
typeof(Action<object>).IsAssignableFrom(typeof(Action<string>)).Dump(); // false
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • Thanks man, I didn't realize that it checks for covariance and contravariance. An article on Google seems to indicate otherwise. – Alwyn Jul 13 '12 at 16:55