Search code examples
c#dictionary

How can I use a dictionary to swich between classes according to a integer value?


I have a C# application where I have to switch between classes according to the value of an integer variable. I have a string array "myvar" that should get the values from one of the classes (myclass1, myclass2, myclass3....) according to the value of an integer variable (var1). Currently, I am using the following code. I want to shorten my code by using a dictionary. I have once used a dictionary for translating a string variable to a list of strings. But I cannot adapt it to my current use case because here I have to switch between classes. Is it possible to use a dictionary in my case?

myclass1 my_class1 = new myclass1();
myclass2 my_class2 = new myclass2();
myclass3 my_class3 = new myclass3();
//several other classes


int var1 = 0;
string[] myvar= new string[999];


public void my_method()
{
  for(int j = 0; j < 999; j++)
  {
     if (var1==1)
     {
       myvar[j] = my_class1.varlist[j];
     }
     if (var1==2)
     {
       myvar[j] = my_class2.varlist[j];
     }
     if (var1==3)
     {
       myvar[j] = my_class3.varlist[j];
     }
     // same for the rest classes

  }      

}
                            

Solution

  • You could define a common interface and have a dictionary based on that.

    E.g.

    interface IMyClass {
      int GetItem(int index);
    }
    
    class MyClass1 : IMyClass {
      public int GetItem(int index) {
        // actual code here...
      }
    }
    
    Dictionary<int, IMyClass> myClasses = new {
            { 1, new MyClass1() },     
            { 2, new MyClass2() },     
            { 3, new MyClass3() },     
        };