1st Question:
In PHP there is:
$b = new SomeClass();
$a = "foo";
$b->$a("something"); // This is the same as $b->foo("something");
How do you do this in C#?
2nd Question:
In PHP I can iterate through each method on a class, similar to:
$a = new SomeClass(); // Which implements methodA, methodB;
foreach($method in get_class_methods(SomeClass()))
{
$method("do stuff with each method");
}
How to do this in C#?
3rd Question
PHP has a magic method __call() if a Class does not implement a method it executes it as a default such as if a method doesn’t exist it still can run
class NewClass()
{
// constructor
__call(class name, array of parameters)
{
}
}
so if you do
$a = new NewClass();
$a->thisDoesntExistButWorks("123","abc");
// The method gets "magically created" such as
thisDoesntExistButWorks(array with 123 and abc)....
1 and 2 have been answered more than once. So i’ll attempt 3.
C# does not provide an unknown method method because it doesn’t have to. If you call the Method directly like
a.NonExistentMethod()then the program simply wont compile, and the idea of catching the bad call at runtime is irrelevant.As you have already found out though it it possible to call methods dynamically at runtime by doing
a.GetType().GetMethod("NonExistentMethod").Invoke(a, new object[0]). This will fail with aNullReferenceExceptionbecause the call toGetMethodreturns null. However this situation is detectable, and so maybe we can do something about it. Here is an extension method that behaves as much like PHP as possible. Please note that this is untested, and should never be used in production (or probably even experimental) code.This can by used by doing this
a.CallOrDefault("method name", arg1, arg2);