What does a method name equivalent to delegating actions mean?

I just experimented and got the following snippet:

public static class Flow {
    public static void Sequence(params Action[] steps) {
        foreach (var step in steps)
            step();
    }
}
void Main() {
    Flow.Sequence(() => F1(), () => F2());
    Flow.Sequence(F1, F2); // <-- what makes this equiv to the line above?

}
void F1() { }
void F2() { }

I did not understand that one method name matches the name Action.

What does it do?

+5
source share
3 answers

Basically, this is what happens in the background:

void Main() 
{    
    Flow.Sequence(new Action(delegate(){ F1(); }), new Action(delegate(){ F2(); }));    
    Flow.Sequence(new Action(F1), new Action(F2)); 
}

They are NOT EXACTLY equivalent, but they are very close. They will display the same results at runtime, with the only difference being that the arguments in the first call to Sequence would be an action that calls an anonymous method, which then calls the static methods F1 and F2; the second call to the sequence will be Action, which calls the static methods F1 and F2.

Hope this helps.

+3

# - , . .

, :

, , . , . , .

, , , .

F1() F2(), , Action delegate:

public delegate void Action();

, Action.

, , Action.

+7

The compiler uses an implicit conversion from a group of methods to a delegate of a compatible type (in this case, the void return method takes no arguments), the method names are irrelevant here.

0
source

All Articles