0

I'm trying to learn about events and I have a task to create EventArgs info classes, derived from EventArgs. I'm not sure what this means and how I should do?

RpgNick
  • 110
  • 1
  • 9
3D-kreativ
  • 9,053
  • 37
  • 102
  • 159

3 Answers3

2

Event arguments are made to deliver additional information about the event that fired, for instance a value that was changed or an item's ID. The signature of event handlers contains a sender and EventArgs.

Since EventArgs are pretty empty, you usually implement your own class:

public event EventHandler<FooEventArgs> Foo; // produces handler(object sender, FooEventArgs e)

public sealed class FooEventArgs : EventArgs
{
    public FooEventArgs(int bar)
    {
        this.Bar = bar;
    }

    public int Bar { get; private set; }
}

This is just a normal subclass like you would create everywhere else. If you do not need to pass more information, use EventArgs.Empty (static field).

Matthias Meid
  • 12,455
  • 7
  • 45
  • 79
  • Interesting, is delegates involved in this also? – 3D-kreativ Aug 09 '12 at 08:33
  • 1
    An event *is* basically a special form of a delegate: An `EventHandler` is a multicast delegate with parameters `object sender` and `T e`. Multicast means that the delegate can point to multiple methods that are executed sequentially. Is this helpful? It's a little hard to describe in a comment - digging into RpgNick's link may help you too. :) – Matthias Meid Aug 09 '12 at 08:41
  • Do people typically leave child classes of EventArgs open or sealed? – Kyle Baran May 18 '15 at 08:08
  • 1
    @KyleBaran My using `sealed` here didn't have an EventArgs-specific reason. I tend to seal classes unless I want to use (and think about) inheritance. General terms popping up in this context are the Liskov substitution principle, the open/closed principle, "prefer composition over inheritance" and this discussion http://stackoverflow.com/questions/1450250/purpose-of-final-and-sealed – Matthias Meid May 18 '15 at 18:23
1

Try this

public class EventArgsInfo : EventArgs
{
  public string MyCustomProperty { get;set; }
}
JohnnBlade
  • 4,261
  • 1
  • 21
  • 22
  • Use mutable `EventArg` object with care. One instance is shared by all handlers, therefore unintended modifications may have nasty side effects. Of source there are cases where this behaviour is wanted, like requesting to cancel an action or passing data back. – Matthias Meid Aug 09 '12 at 08:28
0

EventArgs represents a type with arguments given to the event (hence the name).

The standard EventArgs type includes a minimal amount of information (maybe even none). Best practice is to create your own inheritance of it (for each custom event you create) and extend the arguments with your needs for your specific event.

For more information check out the MSDN documentation on the EventArgs class. It contains a nice example of how a custom EventArgs class can be created and used.

Gerald Versluis
  • 30,492
  • 6
  • 73
  • 100