I'm using c#.
I have class
class A
{
public void MyMethod(int x){//Do something...};
}
How can I call MyMethod
without creating an instance of Class A
?
Can I use delegate/Action or something else to do that?
*Without changing MyMethod to static function
Thanks
You can do this... but you really, really shouldn't:
// DO NOT USE THIS CODE
using System;
public class Evil
{
public void Method()
{
Console.WriteLine($"Is this null? {this == null}");
}
}
class Test
{
static void Main()
{
var method = typeof(Evil).GetMethod("Method");
var action = (Action<Evil>) Delegate.CreateDelegate(typeof(Action<Evil>), method);
action(null);
}
}
Output:
Is this null? True
The CreateDelegate
call creates an open instance delegate. From MSDN:
In the .NET Framework version 2.0, this method overload also can create open instance method delegates; that is, delegates that explicitly supply the hidden first argument of instance methods. For a detailed explanation, see the more general CreateDelegate(Type, Object, MethodInfo) method overload, which allows you to create all combinations of open or closed delegates for instance or static methods, and optionally to specify a first argument.
We then invoke the method passing null
as the argument, so the method is invoked with this
being null
.
But you absolutely should not do this and if the interviewer really expected you to know about this, then that's more of a reflection on them than it is on you.
Instance methods are clearly intended to be invoked on actual instances.
See more on this question at Stackoverflow