Covariance and Contravariance
I am confused about how contravariant / covariance works with C #. I have the following pseudocode
public static void Main()
{
Action<string> action = e => Console.WriteLine(e);
Execute(action);
}
private static void Execute(Action<object> action)
{
action("hello world");
}
who throws
CS1502: Best overloaded method match for [...] has some invalid arguments
and I'm not really sure why. also what would be the correct way to do this?
In my real-world scenario, I have a basic interface that I use instead of passing an object in specific cases.
Thank!
Action<in T>
is contravariant, that is, you can pass "larger" types to a method. Because it string
is smaller (more specific or derived) than object
, you get a compile-time error. If you reversed your example and created Action<object>
instead Action<string>
, your method would compile:
public static void Main()
{
Action<object> action = e => Console.WriteLine(e);
Execute(action);
}
private static void Execute(Action<string> action)
{
action("hello world");
}
Action
and Func
are contravariant in their argument types, which means that you can assign Action<T>
to Action<U>
if it U
is a subtype T
. In your case, object
is a supertype string
, so the assignment is invalid.