Possible Duplicate:
Call non-static method from static method c#
We can call non-static method from static method creating instance. Code:
public class Foo
{
public void Data1()
{
}
public static void Data2()
{
Foo foo = new Foo();
foo.Data1();
}
}
However, I heard that non-static method can be called from static method with the help of delegate. is it true? If yes, then how? Please guide me with sample code. Thanks.
This is one method for calling a non-static method via a delegate. Note that it is a two-step process, since to call a non-static method, you absolutely need an instance of the class. I would also note that there is almost certainly a better way to do what you want to do, since needing to call a non-static method from a static method despite not wanting to use an object instance makes it sound like the non-static method should be static.
public class MyClass
{
private static Action NonStaticDelegate;
public void NonStaticMethod()
{
Console.WriteLine("Non-Static!");
}
public static void CaptureDelegate()
{
MyClass temp = new MyClass();
MyClass.NonStaticDelegate = new Action(temp.NonStaticMethod);
}
public static void RunNonStaticMethod()
{
if (MyClass.NonStaticDelegate != null)
{
// This will run the non-static method.
// Note that you still needed to create an instance beforehand
MyClass.NonStaticDelegate();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With