Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can we create instance of a class at run time and invoke all methods of class through code?

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?

like image 511
Vijjendra Avatar asked May 02 '11 08:05

Vijjendra


2 Answers

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).

like image 171
user703016 Avatar answered Sep 30 '22 03:09

user703016


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.

like image 32
Daniel Hilgarth Avatar answered Sep 30 '22 04:09

Daniel Hilgarth