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

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

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 comment