scraimer scraimer - 9 months ago 32
C# Question

How do I create a new delegate type based on an existing one, in C#?

Is there any way that I can create a new delegate type based on an existing one? In my case, I'd like to create a delegate

which would have the same functionality as

Why do I want this? To take advantage of compile-time type-checking, of course! This way, I can have two different delegates:
, and never the twain shall be confused - even if they are both functionally identical to

Is there syntax to do this sort of thing?

Oh, and code like:

using MyRightClickHandler = EventHandler<MouseEventArgs>

isn't good enough. It doesn't do any type-checking, since it doesn't actually create a new type. And I'd have to paste such a line into every code file in which I would refer to


Well, it's as simple as copying the delegate declaration from the original. There's nothing in C# to do this automatically, but I can't see it's much of a burden:

public delegate void MyLeftClickHandler(object sender, MouseEventArgs e);
public delegate void MyRightClickHandler(object sender, MouseEventArgs e);

It's not like MouseEventHandler is going to change any time soon...

Have you actually been bitten by bugs due to using the wrong delegates in the wrong places though? I can't remember ever having found this a problem myself, and it seems to me you're introducing more work (and an unfamiliar set of delegates for other developers) - are you sure it's worth it?