xpt xpt - 1 month ago 8
C# Question

Using delegates with non static methods in C#

Asking the same question as
Using delegates with non static methods [no picked answer]
so as to bring a closure to it.

So I use @Adam Marshall's solution, it works, but as soon as I start using it, i.e.,

Testit()
:

using System;

public class TestClass
{
private delegate void TestDelegate();
TestDelegate testDelegate;

public TestClass()
{
testDelegate = new TestDelegate(MyMethod);
}

public static void Testit()
{
testDelegate();
}

private virtual void MyMethod()
{
Console.WriteLine("Foobar");
}
}

public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
TestClass.Testit();
}
}


It started to give the followig Error:


A object reference is required for the non-static field, method, or property


You can test it out here .
How to fix it? (Please fix it if possible instead of directing me to other posts, I've read them but am not able to understand them) Thx.

Answer Source

Either everything has to be static or everything has to be instance. You're getting in trouble because you are mixing and matching.

Everything static:

using System;

public class TestClass
{
    private delegate void TestDelegate();
    static TestDelegate testDelegate;    //<-- static

    static TestClass()                   //<-- static
    {
        testDelegate = new TestDelegate(MyMethod);
    }

    public static void Testit()
    {
        testDelegate();
    }

    private static void MyMethod()
    {
        Console.WriteLine("Foobar");
    }
}

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");
        TestClass.Testit();
    }
}

Everything instanced:

using System;

public class TestClass
{
    private delegate void TestDelegate();
    TestDelegate testDelegate;

    public TestClass()
    {
        testDelegate = new TestDelegate(MyMethod);
    }

    public void Testit()   
    {
        testDelegate();
    }

    private void MyMethod()
    {
        Console.WriteLine("Foobar");
    }
}

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");
        var t = new TestClass();
        t.Testit();   //<-- non-static
    }
}

Output (same in both examples):

Hello World
Foobar