In all the .NET book I've read the guide line for implementing events explains that you need to subclass EventArgs
and use EventHandler. I looked up more info on http://msdn.microsoft.com/en-us/library/ms229011.aspx, and it says "Do use System.EventHandler instead of manually creating new delegates to be used as event handlers." I understand that there are important reasons to use EventArgs, but my question is not "Should I do it this way?", but "Can I do it this way?".
Is there any reason that I can't use a generic delegate instead of an EventHandler
with my events? For example, if I want a strongly-typed sender (anyone else get annoyed by that object sender
?) .
To explain what I mean better, is there any reason the following won't work?
public class IoC
{
public AbstractFactory GetAbstractFactory()
{
var factory = new AbstractFactory();
factory.CreateObject += ()=>new object();
return factory;
}
}
public class AbstractFactory
{
public event Func<object> CreateObject;
private object OnObjectCreated()
{
if(CreateObject == null)
{
throw new Exception("Not injected.");
}
return CreateObject();
}
private object _injectedObject;
public object InjectedObject
{
get
{
if(_injectedObject == null)
{
_injectedObject = OnObjectCreated();
}
return _injectedObject;
}
}
}
It's just convention, and no requirement of the language. You can use any delegate type as an event.
The standard
EventHandler<T>
signature has a few advantages though:EventArgs
parameter. This wouldn't work if you had one parameter for each thing you want to pass into the eventhandler.EventArgs
base-class can subscribe to any event following the conventionEventHandler<T>
which appear on all events.void
. Other return types don't make much sense as eventhandlers.