tags:

views:

152

answers:

3

I don't understand how extending EventArgs is useful.

public class ClickedEventArgs : EventArgs {
  int x;
  int y;
  public ClickedEventArgs (int x, int y) { 
   this.x = x; 
   this.y = y; 
  }
  public int X { get { return x; } } 
  public int Y { get { return y; } } 
}

Code is above. How can i use this inheritance?Also; i want to learn how can i call this code blog from default.aspx

+1  A: 

Here is a example of how you might use your code:

public class MyClass () {        
    public event EventHandler<ClickedEventArgs> ClickedEvent = delegate {};  //Register the event

    protected void SomethingWasClicked(int x, int y) {    
        ClickedEvent(this, new ClickedEventArgs(x,y));   //Invoke the event that is subscribed to
    }

}

public class AnotherClass () {

    public AnotherClass () {
        MyClass mClass = new MyClass();
        mClass.ClickedEvent += new EventHandler(mClass_clickedEvent);
    }

    protected void mClass_clickedEvent(object sender, ClickedEventArgs e) {
        //Retrieve the X parameter that was passed from the MyClass instance
        int x = e.X;  
    }
}
Andreas Grech
+5  A: 

Are you asking why it's useful to derive from EventArgs in the first place? I have to say that with C# 1 it didn't make a lot of sense, because of the way delegate conversion worked - but as of C# 2 it's more sensible. It allows an event handler to be registered with an event even if it doesn't care about the details of the event arguments.

For example:

void LogEvent(object sender, EventArgs e)
{
    Console.WriteLine("Event sent from " + sender);
}

...

textArea.KeyPress += LogEvent;

This works even though Control.KeyPress is an event of type KeyPressEventHandler. C# and .NET don't mind that the signature of LogEvent doesn't exactly match the signature of KeyPressEventHandler - it's compatible enough.

Admittedly this would still be feasible if we didn't have EventArgs at all (you could just use object) but given the EventArgs class and the pattern, it makes sense to derive your own event arguments from EventArgs.

Jon Skeet
There is one very mild advantage to EventArgs over simply using object. The delegate having the signature (object, object) is more prone to a being called errorenously due to typos in the code. With a signature of (object, EventArgs) such a typo is much more likely to be spotted at compile time.
AnthonyWJones
True, yes. I hadn't thought of that before. It's slightly odd, mind you...
Jon Skeet
Oh and EventArgs<TEventArgs> has where TEventArgs : EventArgs so if you want to use this Generic instead declaring your own handler type you need to derive from EventArgs.
AnthonyWJones
+1  A: 

What is really important here is that you can easily UPGRADE your event later to have MORE details and don't break existing decoupled listeners.

Mash