C. Carrasquinho C. Carrasquinho - 1 month ago 36
C# Question

C# Get the name of an object without knowing its 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.

Answer

just cast it to its base type Control

var name = ((Control)sender).Name