Help with calling functions

Started by
3 comments, last by TheUnbeliever 15 years, 3 months ago
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
Advertisement
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();    funcs();  }};


(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).
[TheUnbeliever]
Is it possible not to return anything using Func<>?
I would imagine so if it is of size 0.
Quote:Original post by Z3R0Bit
Is it possible not to return anything using Func<>?


Annoyingly, not as far as I'm aware. You'll need an Action delegate for that.
[TheUnbeliever]

This topic is closed to new replies.

Advertisement