C. Carrasquinho C. Carrasquinho - 29 days ago 13
C# Question

C# Get the name of an object without knowing it's Type

private void function(object sender, EventArgs e)


Hello!
Is it possible to get the Name, without using a variable?

if(sender.getType().Name == "Button"){
Button btn = sender as Button;
ObjName = btn.Name
}
if(sender.getType().Name == "CheckBox"){
CheckBox cbx= sender as CheckBox;
ObjName = cbx.Name
}


I have a function that works with a lot of different object types, and the only thing i need is the Name.

Cheers!

Answer

just cast it to its base type Control

var name = ((Control)sender).Name