i have two classes: Class1
and Class2
class Class1
{
public void method();
}
class Class2
{
public void method();
}
in another place I have the class type and I want to create an instance from it.
type is typeof(Class1
) or typeof(Class2)
public void CreateInstance(Type type)
{
var instance = Activator.GetInstance(type);
instance.method(); //compile error: object doesn't contain method
}
a solution is I define an interface that my classes implement that interface.
interface IInterface
{
void method();
}
public void CreateInstance(Type type)
{
var instance = Activator.GetInstance(type);
((IInterface)instance).method();
}
because I can't access to class definition I can't do this. How can I do this?