Here is a stripped down version of a delegate I am trying to get to work,
which is how an example program shows:
using System;
using System.Collections.Generic;
using System.Text;
namespace delegate4
{
class Program
{
delegate void Print(string s);
static void Main(string[] args)
{
// not anonymous - must have a method already set up to call
Print delegateVariable = new Print(realMethod);
<--------
delegateVariable("This is our non-anonymous delegate string");
}
public void realMethod(string myString)
{
Console.WriteLine(myString);
}
}
}
This gives me an error:
An object reference is required for the nonstatic field, method, or property
'delegate4.Program.realMethod(string)'
Why doesn't this work?
Thanks,
Tom
Alberto Poblacion - 31 Mar 2008 07:18 GMT
> Here is a stripped down version of a delegate I am trying to get to work,
> which is how an example program shows:
[quoted text clipped - 28 lines]
>
> Why doesn't this work?
It doesn't work because you are calling an instance method
("realMethod") from a static method ("Main"). The fix is to either declare
"realMethod" as static, or create an instance of class "Program" and
initialize your delegate to point to theInstance.realMethod.
Jon Skeet [C# MVP] - 31 Mar 2008 08:55 GMT
> Here is a stripped down version of a delegate I am trying to get to work,
> which is how an example program shows:
[quoted text clipped - 29 lines]
>
> Why doesn't this work?
realMethod is an instance method - it needs to know which instance of
Program it's being called on (the *target*).
Your options are:
1) Make the method static
2) Create an instance of Program and use that to create the delegate,
e.g.
Program prog = new Program();
Print delegateVariable = prog.RealMethod;

Signature
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk
tshad - 31 Mar 2008 16:37 GMT
>> Here is a stripped down version of a delegate I am trying to get to
>> work, which is how an example program shows:
[quoted text clipped - 41 lines]
> Program prog = new Program();
> Print delegateVariable = prog.RealMethod;
Makes sense.
Thanks,
Tom