title: Dynamically casting classes
body: <pre><code> class Base
      {
          virtual public void FuncA()
          {
              MessageBox.Show("10");
          }
      }
  
      public class BasePlusOne: Base
      {
          public void Bp1MEthod()
          {
              MessageBox.Show("BasePlusOne");
          }
          override public  void FuncA()
          {
              MessageBox.Show("overridden by BasePlusTwo");
          }
      }
  
  
      public class BasePlusTwo : Base
      {
          public void Bp1MEthod()
          {
              MessageBox.Show("BasePlusTwo");
          }
          override public void FuncA()
          {
              MessageBox.Show("overridden by BasePlusTwo");
          }
      }
  
  
      public class One
      {
          public Base GetBase(int i )
          {
              if (i == 1)
              {
                  return new BasePlusOne();
              }
              else
              {
                   return new BasePlusTwo();
              }
          }
      }
  
  
      public partial class Form1 : Form
      {
          public Form1()
          {
              InitializeComponent();
          }
  
          private void button1_Click(object sender, EventArgs e)
          {
              One one = new One();
              Base bp =one.GetBase(2);
  
              BasePlusOne b = (BasePlusOne)bp;
  
              b.Bp1MEthod();
              b.FuncA();
          }
      }
  </code></pre>
  
  <p>As seen I'm using the following code to dynamically select the <code>base</code> class. I am casting the <code>base</code> class received to the appropriate one . This code will throw exception if the returned class is <code>BasePlusOne</code>. Is there any better method to handle this scenario? Is there any other fault with this approach?</p>
  
  <pre><code>One one = new One();
  Base bp =one.GetBase(2);
  
  BasePlusOne b = (BasePlusOne)bp;
  
  b.Bp1MEthod();
  b.FuncA();
  </code></pre>