Why can\'t I add a delegate to my interface?
As others have mentioned, you can only define delegates outside of the interface.
There is little to nothing wrong w/ using delegates.
Personally I think that Func<int, double>
is less desirable than using delegates:
It is old news that Events are not thread safe, thus the following code is not ideal:
if (MyFuncEvent != null)
{
MyFuncEvent(42, 42.42);
}
See: http://kristofverbiest.blogspot.com/2006/08/better-way-to-raise-events.html
The safer code is:
MyFuncEventHandler handler = MyFuncEvent;
if (handler != null)
{
handler(42, 42.42);
}
You have to duplicate the signature of the event if you want to save it to a variable (or you could use var
, which I dislike). If you have lots of arguments then this could get very tedious (again, you could always be lazy and use var
).
Func<int, double, string, object, short, string, object> handler = MyFuncEvent;
if (handler != null)
{
handler(42, 42.42, ...);
}
Delegates save you from having to duplicate the signature of the method/event every time you want to assign it to a variable type.