0

In Java I can check if a method named "addNumbers" exists in a class "Calculate" by doing this:

Class<?> c = Class.forName("com.example.package.Calculate");
Method m = c.getMethod("addNumbers", int.class, int.class);
m.invoke(5,7)

What is the C# equivalent for this example?

khelwood
  • 55,782
  • 14
  • 81
  • 108
linuxman
  • 147
  • 1
  • 1
  • 8
  • 3
    Erm, why not just call this method from your test? That way you'll get a compile-time error if the method doesn't exist, and you also get the chance to test what the method *does* – canton7 Mar 29 '22 at 08:44
  • 1
    I can't understand why you'd need to do this in a statically typed language (which both Java and C# are). – ProgrammingLlama Mar 29 '22 at 08:47
  • Because I want to test if the pupils implemented the method "addNumbers" from the exercise task. It works in java, so I assume there must be a c# equivalent for this approach. – linuxman Mar 29 '22 at 08:47
  • It's called "reflection". – ProgrammingLlama Mar 29 '22 at 08:47
  • 4
    Though you can do it by reflection, there are cleaner ways to enforce implementing a method. Why don't you just let the pupils implement an `ICalculator` interface with an `AddNumbers` method? – György Kőszeg Mar 29 '22 at 08:50

0 Answers0