views:

344

answers:

6

Let's say I want to store a group of function pointers in a List<(*func)>, and then later call them, perhaps even with parameters... Like if I stored in a Dict<(*func), object[] params> could I call the func with the parameters? How would I do this?

+6  A: 

Look at the C# documentation on delegates, which is the C# equivalent of a function pointer (it may be a plain function pointer or be curried once to supply the this parameter). There is a lot of information that will be useful to you.

Ben Voigt
Which C# documentation on delegates? Links would be helpful.
sblom
Once you have the right search keywords, finding the documentation is trivial. Google "C# delegates site:msdn.microsoft.com". Unfortunately, SO seems to know about lmgtfy so the animated demonstration doesn't work.
Ben Voigt
+12  A: 

.NET uses delegates instead of function pointers. You can store a delegate instance like any other kind of object, in a dictionary or otherwise.

See Delegates from the C# Programming Guide on MSDN.

John Saunders
+2  A: 

There are a couple ways you could do this. You could do it as others have suggested through the use of delegates. But to get the dictionary to work, they would all need the same signature.

var funcs = new Dictionary<Action<object[]>, object[]>();

Or if they have different signatures you could use the actual reflected method, like the following

var funcs = new Dictionary<MethodInfo, object[]>();
Nick Berardi
+5  A: 

You can absolutely have a dictionary of functions:

List<string, Action<T>> actionList = new List<string, Action<T>>();
List<string, Func<string>> functionList = new List<string, Func<string>>();

actionList.Add("firstFunction", ()=>{//do something;});
functionList.Add("firstFunction", ()=>{return "it's a string!";});

You can then call the methods:

string s = functionList["firstFunction"].Invoke();
Dave Swersky
You can also call them directly: `functionList["firstFunction"]()`
280Z28
+2  A: 

Use ether a delegate or an event (depending on the usage).

Danny Varod
A: 

You need to use delegate.

Ram