I have a function that takes a control as a parameter and depending on the type of control (for example: TextBox, ComboBox, RadioButton, etc.), it executes code like:
internal static void DoSomething(Control control) { if (control is Button) { // code for button } else if (control is CheckBox) { // code for CheckBox } else if (control is TextBox) { // code for TextBox } // etc..... }
I am wondering if this is the best way to do it.
I know some other ways to do the same (for example: searching for a control type using GetType() , including a string representation of this type), and the Microsoft code analysis tool tells me to use instead as' of 'is' like this ( because it is better in performance):
internal static void DoSomething(Control control) { Button button = control as Button if (button != null) { // code for button } else { CheckBox checkBox = control as CheckBox; if (checkBox != null) { // code for CheckBox } else { TextBox textBox = control as TextBox; if (textBox != null) { // code for TextBox } // etc..... } } }
but I find this last solution quite verbose and not very practical to read. I would like to be able to directly include a control type, but I cannot do this without resorting to using a string representation (which I don't like at all), since the case switch statement cannot contain a variable.
So what really is the best way to get the job done? and what do you think is the best way to do it? (not necessarily in terms of performance, but, for example, with the ability to read code)
Edit: since a lot is happening on the topic βwhy I use one common function, and not many types-specific methodsβ, here is another information:
I get a control variable from another part of the application I'm working on (type = Control), and I do something with this variable, depending on its type.
so in principle I have a choice between two options: either I use one common function, or I check the type of control in the body of the function so that at some point I execute the correct part of the code (the parameters that I have chosen now, but this can change ), or I check the type of control before calling the type method.
in any case, I have to turn on the type of control at some point, and this is the question of my question (no matter what I do with it, so to speak).