Friday, October 24, 2008

Fun with delegates and dictionnary

In Python functions are first class citizen.
It's very easy to assign a value to a dictionnary entry mydict["myfunction"]=hello
and simply call it with mydict["myfunction"]()
Can the same be done n C# ?
I found a way using delegates although it is not as flexible as Python
Here is the code, feel free to comment

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

namespace dictcaller
{
class Program
{
delegate void DictDelegate(string message);
Dictionary d = new Dictionary();

static void SampleDelegateMethod(string message)
{
Console.WriteLine(message);
}

static void Main(string[] args)
{
Program s = new Program();
s.d["test"] = SampleDelegateMethod;
s.d["test"].Invoke("hello");
Console.ReadLine();
}
}
}

No comments:

Post a Comment