-2

From what I understand about contravariance in C#, is that it is valid to assign a method that takes a more general type (base type) to a delegate that expects a less general type (derived type).

For example, if we define a method that takes an object (the more general type) as a parameter, we can assign it to an an Action<string> which expects a string (the more derived type) as a parameter like this:


static void Method(object b) { } // the method takes the more general object type

Action<string> action = Method; 

// this is valid as the static method can accept any string passed into it by boxing it into an object type

But when it comes to value and reference types, it seems that the C# compiler doesn't allow assigning the same method to an action that expects an int as a parameter like this:

static void Method(object b) { } // the method takes the more general object type

Action<int> action = Method; // this generates a compiler error

In this case, the compiler doesn't allow this, although the static method can accept any int passed into it by boxing its value.

I have also tried this example with a user defined struct which should inherit from object as per Microsoft documentation ("All struct types implicitly inherit from the class System.7 ValueType , which, in turn, inherits from class object .").

sepp2k
  • 363,768
  • 54
  • 674
  • 675
  • 2
    Because [variance applies only to reference types](https://learn.microsoft.com/en-us/dotnet/standard/generics/covariance-and-contravariance). – shingo Aug 19 '23 at 14:49

0 Answers0