Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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() },     
    };
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading