tags:

views:

382

answers:

2

It is not possible to inherit from System.Delegate or System.MulticastDelegate in C#. It is perfectly possible to do it in MSIL as long as you declare standard 'runtime managed' methods. However, every time I am adding a 'cil managed' method to the type, I am getting:

System.TypeLoadException: Illegal definition for runtime implemented delegate method.

Is it at all possible to extend Delegate/MulticastDelegate?

+7  A: 

Not with your own custom code, in C#. From section 10.1.4 of the C# 3.0 spec:

The direct base class of a class type must not be any of the following types: System.Array, System.Delegate, System.MulticastDelegate, System.Enum, or System.ValueType. Furthermore, a generic class declaration cannot use System.Attribute as a direct or indirect base class.

However, every time you create a delegate type, that automatically derives from MulticastDelegate.

From ECMA-335, section 8.9.3:

While, for the most part, delegates appear to be simply another kind of user-defined class, they are tightly controlled. The implementations of the methods are provided by the VES, not user code. The only additional members that can be defined on delegate types are static or instance methods.

That sounds like it's prohibiting constructors. I'd use a static method in a normal type instead, personally.

Jon Skeet
A: 

You may be interested in looking at the following post from Rick Strahl where he compares different methods of dynamic delegate creation.

alex