2

Can someone provide me an example of how maybe I store different functions in a dictionary with int as a key and function as value. So then I could easly call function as following:

functionsDictionary[123](string);

Note all functions in dictionary will take only one input which is string. And will have no return.

jM2.me
  • 3,839
  • 12
  • 44
  • 58
  • 1
    http://stackoverflow.com/questions/3813261/how-to-store-delegates-in-a-list – Luis Feb 26 '11 at 07:46
  • Kinda is duplicate, kinda not. But I forgot to mention that I would like to add functions to dictionary using dictionary.add method. List != Dictionary :P – jM2.me Feb 26 '11 at 07:53

2 Answers2

8

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)
    {
    }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1
Dictionary<int, Action<string>> _functions = new Dictionary<int, Action<string>>();
_functions[123]("hello");
jgauffin
  • 99,844
  • 45
  • 235
  • 372