0

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.

3
  • 3
    simply cast your class to interface and call your method. you don't need reflection Commented Dec 1, 2016 at 7:00
  • Thanks M. kazem Akhgary. It was an interview question to call it using reflection. Commented Dec 1, 2016 at 7:12
  • 1
    using reflection is something at expert level and you only use it when you really need it. that's very rare. if you are good programmer you never need reflection ;) Commented Dec 1, 2016 at 7:13

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! It worked. But now I want to call IntB.MethodFirst. How can I call it?
0
        IntA classA = new ClassA();
        classA.MethodFirst();
        Console.ReadLine();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.