Jump to content
  • Advertisement
Sign in to follow this  
Z3R0Bit

Help with calling functions

This topic is 3587 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!