0

The problem:

interface ICovariant<out R>
{
    // The following statement generates a compiler error
    // because you can use only contravariant or invariant types
    // in generic constraints.
    // void DoSomething<T>() where T : R;
}

Why is the generic constraint on methods in this case not allowed.

EDIT: Lol I found the answer, Generic type "T" in the method is actually an argument (or an input) and hence it is not covariant.

GameOver
  • 13
  • 3
  • Rather than it be void DoSomething() where T : R; It should just be void DoSomething(); – DCCoder Sep 12 '20 at 15:21
  • 6
    Because `R` is covariant, `ICovariant cs = default; ICovariant co = cs;` is valid, enabling `cs.DoSomething();` which would violate the constraint. – Aluan Haddad Sep 12 '20 at 15:25
  • 2
    no it doesn't answer the question, i am specifically asking why the statement i provided is not allowed – GameOver Sep 12 '20 at 15:26
  • 3
    @DCCoder Nope. In that case, `R` would be a different generic type (which isn't constrained) and you'd get a warning about it having the same name as the other `R`. – 41686d6564 stands w. Palestine Sep 12 '20 at 15:27
  • @GameOver it seems that the link 41686d6564 posted accurately answers that question. – DCCoder Sep 12 '20 at 15:31
  • @GameOver _"no it doesn't answer the question"_ Don't just look at the question and decide it's different from yours. Did you read [the accepted answer](https://stackoverflow.com/a/5043054/8967612)? It basically says what Aluan said in the comment above and you accepted (in a now-deleted comment). The only difference is that Eric's answer uses a traditional method parameter and your code uses a generic type parameter. The rule is the same though. It applies to both. – 41686d6564 stands w. Palestine Sep 12 '20 at 16:00

0 Answers0