Is it possible to instantiate a class at runtime and call all methods of the class through code?

In an interview, did Interviwer ask me to instantiate the class at runtime and call all the methods of the class through code? Sample code for the TestClass class 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 instantiate this class at runtime and call all its methods and properties at runtime, can anyone explain how I can archive it. 2. What is the benefit / use of a method call in this way?

+4
source share
2 answers

I think he was asking for thought. There is a ton of information on this topic here and on Google.
Basically, the reason you would like to do this is because you don’t know the specific type at compile time and must find it dynamically at runtime.
One example is a simple plug-in system where a plug-in is required to implement a specific interface. At run time, you load all the assemblies in the specified folder and use reflection, you look for classes that implement the interface, and then instantiate this class and call methods on it.

+2
source

Yes it is possible.

To create an instance that you would use:

 Type classType = Type.GetType("TestClass"); object instance = Activator.CreateInstance(classType); 

And then calling Sub(23, 42) on instance looks like this:

 classType.InvokeMember("Sub", BindingFlags.InvokeMethod, null, instance, new object[] { 23, 42 }); 

Reflection is used (for example) when you do not know the types at compile time and want to detect them at runtime (for example, in external dlls, plugins, etc.).

+4
source

All Articles