#1,157 – Contravariance and Generic Delegate Types

As with generic interfaces, generic delegate types are contravariant if you mark input parameters as in.

In the example below, we’re unable to assign an instance of ReturnDelegate<Dog> to ReturnDelegate<Terrier>.  The delegate type is not contravariant.

        public delegate void ReportOnDelegate<T>(T param);

        public static void ReportOnDog(Dog d)

        static void Main(string[] args)

            ReportOnDelegate<Dog> del = ReportOnDog;

            // Error: Cannot implicitly convert ReportOnDelegate<Dog>
            // to ReportOnDelegate<Terrier>
            ReportOnDelegate<Terrier> del2 = del;

We can get the delegate type to behave contravariantly by marking its type parameter with the in keyword.

        public delegate void ReportOnDelegate<in T>(T param);

We can now assign an instance of ReportOnDelegate<Dog> to a variable of type ReportOnDelegate<Terrier>.


About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #1,157 – Contravariance and Generic Delegate Types

  1. Pingback: Dew Drop – August 11, 2014 (#1833) | Morning Dew

  2. Pingback: Dew Drop – August 12, 2014 (#1834) | Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: