Question

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;
        }
    }
}

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top