I was wondering about the following:
private void RandomEventHandler_Click(object sender, EventArgs e)
{
// SOME CODE IN EVENTHANDLER HERE
}
Button BtnPushed = (Button)sender;
How come it’s possible to cast from an object in the eventhandler to for example a Button, but without having to create an object of the class Button first?
For example like this:
private void RandomEventHandler_Click(object sender, EventArgs e)
{
// SOME CODE IN EVENTHANDLER HERE
}
Button BtnPushed = new Button();
BtnPushed = (Button)sender;
Normally you would have to create an object of a class, which is a reference type before you can work with it.
Please explain. Thx!
I think you might be mixing up things. From the examples you gave, I guess you might be confused by event handlers, and the fact that they usually have a method signature along the lines of
void Handler(object sender, EventArgs args)where sender might be an instance of say aButton.In OOP types can inherit from other types and you can use instances of inherited types as instances of base types, this concept is called Polymorphism. For instance, the
Buttonclass inherits fromObject, somewhere up the inheritance chain. You could say that an inherited type is a specialized kind of its base type:Therefor you could say that when creating an instance of John, that this is also an instance of Person:
But not the other way around, because not all people are
John, some might beSteveorMary, some might even just bePerson:In those cases where we know that it’s an instance of
John, we can tell the compiler “don’t worry, I know what I’m doing”, and explicitly cast thePersonto aJohn:To be clear, it’s important to differentiate between the Type of an instance, and the Type of a variable:
The point with event handlers is that they usually provide the sending control instance in the form of its base type
Object. The instance of the control is still very much aButton, but we’re just looking at it as anObject. Therefor you can cast theObjectto aButton.