I am pretty confident that I should be able to use a delegate with a non-static method, but the below is giving me an error:
public class TestClass
{
private delegate void TestDelegate();
TestDelegate testDelegate = new TestDelegate(MyMethod);
private void MyMethod()
{
Console.WriteLine("Foobar");
}
}
The error I am getting is:
A field initializer cannot reference the non-static field, method, or property
If I make MyMethod static, everything works fine. Was I simply wrong in thinking I could use a delegate with a non static method (I am sure I remember doing so in the past).
Answering this as I had to 'show more comments' and do a double take before I realised what the actual answer was.
Error:
The solution is to initialise the delegate inside the constructor.
I couldn't actually find this in the C# Language Reference itself, and a lot of the stock examples are static methods.
i.e.
How about TestDelegate testDelgate = MyMethod;