#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)
        {
            Console.WriteLine(d.Name);
        }

        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>.

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: