Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call non-static method from static method c# [duplicate]

Tags:

c#

oop

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.

like image 575
Mou Avatar asked Nov 28 '22 10:11

Mou


1 Answers

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();
        }
    }
}
like image 175
dlev Avatar answered Dec 15 '22 14:12

dlev