I am looking for a way to be able to instantiate multiple classes that have the same method.
looking to do something where I can pass in the name of the class as a string. Here is what I have so far while it compiles it will not run as I am not instantiating the class correctly.
Im doing something like this but I know I am missing something. If anyone can help I would appreciate it.
public class useMyClass{
public runMyClass(string st1, list<string> mysts, string myClass){
classProcessor cp = new myClass1(); // this works
classProcessor cp = new myClass2(); // this works
// Here I just want to be able to do using the string variable myClass (myClass1 or myClass2 ) could be the string value
//classProcessor cp = new Class(myClass);
// This does not work always null
classProcessor cp = (classProcessor)System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(myClass);
cp.myMethod(st1,mysts);
}
}
file1: classProccessor.cs
public interface classProccessor{
public void myMethod(string st1, list<string> mysts);
}
file2: myClass1.cs
public class myclass1 : classProccessor{
public void myMethod(string st1, list<string> mysts){
//do something;
}
}
file3: myClass2.cs
public class myclass2 : classProccessor{
void myMethod(string st1, list<string> mysts){
// do something different;
}
}
How can I create a new instance of a class using the string name of the class through the use of the interface? I know I must be missing something simple.
classProcessor cp = (classProcessor)System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(myClass); // makes it past here cp.myMethod(st1,mysts); // says null reference exception use "new" keyword
– user2300516 Apr 20 '13 at 03:07