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. }
As you can see from the declaration
the only guarantee is that
sender
is of typeobject
; andobject
instance doesn't haveText
propertyso you have cast to a type which has
Text
property, a most accurate way to Control:When explicit cast to
Button
can be dangerous: you may want, say, add
myPanel.Click += button_Click
while you don't check cast's result (treatmyPanel
asButton
and let it be).