Josh Ding
Josh Ding

Reputation: 83

A simple question about delegate instantiation

I am trying to read some code on the internet, but still cannot figure it out.

The code is:

private delegate string GetAString();

static void Main()
{
    int x = 40;

    GetAString firstStringMethod = new GetAString(x.ToString);

    Console.WriteLine(firstStringMethod());
} 

My question is "delegate string GetAString()" does not need parameters, but when it is instantiated, it has the x.ToString parameter.

Why? Can anyone explain this? Thanks.

Upvotes: 0

Views: 60

Answers (1)

ProgrammingLlama
ProgrammingLlama

Reputation: 38870

A delegate is a special type of variable that can hold a reference to a method (not the result of the method but the method itself), allowing it to be passed around and invoked in places where you perhaps don't have access to the object the method belongs to.

From the docs:

Represents a delegate, which is a data structure that refers to a static method or to a class instance and an instance method of that class.

Your code:

GetAString firstStringMethod = new GetAString(x.ToString);

Note the lack of () at the end of x.ToString. We're not calling x.ToString() here. We're creating a GetAString and passing x.ToString (which is a method that satisfies the signature required by the delegate).

This means that when we call firstStringMethod() it will call x.ToString() and proxy the result to you.

Consider another example:

public delegate int Operation(int a, int b);

We could define multiple methods:

public int Sum(int a, int b)
{
    return a + b;
}

public int Multiply(int a, int b)
{
    return a * b;
}

And then switch according to user input:

Operation o;
switch (Console.ReadLine())
{
    case "+":
        o = new Operation(Sum);
        break;
    case "*":
        o = new Operation(Multiply);
        break;
    default:
        Console.WriteLine("invalid operation");
        return;
}

Console.WriteLine(o(4, 3));

If the user inputs "+" then the result will be 7, while inputting "*" will result in "12".

You can see from this example that we're not passing the arguments of Sum or Multiply when we instantiate o. We're simply passing the method. We then use the delegate to supply the arguments and get the result.

Example if user input is +

Example if user input is *

Upvotes: 3

Related Questions