Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delegate contravariance (parameter compatibility)

Tags:

c#

c#-5.0

I am looking at the C# 5 in a Nutshell text, section on Delegate Parameter Compatibility. It says

When you call a method, you can supply arguments that have more specific types than the parameters of that method. This is ordinary polymorphic behavior. For exactly the same reason, a delegate can have more specific parameter types than its method target. This is called contravariance.

This paragraph makes sense up until the last sentense. Why is it contravariance, i.e. what projection here is contravariant?

The accompanying example is below.

delegate void StringAction (string s);

class Test
{
    static void Main()
    {
        StringAction sa = new StringAction (ActOnObject);
        sa ("hello");
    }

    static void ActOnObject (object o)
    {
        Console.WriteLine (o); // hello
    }
}
like image 344
nomad Avatar asked Jun 21 '26 23:06

nomad


2 Answers

The projection of object (the parameter of the function ActionObject) to the type declared for the delegate (string) is contravariant.

This is allowed because by passing it a string (which you must due to the delegate signature), you are guaranteed that you will have an object (which the assigned function takes), so everything is nice and safe.

Just so you know, "ordinary polymorphism" in this context is actually called covariance.

See MSDN for more details.

like image 66
BradleyDotNET Avatar answered Jun 24 '26 12:06

BradleyDotNET


Function types are contravariant in argument types. In your example the type

delegate void ObjectAction(object o);

is a subtype of

delegate void StringAction(string s);

since ObjectAction can be used everywhere that StringAction is used because, if a caller is passing in a string argument, the argument must also be of type object.

object is a supertype of string but ObjectAction is a subtype of StringAction; the subtyping goes in the opposite direction. This is why it's called contravariant. Because the variation in the function subtypes goes in the opposite direction of the parameter subtypes.

like image 21
mrmcgreg Avatar answered Jun 24 '26 14:06

mrmcgreg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!