c# - What is it called when you assign a class method to a variable? - Stack Overflow

admin2025-04-17  2

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);
    }
}

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);
    }
}
Share Improve this question edited Feb 1 at 5:20 Ry- 226k56 gold badges493 silver badges499 bronze badges asked Feb 1 at 4:38 akTedakTed 2452 silver badges9 bronze badges 2
  • 3 It's called creating a delegate which has as its method the static class method. Hover over the go variable to see that it's of type Action<string> – Ivan Petrov Commented Feb 1 at 4:56
  • Ahhh, I didn't think to hover over it. I'm usually just hovering to figure out my many mistakes haha – akTed Commented Feb 1 at 10:46
Add a comment  | 

1 Answer 1

Reset to default 2

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.

转载请注明原文地址:http://anycun.com/QandA/1744839603a88343.html