C# · Dotnet

Replacing Conditional statements with Inheritance

Dear Reader,

Today while i was lurking at stackoverflow, i stumbled upon this question. In my discussion with the author, he had asked me give him a small code snippet for replacing his conditional statement i.e switch. So below is the code i gave away. As discussed in the SO thread, this solution has to be chosen wisely. I bet the code is very simple and self explanatory also i bet its not some thing new and amazing. Just gave it a try myself with simple code style 🙂

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            Base b = new Base();
            Console.WriteLine(b.GetText(1));
            Console.WriteLine(b.GetText(2));
            Console.ReadLine();
        }
    }

  class Base
   {
      //Static coz to have only one copy for all Base instances.
       static IDictionary dict;

      static Base()
       {
           dict = new Dictionary();

           dict.Add(1, new One());
           dict.Add(2, new Two());
       }

       public Base()
       {

       }

       protected virtual string DisplayText()
       {
           return string.Empty;
       }

       public string GetText(int number)
       {
           Base b = new Base();
           if (dict.ContainsKey(number))
               b = dict[number];

           return b.DisplayText();
       }
   }

   class One : Base
   {
       protected override string DisplayText()
       {
           return "1";
       }
   }    class Two : Base
    {
        protected override string DisplayText()
        {
            return "2";
        }
    }
}

Thanks & Happy Coding,
Zen 🙂

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s