#1,154 – Input Parameter Compatibility when Assigning to Delegate Types

When you assign a method to an instance of a delegate type (or pass a method name to a method that takes a delegate), the types of the parameters in the method will normally exactly match the types in the declaration of the delegate type.

You can, however, assign a method when the type of an input parameter for a delegate is derived from the corresponding parameter type in the method.  This is shown in the second chunk of code, below.  When you invoke using the delegate, however, you’ll still need to pass an object whose type is the more derived type.

            // Delegate/Method = string/string
            AcceptString asd1 = StringMethod;
            asd1("s");  // ok
            // asd1(new object());    // Error

            // Delegate/Method = string/object
            //   Assignment works, but must invoke with string
            asd1 = ObjectMethod;     // ok
            //asd1(new object());    // Error
            asd1("s");               // works--string converted 

            // Delegate/Method = object/object
            AcceptObject asd2 = ObjectMethod;
            asd2("s");               // ok
            asd2(new object());      // ok

            // Delegate/Method = object/string
            //   Asignment does not work
            // AcceptObject asd3 = StringMethod;   // Error

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

2 Responses to #1,154 – Input Parameter Compatibility when Assigning to Delegate Types

  1. Pingback: Dew Drop – August 6, 2014 (#1830) | Morning Dew

Leave a comment