2

Why in .Net templating a generic class is an invariant operation towards generic arguments? Interfaces and delegates are not, but classes are.

For instance, I would like to be able to assign object of type Expression<Func<string>> to Expression<Func<object>>. As T in Func<T> is "out" and Expression is immutable, it would be reasonable to assign it as I have showed, right?

user3284063
  • 665
  • 5
  • 20

1 Answers1

-2

Had classes allowed variant type parameters, you wouldn't be able to use them in any field, since fields are always (at least sometimes) writable and readable.

That would limit the utility enough to make it not worth it.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Please see Contravariance and Covariance in C#. – David Jul 03 '14 at 18:31
  • @Aravol: What? Even a `readonly` field is writable in a ctor, so any usage in a field would be invariant. – SLaks Jul 03 '14 at 18:32
  • A class would not be able to expose any *public* fields with the variant generic type, and likely could not use any variant field of any instance *other than itself*, but variant classes would be useful if the type system supported them. Static fields would be a trickier issue, whether or not they were of the generic type; if an instance method of a type `Thing` returns the contents of a static field, should casting a `Thing` to a `Thing` and calling that method yield the value associated with `Thing` or `Thing`? – supercat Jul 03 '14 at 19:36