c# - Why cast the sender of an event to a control type? -


i new asp.net development , trying comprehend why object casting required when dealing event handling.

i reading asp.net 4 unleashed , came across code, not understand purpose of @ all. don't point of cast in following method:

protected void button_click(object sender, eventargs e) {     button btn = (button)sender;     btn.text = (int32.parse(btn.text) + 1).tostring(); }  

the html here:

    first counter: <asp:button id=”button1” text=”0” onclick=”button_click” runat=”server” /> <br /><br /> second counter: <asp:button id=”button2” text=”0” onclick=”button_click” runat=”server” /> 

i don't understand point of casting btn button. can please explain this?

until have learned c# event keyword, , delegate types, difficult comprehend reasoning here. said…

note sender parameter in method declaration has type object. due standard pattern events in .net: delegate type uses object parameter first parameter delegate's signature.

doing way allows small number of delegate types reused wide variety of events. common delegate type used eventhandler, find on wide variety of events in number of classes (hundreds in .net, if not thousand or more).

rather having framework include delegate types each possible sender, method signature uses object. it's event handler (e.g. button_click() method) cast object reference actual type expected.

note in many cases, event handler not need use sender parameter @ all. either attached single event, on object can referenced via instance field in class, or sending object isn't needed @ handling of event (fairly common click events…the reason button object needed here event handler contrived example purpose of reference you're reading).


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -