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-♦
225k56 gold badges492 silver badges498 bronze badges
asked Feb 1 at 4:38
akTedakTed
2452 silver badges9 bronze badges
2
|
1 Answer
Reset to default 2Here, 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.
Action<string>
– Ivan Petrov Commented Feb 1 at 4:56