I'm trying to properly understand Events
and EventArgs
but can't quite get a handle on the whole EventArgs.Empty
property.
EventArgs
implements:
public static readonly EventArgs Empty;
and allows us to create an EventHandler
and call it using:
public event EventHandler<EventArgs> TestHappening;
private void MyMethod()
{
TestHappening( this, EventArgs.Empty );
}
Now I've studied a number of classes based on EventArgs
and none of them seem to implement this so I'm flying a little blind even though I've read all the documentation I could find regarding EventArgs.Empty
. According to the documentation, "The value of Empty is a read-only instance of EventArgs equivalent to the result of calling the EventArgs constructor".
Based on that I've created the following implementation:
public class TestEventArgs : EventArgs
{
public static readonly TestEventArgs Empty;
public bool UpdatedValue { get; private set; }
TestEventArgs()
: this( false )
{
}
public TestEventArgs( bool updatedValue )
{
this.UpdatedValue = updatedValue;
}
}
public event EventHandler<TestEventArgs> TestHappening;
private void MyMethod()
{
TestHappening( this, EventArgs.Empty );
}
Is the use of TestEventArgs.Empty
instancing a class or what exactly is it doing?
Also, even though all the subclasses I checked didn't make use of Empty
, they still have it available, isn't it confusing having an unusable property exposed?
Lastly, based on the various documents I studied, there were two main variances of when to actually instantiate the EventArgs
. Which is considered "more" correct?:
OnTestHappening( new TestEventArgs( false ) );
private void OnTestHappening( TestEventArgs e )
{
var handler = TestHappening;
if ( handler != null )
handler( this, e );
}
vs
OnTestHappening( true );
private void OnTestHappening( bool foo )
{
var handler = TestHappening;
if ( handler != null )
handler( this, new TestEventArgs( foo ) );
}