views:

394

answers:

2

The .net EventHandler is limited to Templates that inherits from EventArgs. How is that done? The implementation (Got to refference in vs) shows the following code:

[Serializable]
public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e);

But i think TEventArgs is just a name. How can I write a typed delegate that is limites to anything that inherits from MyClass?

+2  A: 

Generic type constraints

meandmycode
+3  A: 

TEventArgs is a generic type parameter - but it has a constraint. The actual signature is:

[Serializable]
public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e)
    where TEventArgs : EventArgs

The "where TEventArgs : EventArgs" bit is the type constraint which means you can only supply a type argument for TEventArgs which is EventArgs or a derived class.

Basically it's just "normal" C# generics, just applied to a delegate declaration.

Jon Skeet