C
C#13mo ago
eggsaVEVO

❔ You cannot use a covariant type parameter as a generic type constraint for interface methods.

I do understand what variant type parameters are after reading about covariance and contravariance. What I do not understand however is what the sentence "You cannot use a covariant type parameter as a generic type constraint for interface methods." or "You can use a contravariant type parameter as a generic type constraint for an interface method." means from https://learn.microsoft.com/en-us/dotnet/standard/generics/covariance-and-contravariance#define-variant-generic-interfaces-and-delegates. Can someone explain to me the meaning of this sentence is?
Covariance and Contravariance in Generics - .NET
Learn about covariance, which allows you to use a more derived type, and contravariance, which allows you to use a less derived type, in .NET generics.
10 Replies
JakenVeina
JakenVeina13mo ago
example?
eggsaVEVO
eggsaVEVOOP13mo ago
They don't give an example in the documentation. Its just that sentence.
JakenVeina
JakenVeina13mo ago
an example of what you are trying to do
eggsaVEVO
eggsaVEVOOP13mo ago
I was just reading the documentation on Covariance and Contravariance without trying to do something specifically. Just studying C# details
JakenVeina
JakenVeina13mo ago
ah well which piece(s) of that sentence are you having trouble with?
eggsaVEVO
eggsaVEVOOP13mo ago
Basically I do not understand this sentence as a whole: "You cannot use a covariant type parameter as a generic type constraint for interface methods." I did ask bard about this and it came up with a term called "covariance hole". But that does seem to be made up because I could not find that anywhere else
JakenVeina
JakenVeina13mo ago
covariant type parameter
<out T>
<out T>
generic type constraint
where U : T
where U : T
interface method
public interface IMyInterface
{
void MyMethod();
}
public interface IMyInterface
{
void MyMethod();
}
so, I'd have to say
public interface IMyInterface<out T>
{
void MyMethod<U>(U param)
where U : T;
}
public interface IMyInterface<out T>
{
void MyMethod<U>(U param)
where U : T;
}
it means you can't do this
eggsaVEVO
eggsaVEVOOP13mo ago
Oh I see. Thank you for the example!
JakenVeina
JakenVeina13mo ago
if you want a better answer, try #advanced or #roslyn
Accord
Accord13mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server