In an Interview Interviwer asked to me can we create instance of a class at run time and invoke all methods of class through code? The sample code for the class TestClass is below
public class TestClass
{
public int ID
{
get;
set;
}
public string Name
{
get;
set;
}
public float Salary
{
get;
set;
}
public string Department
{
get;
set;
}
public int Add(int a, int b)
{
return a + b;
}
public int Sub(int a, int b)
{
return a - b;
}
}//end class
Now I want to create instance of this class at run time and call all its methods and properties at run time, can any one explain how can I archive this. 2. what is the benefit/uses to call the method like this way?
Yes, it's possible.
To create an instance you would use :
Type classType = Type.GetType("TestClass");
object instance = Activator.CreateInstance(classType);
And then calling Sub(23, 42)
on instance
looks like :
classType.InvokeMember("Sub", BindingFlags.InvokeMethod, null, instance, new object[] { 23, 42 });
Reflection is used (for example) when you don't know types at compile time and wish to discover them at runtime (for example in external dlls, plugins, etc).
I think he was asking about reflection. There is a ton of information on this topic both here and on google.
Basically, the reason why you would want to do this is, that you don't know the concrete type at compile time and need to find it out dynamically at run time.
One example is a simple plugin system, where you require the plugin to implement a certain interface. At runtime, you load all assemblies in the designated folder and using reflection, you search for classes that implement the interface and then create an instance of that class and call methods on it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With