Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Switching on types is definitely lacking in C# (<strong>UPDATE: in C#7 / VS 2017 switching on types is supported - <a href="https://stackoverflow.com/questions/298976/is-there-a-better-alternative-than-this-to-switch-on-type/299001#299001">see Zachary Yates's answer below</a></strong>). In order to do this without a large if/else if/else statement, you'll need to work with a different structure. I wrote a blog post awhile back detailing how to build a TypeSwitch structure.</p> <p><a href="http://blogs.msdn.com/jaredpar/archive/2008/05/16/switching-on-types.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/jaredpar/archive/2008/05/16/switching-on-types.aspx</a></p> <p>Short version: TypeSwitch is designed to prevent redundant casting and give a syntax that is similar to a normal switch/case statement. For example, here is TypeSwitch in action on a standard Windows form event</p> <pre><code>TypeSwitch.Do( sender, TypeSwitch.Case&lt;Button&gt;(() =&gt; textBox1.Text = "Hit a Button"), TypeSwitch.Case&lt;CheckBox&gt;(x =&gt; textBox1.Text = "Checkbox is " + x.Checked), TypeSwitch.Default(() =&gt; textBox1.Text = "Not sure what is hovered over")); </code></pre> <p>The code for TypeSwitch is actually pretty small and can easily be put into your project.</p> <pre><code>static class TypeSwitch { public class CaseInfo { public bool IsDefault { get; set; } public Type Target { get; set; } public Action&lt;object&gt; Action { get; set; } } public static void Do(object source, params CaseInfo[] cases) { var type = source.GetType(); foreach (var entry in cases) { if (entry.IsDefault || entry.Target.IsAssignableFrom(type)) { entry.Action(source); break; } } } public static CaseInfo Case&lt;T&gt;(Action action) { return new CaseInfo() { Action = x =&gt; action(), Target = typeof(T) }; } public static CaseInfo Case&lt;T&gt;(Action&lt;T&gt; action) { return new CaseInfo() { Action = (x) =&gt; action((T)x), Target = typeof(T) }; } public static CaseInfo Default(Action action) { return new CaseInfo() { Action = x =&gt; action(), IsDefault = true }; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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