title: Best way to switch behavior based on type
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/298976/c-sharp-is-there-a-better-alternative-than-this-to-switch-on-type">C# - Is there a better alternative than this to ‘switch on type’?</a>  </p>
  </blockquote>
  
  
  
  <p>Consider the classic:</p>
  
  <pre><code>class Widget { }
  class RedWidget : Widget { }
  class BlueWidget : Widget { }
  </code></pre>
  
  <p>For the most part, in my UI, I can treat all <code>Widget</code>s the same.  However, there are minor differences, which I need to <code>if</code> or <code>switch</code> through.</p>
  
  <p>Possible approaches:</p>
  
  <p><strong>Enum Indicator</strong> - set by constructor</p>
  
  <pre><code>enum WidgetVariety { Red, Blue }
  
  class Widget {
      public WidgetVariety Variety { get; protected set; }
  }
  
  class RedWidget : Widget {
      public RedWidget() {
          Variety = Red;
      }
  }
  
  // Likewise for BlueWidget...
  
  switch (mywidget.Variety) {
  case WidgetVariety.Red:
      // Red specific GUI stuff
  
  case WidgetVariety.Blue:
      // Blue specific GUI stuff
  }
  </code></pre>
  
  <p><strong>Use <code>is</code></strong></p>
  
  <pre><code>Widget w = ...;
  if (w is RedWidget) {
      (RedWidget)w ...
  }
  else if (w is BlueWidget) {
      (BlueWidget)w ...
  }
  </code></pre>
  
  <p>The reason I've resorted to this is 1) Most of the code is already somewhat written this way, but much uglier.  2) 90% of the code is identical - basically just one column in a GridView needs to be handled differently depending on the type.</p>
  
  <p>Which would you recommend? (Or anyone have a better solution?)</p>
  
  <hr>
  
  <p><strong>Edit</strong> I know I'll probably be recommended to the Visitor Pattern, but that simply seems to complicated for sparse, minor differences in this case.</p>
  
  <p><strong>Edit 2</strong>
  So one particular difference I was having a hard time sorting out is this column that is different between the two types. In one case, it retrieves a <code>bool</code> value, and assigns that to the grid cell. In the other case, it gets a string value. </p>
  
  <p>I suppose in this case, it should be obvious that I could define:</p>
  
  <pre><code>public object virtual GetColumn4Data();
  
  public override GetColumn4Data() { return m_boolval; }
  
  public override GetColumn4Data() { return m_mystring; }
  </code></pre>
  
  <p>This felt wrong to me initially, due to the use of <code>object</code>. However, that <em>is</em> the type of the property that I am assigning to in the cell, so <strong>of course</strong> this makes sense!</p>
  
  <p>Too long at the office today it seems...</p>