C# – Working with “object sender, EventArgs e” inside an Event Handler

c

When I manually cast the object sender and Eventargs e to a class like below what is it I am exactly doing? I know that it allows me to access all the arguments that have been passed and also to manipulate the object sender (as below):

private void Button1_Click(object sender, EventArgs e)
{
    / /casting the arguments
    MouseEventArgs eventargs = e as MouseEventArgs;
    Button button1 = sender as Button;
    // displays which mouse button I used
    MessageBox.Show(eventargs.Button.ToString());
    // displays the name of the button I clicked
    MessageBox.Show(button1.Name.ToString());
    // changes the text of the button
    button1.Text = "Ive changed";
}

I feel like I don't understand how this works, only that it works.

Also, it seems quite easy to write an event handler that serves several objects of the same type, but not one that can handle different types of event or different types of object ie:

private void Generic_Event_Handler(object sender, EventArgs e)
{
    // displays what object and event triggered the handler
    MessageBox.Show(sender.ToString());
    MessageBox.Show(e.ToString());
}        

Is this ever used? Is there a decent explanation of eventhandlers out there?

Best Answer

The following signature

private or protected void EventHandlersName (object sender, EventArgs e)

is the signature that they have all the event handlers in .NET. The parameter called sender is associated with the object on which the event called e was raised.

Why the type of sender is object?

Because all types in .NET has as their base type the type System.Object. So this way it doesn't make any difference if we have a click event on button on a win form, or in a WPF applciation or in an ASP.NET web form button.

Why we should manually cast the object sender?

We should do so, in order we have access to the properties and the methods of the specific type we have in each case.

For instance, all controls may not have a property called Name. Furthermore the base type called System.Object doesn't have. So if you don't cast the object sender to a Button class, then you can't read it's property called Name.

Related Topic