High order functions in C# which return void

Viewed 373

I am having some issues understanding HOF in C#. I want my DoSomething function to receive a function as a parameter that returns void and receives two strings. I cannot set the first generic parameter to void as the compiler complains. And this gives me an error.

Whats the right syntax to do this in C# ?

using System.IO;
using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("Hello, World!");
        DoSomething((v1, v2) => Console.WriteLine(v1, v2));
    }
    
    private static void DoSomething(Func<string,string,string> f){
        f("1", "2");
    }
}
1 Answers

Use Action<string, string> instead of Func<string, string, string> basically. The Action delegates are declared to return void; the Func delegates are declared to return "the final type parameter".

using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("Hello, World!");
        DoSomething((v1, v2) => Console.WriteLine(v1, v2));
    }

    private static void DoSomething(Action<string, string> action)
    {
        action("1", "2");
    }
}

Note that here the result is just "1" because that's being interpreted as a format string. If you use action("Value here: '{0}'", "some-value"); instead, you'll get output of Value here: 'some-value'.

Related