1

I want to call a different function without write if conditions like this:

if(a==1)
{
    function1 ();
}
if(a==2)
{
    function2 ();
}
if(a==3)
{
    function3 ();
}

I want to call function like this :

Dictionary<int, function> functions= new Dictionary<int, function>();
functions.add(1, function1);functions.add(2, function2);functions.add(3, function3);

function[1];

How can I do this?

3
  • 1
    Replace function with Func<...>/Action<...>. Commented Nov 23, 2015 at 13:04
  • Have you heard about delegates ? Change your function what says @Sinatr and invoke like this function[1]() Commented Nov 23, 2015 at 13:04
  • Also read about delegates before you read about Func<> and Action<>, Commented Nov 23, 2015 at 13:08

3 Answers 3

3

It seems your functions are actually actions, since a function returns a value. Also you don't have any method parameters, so you have to use Action.

Dictionary<int, Action> functions= new Dictionary<int, Action>();
functions.Add(1, function1);
functions.Add(2, function2);
functions.Add(3, function3);

function[1](); // <-- calling here needs parentheses
Sign up to request clarification or add additional context in comments.

2 Comments

No, unless you wrap that call in an action too (if possible). It is all the same or not.
there is no another issue??
1

You can do something like the following

void Main()
{
    Dictionary<int, Func<bool>> funcMap = new Dictionary<int, Func<bool>>() {
        {1, Function1},
        {2, Function2}
    };


    Console.WriteLine(funcMap[1]());
    Console.WriteLine(funcMap[2]());
}

// Define other methods and classes here


bool Function1()
{
    return true;
}

bool Function2()
{
    return false;
}

This works because all functions have the same signature.

2 Comments

thank you for the answer. but I can I have it with different signature
Possibly you need to explain how your code is getting used. You didn't gave us much to work with.
1

You can use lambdas to map functions with different signatures. Idea is the same as with Action:

var functions = new Dictionary<int, Action>
{
    { 1, () => method1(123) },
    { 2, () => method2(123, "123") },
};

functions[1](); // will call method1(123);

where functions are defined like this

void method1(int a) => Console.WriteLine(a);
void method2(int a, string b) => Console.WriteLine(a + b);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.