This is my test code:
class PassingInActionStatement
{
static void Main(string[] args)
{
var dsufac = new DoSomethingUsefulForAChange();
dsufac.Do(WriteToConsole);
dsufac.Do2(s => WriteToConsoleWithSomethingExtra("Test"));
dsufac.Do(WriteToConsoleWithSomethingExtra("Test")); // Does not compile
}
internal static void WriteToConsole()
{
Console.WriteLine("Done");
}
internal static void WriteToConsoleWithSomethingExtra(String input)
{
Console.WriteLine(input);
}
}
internal class DoSomethingUsefulForAChange
{
internal void Do(Action action)
{
action();
}
internal void Do2(Action<String> action)
{
action("");
}
}
The first 2 calls work but I am wondering why the 3rd one does not. I do not fancy the code inside Do2 as it seems strange that I have type type action("") in there in order to get it to work.
Could someone please explain the 2 things I do not understand please?
- Why I can not write the third line like that with calling Do
- Why I have to write action(“”) in order get it to work in Do2
actually calls the function first (
WriteToConsoleWithSomethingExtra("Test")) and then attempts to pass the result intoDo. Since there is no result (void), it’s not possible.What you actually want is this:
The inner part declares a function that takes nothing (the
() =>bit), which callsWriteToConsoleWithSomethingExtra("Test")when executed. Then yourdsufac.Docall will receive an action, like it expects.As for
Do2– you’ve declared it as takingAction<String>, which means thatactionis a function that takes one argument. You have to pass it a string. That string might be empty, like in youraction("")example, or it might be passed in externally, as in something like this: