In the following example, I want to define a System.Action which executes a specific method that I define at runtime, but how do I pass the method name (or the method itself) so that the Action method can define the delegate to point to that particular method?
I'm currently getting the following error:
'methodName' is a 'variable' but is used like a 'method'
using System;
using System.Collections.Generic;
namespace TestDelegate
{
class Program
{
private delegate void WriteHandler(string message);
static void Main(string[] args)
{
List<string> words = new List<string>() { "one", "two", "three", "four", "five" };
Action<string> theFunction = WriteMessage("WriteBasic");
foreach (string word in words)
{
theFunction(word);
}
Console.ReadLine();
}
public static void WriteBasic(string message)
{
Console.WriteLine(message);
}
public static void WriteAdvanced(string message)
{
Console.WriteLine("*** {0} ***", message);
}
public static Action<string> WriteMessage(string methodName)
{
//gets error: 'methodName' is a 'variable' but is used like a 'method'
WriteHandler writeIt = new WriteHandler(methodName);
return new Action<string>(writeIt);
}
}
}