tags:

views:

90

answers:

6

If I am writing code to handle an event from a control on a form as follows:

 private void btnButton_Click(object sender, EventArgs e)
 {
        Button btn = (Button)sender;
        btn.Text = "Button pressed"
 }

Should I always cast the sender object to its correct type (as I'm doing above), or is it better to explicitly reference the control name, like:

 private void btnButton_Click(object sender, EventArgs e)
 {
        btnButton.Text = "Button pressed"
 }

What's the best practice here? I guess I'm probably worrying about this too much though...

+4  A: 

I prefer to reference the button directly (option 2), because it easier to search where the button is referenced and the text is changed.

Grzenio
+1 for easy maintainability
Rob Stevenson-Leggett
However, this fails if you've bound the smae method to multiple controls. In that case, sender could be any of several controls, so the assumption of sender's identity fails. (See Rob Stevenson-Leggett's answer.)
Mike Hofer
I would not be naming the routine handling the event <control_name>_<event name> if it is handling multiple events.
RS Conley
+4  A: 

Personally I use sender if I've bound the same method to multiple controls e.g.

 private void checkBox_Click(object sender, EventArgs e)
 {
    CheckBox box = (CheckBox)sender;
    myDataObject.SomeOption = box.Value;
 }

I think it's better to reference the control directly if you can for maintainability.

Bear in mind that dynamically created controls will need to use the sender method also.

Rob Stevenson-Leggett
This method works, especially if you're adding controls dynamically to the page. +1
Mike Hofer
+2  A: 

It really depends on the application. In some cases (usually small straightforward forms) it's fine to reference the control property. In some cases (any time you have programmatically added controls) it's absolutely necessary to use the casting method.

C. Ross
+2  A: 

If you have separate event handler for each control - use control directly.

If you have one event handler for few controls - use casting to sender.

In other words, use control directly as often as it's possible, imho.

abatishchev
A: 

I would use the first option if the handler applies to a particular control only. The second option is good for general handlers, like handling all CheckBoxes on a page or in some control (the way Rob presented it).

Pawel Krakowiak
+1  A: 

I would go with #2 for a event handling a single control. For maintainability I do NOT name routines that handle multiple controls _. Instead I make a separate name that indicates that it handle an event for multiple controls for example MultiShapeButtons_Click instead of btnShapeButton1_Click

RS Conley