Search code examples
c#variables

What is it called when you assign a class method to a variable?


In the code below, I have a class Test with a method Go. I created var Go = Test.Go, and I'm able to use either Go("stuff") or Test.Go("stuff").

What do you call assigning a class method to a variable?

var Go = Test.Go;

Go("Hello");
Test.Go("World");

class Test
{
    public static void Go(string word)
    {
        Console.WriteLine(word);
    }
}

Solution

  • Here, you are storing as a method reference to Test.Go in the Go variable. The variable Go points a reference to the method itself ie it is a kind of function "pointer" to Test.Go.

    When the method Go("Hello") is invoked , it is invoking the method using the reference. You can think of Go as a delegate or a method reference.

    The reference pointer Go is especially useful when you want to pass methods around as arguments or store them for later use.

    Go is more flexible, as you can pass it around, store it, or use it as a callback. Test.Go is a specific, typical direct call to the method.