y2k
y2k

Reputation: 65996

How to store a function pointer in C#

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?

Upvotes: 19

Views: 26925

Answers (6)

Dave Swersky
Dave Swersky

Reputation: 34810

You can absolutely have a dictionary of functions:

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

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

You can then call the methods like this:

string s = functionList["firstFunction"].Invoke();

Upvotes: 22

Soenhay
Soenhay

Reputation: 4048

If you are only storing event handlers then...

Dictionary<string, EventHandler> dictEvents = new Dictionary<string, EventHandler>();
dictEvents.Add("Event1", someEventHandler);

...

protected void someEventHandler(object sender, EventArgs e)
{
   //Do something.
}

Edit:

  • I put this here because I was searching for a way to do something similar when I found this post. However, the solutions in this post did not quite work for my situation so I figured I would share what did work for me.

Upvotes: -1

Danny Varod
Danny Varod

Reputation: 18068

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

Upvotes: 2

Nick Berardi
Nick Berardi

Reputation: 54854

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[]>();

Upvotes: 2

John Saunders
John Saunders

Reputation: 161773

.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.

Upvotes: 35

Ben Voigt
Ben Voigt

Reputation: 283634

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.

Upvotes: 8

Related Questions