Home > Net >  Calling class based on a dynamic variable in c#
Calling class based on a dynamic variable in c#

Time:09-03

I have several classes that I want to access from another class based on a variable from the calling class.

I know one possible way of accomplishing it by using switch statements but I'm trying to see of another easier solution for it.

Here is the class I want to call from

namespace sample
{
public class callingClass{
  public string ClassName:

  public void loadVar(){
  //I want to call the class and it's methods based on value of ClassName variable. The  classname here is dynamic. It is being set from another class. 

    Get_ClassName classname = new Get_ClassName();
    ClassName =classname.Name

//how can I use this ClassName variable to access

// looking for something like this

ClassName NewVar= new ClassName();
NewVar.Set_variable();
}


}

}
namespace sample
{
public class Test_A{
public override void set_variable(){

//Set some variables here
public string Var1="TestA";
}

}
namespace sample{
public class Test_B{
public override void set_variable(){
//Set some variables here
public string Var1="TestB";
}
}
}
namespace sample 
{

public class Test_C{
public override void set_variable(){
//Set some variables here

public string Var1="TestC";
}
}

}

CodePudding user response:

Looks like you need some polymorphism. Create interface, implement to your Test classes and call them inside main class from inner field with type of that interface. Calling classes by varible name is not good.

public class CallingClass {
    public ITest TestClass; 

    // now you can call  CallingClass.TestClass.AnyITestInterfaceMethod()
}

CodePudding user response:

Here is how I solve my problem:

namespace sample
{
public class callingClass{
  public string ClassName:

  public void loadVar(){
 

    Get_ClassName classname = new Get_ClassName();
    ClassName =classname.Name
Type type = Type.GetType(ClassName);
dynamic NewInstance= Activator.CreateInstance(type);
//now i can access the methods and variables like this:
NewInstance.Set_variable();
NewInstance.Var1
}


}

}
  •  Tags:  
  • c#
  • Related