C# Typeresticted delegate with Template
Question
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?
Solution
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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow