Search code examples
c#eventsdelegatesinitializer

Event default initializer


I used to utilize the following:

public event EventHandler OnComplete = delegate { };

I'm not sure, how this is called, is this an "event default initializer"??

But the problem appeared to be when I derived from EventArgs, created my own EventHandler and decided to use the same approach. Please, see:

public class MyEventArgs : EventArgs
{
    int result;
    public int Result
    {
        get
        {
            if (exceptionObject == null)
                return result;
            else
                throw new InvalidOperationException();
        }
        internal set { result = value; }
    }

    Exception exceptionObject;
    public Exception ExceptionObject
    {
        get { return exceptionObject; }
        internal set { exceptionObject = value; }
    }
}

public delegate EventHandler MyEventHandler(object sender, MyEventArgs e);

public class MyOperation
{
    public event MyEventHandler OnOperationComplete = delegate { };
}

So, the line

public event MyEventHandler OnOperationComplete = delegate { };

causes the problem.

How can I make the proper default initialization for "my" events?


Solution

  • public event MyEventHandler OnOperationComplete = (sender, args) => { return null; };
    

    I also think you meant to say:

    public delegate void MyEventHandler(object sender, MyEventArgs e);
    

    not

    public delegate EventHandler MyEventHandler(object sender, MyEventArgs e);