Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return an action type from a method

Tags:

c#

c#-4.0

I am trying to figure out how to return an action from a method. I cannot find any examples of this online. Here is the code I am trying to run but it fails:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication8
{
    class Program
    {
        static void Main(string[] args)
        {
            var testAction = test("it works");
            testAction.Invoke();    //error here
            Console.ReadLine();
        }

        static Action<string> test(string txt)
        {
            return (x) => Console.WriteLine(txt);
        }
    }
}
like image 778
Luke101 Avatar asked Dec 26 '22 09:12

Luke101


1 Answers

The problem is textAction is an Action<string>, which means you need to pass a string:

textAction("foo");

I suspect you want something like:

class Program
{
    static void Main(string[] args)
    {
        var testAction = test();
        testAction("it works");
        // or textAction.Invoke("it works");
        Console.ReadLine();
    }

    // Don't pass a string here - the Action<string> handles that for you..
    static Action<string> test()
    {
        return (x) => Console.WriteLine(x);
    }
}
like image 175
Reed Copsey Avatar answered Dec 28 '22 23:12

Reed Copsey