How to initiate class with interface if you only know the class name in
string - C#
I have a interface named IClass declaring the method Calculate as below:
public interface IClass
{
public int Calculate(int x);
}
Also I have 2 different classes implementing the above mentioned
interface, Class1 and Class2:
public class Class1: IClass
{
public int Calculate(int x)
{
// do some calc with method 1 here
}
}
public class Class2: IClass
{
public int Calculate(int x)
{
// do some calc with method 2 here
}
}
And then I want to call it from main class, however there is restriction
where I don't know the class type, I only know the class string name
(because it's a class library - other people may make the code for it).
The question is: how can I instantiate the particular class (and invoke
the method Calculate) by knowing only its name ?
public class MainForm()
{
public int CalcUsing(string classname, int x)
{
IClass myclass = new Type(typeof(classname))() // doesn't work here
int result = myclass.Calculate(x);
return result;
}
}
No comments:
Post a Comment