Why do delegate arguments have to match exactly?

Michael asks,

Why do delegate arguments have to match exactly, when creating a delegate using Delegate.CreateDelegate?


delegate void SpecialEventHandler(object sender, SpecialEventArgs e);

Handler function:

void SpecialMethod(object sender, EventArgs e)

Now the following

Delegate.CreateDelegate(typeof(SpecialEventHandler), o, SpecialMethod)

fails, even though EventArgs is a direct parent of SpecialEventArgs. Shouldn’t it be possible to use (safe downcast?) this method as a delegate target?

This is an interesting question. It should be possible to be able to support this, but we don’t support it currently. IIRC, there’s a runtime rule that says that a delegate must match exactly. The fancy name for this is delegate contravariance.

This could be something that we support in the future.

Comments (3)

  1. I think that this is one of those things that should be supported. The reasoning behind it is that if you have set up a method where you can safely downcast (implicitly) the arguments that an event fires, then you are stating that you don’t want the extra information that is being afforded.

  2. Michael says:

    Thanks for the answer. As Nicholas points out this quite useful and should work. I have opted to write adapter functions, but thats not really pretty.

Skip to main content