C# Store Functions in a Dictionary

C# Store functions in a Dictionary

Like this:

Dictionary<int, Func<string, bool>>

This allows you to store functions that take a string parameter and return boolean.

dico[5] = foo => foo == "Bar";

Or if the function is not anonymous:

dico[5] = Foo;

where Foo is defined like this:

public bool Foo(string bar)
{
...
}

UPDATE:

After seeing your update it seems that you don't know in advance the signature of the function you would like to invoke. In .NET in order to invoke a function you need to pass all the arguments and if you don't know what the arguments are going to be the only way to achieve this is through reflection.

And here's another alternative:

class Program
{
static void Main()
{
// store
var dico = new Dictionary<int, Delegate>();
dico[1] = new Func<int, int, int>(Func1);
dico[2] = new Func<int, int, int, int>(Func2);

// and later invoke
var res = dico[1].DynamicInvoke(1, 2);
Console.WriteLine(res);
var res2 = dico[2].DynamicInvoke(1, 2, 3);
Console.WriteLine(res2);
}

public static int Func1(int arg1, int arg2)
{
return arg1 + arg2;
}

public static int Func2(int arg1, int arg2, int arg3)
{
return arg1 + arg2 + arg3;
}
}

With this approach you still need to know the number and type of parameters that need to be passed to each function at the corresponding index of the dictionary or you will get runtime error. And if your functions doesn't have return values use System.Action<> instead of System.Func<>.

Is it possible to store functions in a dictionary?

It sounds like you probably want something like:

Dictionary<string, Func<string[], int>> functions = ...;

This is assuming the function returns an int (you haven't specified). So you'd call it like this:

int result = functions[name](parameters);

Or to validate the name:

Func<string[], int> function;
if (functions.TryGetValue(name, out function))
{
int result = function(parameters);
...
}
else
{
// No function with that name
}

It's not clear where you're trying to populate functions from, but if it's methods in the same class, you could have something like:

Dictionary<string, Func<string[], int>> functions = 
new Dictionary<string, Func<string[], int>>
{
{ "Foo", CountParameters },
{ "Bar", SomeOtherMethodName }
};

...

private static int CountParameters(string[] parameters)
{
return parameters.Length;
}

// etc

Store Void Functions in a Dictionary

You can use code like below. Dictionary should help you to achieve what you want to do.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

public class Test
{
public static void Main(string[] args)
{
Dictionary<string, Action> dict = new Dictionary<string, Action>();
dict.Add("Do1", ActionDo1);
dict.Add("Do2", ActionDo1);

dict["Do1"]();
}

public static void ActionDo1()
{
Console.WriteLine("The Do1 is called");
}

public static void ActionDo2()
{
Console.WriteLine("The Do2 is called");
}

}

Hope this helps.

How to store functions in Dictionary with uint as key (C#)

It sounds like you're after

Dictionary<int, Action<string>>

or possibly (based on your title)

Dictionary<uint, Action<string>>

Sample:

using System;
using System.Collections.Generic;

class Test
{
static void Main()
{
var dictionary = new Dictionary<int, Action<string>>
{
{ 5, x => Console.WriteLine("Action for 5: {0}", x) },
{ 13, x => Console.WriteLine("Unlucky for some: {0}", x) }
};

dictionary[5]("Woot");
dictionary[13]("Not really");

// You can add later easily too
dictionary.Add(10, x => Console.WriteLine("Ten {0}", x));
dictionary[15] = x => Console.WriteLine("Fifteen {0}", x);

// Method group conversions work too
dictionary.Add(0, MethodTakingString);
}

static void MethodTakingString(string x)
{
}
}

Dictionaries and Functions

Basically in the same way:

static void Main() {
var dict = new Dictionary<string, Action>();
// map "do" to MyFunc
dict.Add("do", MyFunc);
// run "do"
dict["do"]();
}

static void MyFunc() {
Console.WriteLine("Some stuff");
}

Calling Functions Based on Content of a Dictionary C#

How you would do this depends upon the method signatures and what, if any, parameters you need to pass. In general, though, you'd need to create a dictionary of delegates. Action and Func are pretty easy to use in this situation.

Something like this would work:

private void Test()
{
var commands = new Dictionary<string, Action>();
commands.Add("exit", Exit);
commands.Add("greet", SayHello);

commands["greet"]();
commands["exit"]();
}

private void Exit()
{
this.Close();
}

private void SayHello()
{
MessageBox.Show("Hello!");
}

You could also use lambda expressions to add delegates to such a dictionary for even more flexibility:

commands.Add("exit", () => this.Close());
commands.Add("greet", () => MessageBox.Show("Hello!"));


Related Topics



Leave a reply



Submit