0

I am completely new in C# covariant and contravariant concept. I have been following YouTube tutorials and MSDN docs, but they are still confusing. It will be very kind of you if please explain why cannot I return T from a contravariant delegate with "in T" and why cannot I take T as parameter for a covariant delegate with "out T". And, when should I use covariant and when should I contravariant?

Thank you very much of answering.

Edit 1: I wanted to do something like this:

public delegate T ContravariantDelegate<in T>();
public delegate void CovariantDelegate<out T>(T b);
  • 2
    @AliReza: Um, plenty of delegates are. Delegates absolutely support generic variance, too. – Jon Skeet Jul 07 '21 at 15:25
  • 1
    @AliReza `Action`? `Func`?.. https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/generic-delegates – CoolBots Jul 07 '21 at 15:27
  • 1
    yes this is generic delegate. I thought you want to pass a `delegate` to T. so looks like i did not understand your problem. can you provide some code sample and explain what you want to achieve ? – AliReza Sabouri Jul 07 '21 at 15:32
  • 5
    Well, the "in" means "Please check that I'm only accepting values *into* the delegate" and "out" means "Please check that I'm only passing values *out* of the delegate" - whereas your examples try to do the exact opposite. – Jon Skeet Jul 07 '21 at 15:36
  • @JonSkeet, thank you Sir for your simplification of the terms. I will note them and try to relate it with the examples and tutorials I have been following. – Mahfuzur Rahman Jul 07 '21 at 15:39

0 Answers0