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);
}
}
}
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With