pistacchio
pistacchio

Reputation: 58953

Delegate: Method name expected error

I'm trying to get the following simple Delegate example working. According to a book I've taken it from it should be ok, but I get a Method name expected error.

namespace TestConsoleApp
{
    class Program
    {
        private delegate string D();

        static void Main(string[] args)
        {
            int x = 1;

            D code = new D(x.ToString());

        }
    }
}

Any help?

Upvotes: 16

Views: 47732

Answers (6)

Jens
Jens

Reputation: 25593

You need to feed a method into the delegate constructor.

x.ToString()

is not a method, but a string. Use

D code = new D(x.ToString); 

Upvotes: 3

Darin Dimitrov
Darin Dimitrov

Reputation: 1039468

Should be:

D code = new D(x.ToString);

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503519

I think you mean:

D code = new D(x.ToString);

Note the lack of brackets. With the brackets on, it was a method invocation - i.e. you were trying to execute x.ToString() in that line of code. Without the brackets, it's a method group - an expression which tells the compiler to look at the available methods with that name (in that context), precisely for the purpose of creating delegates.

Which book are you using? If it really has the brackets in the examples it shows, you may want to email the author (or at least check the book's errata page). If it's C# in Depth, I'll go and cry in a corner...

Upvotes: 7

Fitzchak Yitzchaki
Fitzchak Yitzchaki

Reputation: 9163

D code = new D(x.ToString);   // Note the: ()

You need to pas the method to be executed in the delegate. What that you're doing is passing the value instead of the signature of the function.

Upvotes: 0

Hans Kesting
Hans Kesting

Reputation: 39338

Remove the ():

D code = new D(x.ToString);

You want to specify the method, not execute it.

Upvotes: 35

cjk
cjk

Reputation: 46475

Try taking the brackets off the end of the method, you are passing the method, hence don't need to use the brackets.

Upvotes: 0

Related Questions