C# finding sender

smitten picture smitten · Jan 1, 2013 · Viewed 7k times · Source
private void buttonCheck(object sender, EventArgs e)
{
   Type x = sender.GetType();
   var y = Activator.CreateInstance(x); //sends me back to the original problem : sender is an object, not a usable object.

   var x = (Button)sender;  // == button, but you never know what sender is until it's already in this function... so 
   dynamic z = sender; //gives you the image of sender i'm looking for, but it's at runtime, so no intellisense/actual compiletime knowledge of what sender is.
}

how do you go about creating a usable instance of sender without prior knowledge of the class sender is actually bringing to this method?

Answer

D Stanley picture D Stanley · Jan 1, 2013

In the vast majority of cases you know what control(s) will be firing the event because you (the programmer) wire them up. For example, if you wire this event up to a button (or even multiple buttons), You know the sender is a Button so you can just cast:

var b = sender as Button;

or

var b = (Button)sender;

either one will give you full intellisense.

If you wire up this event to multiple control types, your best bet is to check each possible type:

if(sender is Button)
//  cast to Button
else if (sender is TextBox)
//  cast to TextBox
else is (sender is CobmoBox)
//  cast to ComboBox

It may seem messy, but since you haven't stated what you actually want to do in the event handler that's the cleanest way in one event to handle multiple possible sender types.

Another option would be to just create multiple event handlers (one for each type) and wire them up to their respective types. I can't think of many code-reuse scenarios between a Button and a TextBox.