#1,155 – Return Value Compatibility when Assigning to Delegate Types

When you assign a method to an instance of a delegate, input parameters in the delegate may be more specific than corresponding parameters in the method.

Similarly, the return type of the delegate can be less specific (ancestor of) the return type of the method.

In the example below, assume that Terrier derives from Dog.

        public delegate Dog ReturnDogDelegate();

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

        static void Main(string[] args)
        {
            // Return type of method can be more
            // specific than return type of delegate type
            ReturnDogDelegate del = GenerateTerrier;

            // Invoke through delegate - Method 1
            Terrier t = (Terrier)del();

            // Invoke, Method 2
            Dog d = del();
        }

Note that if we invoke through the delegate, it returns an instance of the parent class.  To assign to the derived class, we need an explicit cast.

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,155 – Return Value Compatibility when Assigning to Delegate Types

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