Delegates - does the delegate return type have to match the method it is delegating too?

Yes, It has to return the same type and have the same parameters. In other words, the function and the delegate declaration must have the same signature.

Example:

    //Declare delegate (return double with double param)
    public delegate double Squared(double x);

    public class Circle
    {
        private double _radius;


        public static double ValueTimesValue(double Value)
        {
            return Value * Value;
        }

        public double Area(Squared sqd)
        {
            return sqd(_radius) * Math.PI;
        }

        public void CircleCharacteristics()
        {
            Squared Sq = new Squared(ValueTimesValue);
        }
    }

EDIT: If you see the sample code, Squared Delegate and ValueTimesValue function have the same return type and parameters.


From msdn:

A delegate lets you pass a function as a parameter. The type safety of delegates requires the function you pass as a delegate to have the same signature as the delegate declaration.

And another quote from C# specification:

A method and a delegate type are compatible if both of the following are true:

  • They have the same number or parameters, with the same types, in the same order, with the same parameter modifiers.
  • Their return types are the same.

I think it's very good description of compatibility conditions. And as you can see, your code violates second condition, which produces compiler error.


In simple terms, a delegate is a template for a method (hope I don't get bashed too hard for the oversimplification). If you want a visualization, think of it like a lock, and the physical implementation is like a key. A key fits a certain lock and fails in a different lock. Just as a key won't fit in the wrong lock, a method that applies a different template (signature) fails.

So, yes, you need the right signature for the method you wish to "delegate work to". If you want to think more in software terms, a delegate is a contract for the physical implementation it represents, much like an interface is a contract for the actual methods it represents. They are very similar concepts.

Tags:

C#

Delegates