Windows Forms casting Button class

2.9k Views Asked by At

Please explain.

In line 3 I dont know why class button is used to cast the sender object,

how does sender object functions in line 3

and what is the reason of using Button class in line 3?

1. private void button_Click(object sender, EventArgs e)
2. {
3.      Button btn = (Button) sender;
4.      textBox1.Text = textBox1.Text + btn.Text;
5. }
3

There are 3 best solutions below

0
On BEST ANSWER

As you can see from the declaration

private void button_Click(object sender, EventArgs e)

the only guarantee is that sender is of type object; and object instance doesn't have Text property

private void button_Click(object sender, EventArgs e) {
  // sender.Text doesn't compile - sender being Object doesn't have Text property
  textBox1.Text = textBox1.Text + sender.Text;
}

so you have cast to a type which has Text property, a most accurate way to Control:

private void button_Click(object sender, EventArgs e) {
  // Control: Button, TextBox, Panel etc.
  Control ctrl = sender as Control;

  // If we succeed in cast (i.e. sender is a Control)
  if (ctrl != null)
    textBox1.Text = textBox1.Text + ctrl.Text;
}

When explicit cast to Button

Button btn = (Button) sender; // dangerous code

can be dangerous: you may want, say, add myPanel.Click += button_Click while you don't check cast's result (treat myPanel as Button and let it be).

2
On

Because c# doesn't know Which class is used so you must tell the compiler that object is of type Button.

if the object isn't of type button you wil get an InvalidCastException

a cleaner way would be

Button button = sender as Button;
if(button != null)
{
   //action
}
0
On

These event handlers all include the object sender parameter to indicate which object instance raised the event. This allows you to re-use the event handler for multiple buttons:

button1.Click += button_Click;
button2.Click += button_Click;

The cast to Button is only because the author of the code has remembered that he/she is only using this event handler for Buttons - reusing this handler for other classes would cause an InvalidCastException to occur.