gliese 581 g gliese 581 g - 4 days ago 5
C# Question

Call interface method using reference of class

I want to call an interface method using the reference of a class which implements that interface. I am using reflection for that but my code is not working and I am getting null object reference exception. The code is give below:

interface IntA
{
void MethodFirst();
}
interface IntB
{
void MethodFirst();
}
class ClassA : IntA, IntB
{
public void MethodFirst()
{
Console.WriteLine("this.ClassA.MethodFirst");
}
void IntA.MethodFirst()
{
Console.WriteLine("IntA.ClassA.MethodFirst");
}
void IntB.MethodFirst()
{
Console.WriteLine("IntB.ClassA.MethodFirst");
}
}
class Program
{
static void Main(string[] args)
{
Type t = Type.GetType("ClassA");
t.GetMethod("MethodFirst").Invoke(Activator.CreateInstance(t,null), null);

Console.ReadLine();
}
}


Please let me know what I am doing wrong over here.

Answer

You need to try creating instance of your class using the full namespace of that class. for example,

Type t = Type.GetType("ConsoleApplication1.ClassA");

In case, if you want to call a method from a particular interface -

Type t = Type.GetType("ConsoleApplication1.ClassA");
t.GetInterface("ConsoleApplication1.IntB").GetMethod("MethodFirst").Invoke(Activator.CreateInstance(t, null), null);
Comments