Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it useful to inherit from EventArgs?

Tags:

c#

.net

asp.net

I don't understand why inheriting from 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; } } 
}

In the code above, how can I use this inheritance?

I also want to learn how I can call this code block from default.aspx

like image 862
ALEXALEXIYEV Avatar asked Apr 26 '09 06:04

ALEXALEXIYEV


1 Answers

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.

like image 155
Jon Skeet Avatar answered Sep 27 '22 18:09

Jon Skeet