Search code examples
c#.netdelegates

Why Invoke method of constructed delegate class is virtual?


I've seen in CLR via C# and in codeproject article Delegate Behind the Scenes that when C# compiler sees this

public delegate void MyDelegate(int intValue);

it actually generates something like this

class MyDelegate : System.MulticastDelegate
{
    public virtual void Invoke(Int32 intValue);

    ...
}

Question is, why Invoke method is virtual? Can this generated delegate type be inherited? From the CLR point of view looks like it can. But why? Why not generating sealed class so there will be no virtual methods lookup penalty at runtime?


Solution

  • This is quacks-like-a-duck typing. Similar kind of typing that makes System.Int32, a value type, derived from ValueType, a reference type. Makes no sense, illegal in C#, but actually behaves that way. The real implementation of a delegate's Invoke method is buried in the CLR and is a static function written in C++.

    But sure, annotating it as virtual makes somewhat sense because it behaves like a virtual method. The actual code that executes is not fixed like it is with a non-virtual class method. Even harder to reason out is what the proper model should be for a delegate that's bound to a static method. A virtual method that's static?

    It is just a virtual duck.

    Reading up on function pointers as used in C could help you get a better mental model for delegates. A delegate is a function pointer with bells on, it can also store the target object. C# lacks the syntax to express this another way.