Sign in to follow this  

Help with calling functions

Recommended Posts

I have a bunch of functions(F1,F2,...,Fn) and I'm going to be calling them at random. They're a little too many for me to use branching such as: if(random == 1) F1(); else if(random == 2) F2(); ... Is there any way for me to be able to call a function by using a variable as the function name, something like Fi(); (i being the random number). My guess is it would have something to do with delegates, but I'm not really familiar with them. I'm using Visual Studio 2008, C# Thanks in advance

Share this post

Link to post
Share on other sites
Use an array of delegates (or, more generally, a Dictionary):

using System;

public class Program
string fn1()
{ return "fn1"; }

string fn2()
{ return "fn2"; }

public static void Main()
Func<string>[] funcs = {fn1, fn2};

int i = getMagicNumber();

(Google 'Func delegate MSDN')

Basically, Func is a generic delegate class representing a function that takes up to 4 arguments and returns a value:

Func<string> f is string f()
Func<int, string> f is string f(int)
Func<int, int, string> f is string f(int, int)
Func<int, int, int, string> f is string f(int, int, int)
Func<int, int, int, int, string> f is string f(int, int, int, int)

Beyond that you'll need to define your own delegate (or consider refactoring the function to have fewer arguments).

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this