#1,156 – Covariance and Generic Delegate Types

As with generic interfaces, generic delegate types are covariant if you mark output parameters as out.

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

        public delegate T ReturnDelegate<T>();

        public static Terrier GenerateTerrier()
        {
            return new Terrier("Bubba");
        }

        static void Main(string[] args)
        {
            ReturnDelegate<Terrier> del = GenerateTerrier;

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

We can get the delegate type to behave covariantly by marking its type parameter with the out keyword.

        public delegate T ReturnDelegate<out T>();

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

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.

One Response to #1,156 – Covariance and Generic Delegate Types

  1. Pingback: Dew Drop – August 8, 2014 (#1832) | 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: