Note that there are some explanatory texts on larger screens.

plurals
  1. POmost effective way to determine a control's type in C#/WPF
    text
    copied!<p>I have a function that takes a control as parameter, and depending on the control's type (e.g.: TextBox, ComboBox, RadioButton etc...), it executes type-specific code:</p> <pre><code>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..... } </code></pre> <p>I am wondering if this is the best way to do.</p> <p>I know of some other ways to do the same thing (e.g.: looking for the control's type using <code>GetType()</code>, switching on the string representation of this type), and Microsoft's code analysis tool tells me to use 'as' instead of 'is' like this (because it is better performance-wise):</p> <pre><code>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..... } } } </code></pre> <p>but I find this last solution rather wordy and not very practical to read. I'd like to be able to switch on the control's type directly, but am unable do to so without resorting to use the string representation (which I don't like at all) as a switch's case statement cannot contain a variable.</p> <p>So what really is the best way to do performance-wise? and what is, in you opinion, the best way to do? (not necessarily performance-wise, but "code-readability-wise" for instance)</p> <p><strong>Edit:</strong> as a lot is going on on the subject of "why do I use one common function and not many type-specific methods", here is some more info:</p> <p>I get a control variable from an other part of the app I'm working on (type = Control) and I have do "do something" with this variable, depending on its type.</p> <p>so basically, I have the choice between 2 options: either I use one common function and check the control's type in the function's body so that I execute the right portion of the code at some point (options I have chosen for now, but this could change), or I check for the control's type BEFORE calling a type-specific method.</p> <p>either way, I have to switch on the control's type at some point, and <em>THIS</em> is the subject of my question (regardless of what I do with it, if I may say so).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload