Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>A bigger question is "Why always use EventArgs, even if your event does not need any information?". If EventArgs did not have a public constructor you'd not be able to do this.</p> <p>A good advantage is that if in future you do want to pass information any existing code will still compile. For example the following class started out using just EventArgs, but now passes a string containing some "useful information".</p> <pre><code>class SomeEventSource { public event EventHandler&lt;SomeEventArgs&gt; MyEvent; public void FireTheEvent() { MyEvent(this, new SomeEventArgs("This information is interesting")); } } class SomeEventArgs : EventArgs { public SomeEventArgs(string interestingInformation) { InterestingInformation = interestingInformation; } public string InterestingInformation { get; private set; } } </code></pre> <p>This client code was written before the change, but it still compiles. If the original had not used EventArgs then the change would have been more expensive to implement.</p> <pre><code>class SomeClient { private readonly SomeEventSource _source; public SomeClient() { _source = new SomeEventSource(); _source.MyEvent += source_MyEvent; } public void RunTest() { _source.FireTheEvent(); } void source_MyEvent(object sender, EventArgs e) { // Do something } } </code></pre> <p>There is an annotation on EventArg's constructor which enables it to be optimised in certain situations. EventArgs itself is marked Serializable and ComVisible. Any subclass you create will take advantage of these and fit the pattern.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload