5

Is there any way so that you can call a function with a variable?

variable+"()";

or something like that, or would I have to use if statements?

A switch seems like it might be the answer, so if the variable's value=var1 I want it to execute var1(); if the value is var2 I want it to execute var2(); how would I code it?

Basically, I am trying to find a cleaner alternative to

if (variable == var1)
{
var1();
}
if (variable == var2)
{
var2();
}
2
  • Sean, I think you have to change accepted answer to @Matthew's answer, because that one answers the topic. Guffa's answer is not answer to this topic actually. Commented Sep 26, 2017 at 9:04
  • p.s. I have added another complete example. Commented Sep 26, 2017 at 9:24

11 Answers 11

9

It would be possible to use reflection to find a method in an object and call that method, but the simplest and fastest would be to simply use a switch:

switch (variable) {
  case "OneMethod": OneMethod(); break;
  case "OtherMethod": OtherMethod(); break;
}
Sign up to request clarification or add additional context in comments.

Comments

5

You could use Reflection http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx to access any function or member by name. It takes some getting used to though. It also has performance issues, so if you can avoid using it, you should.

Comments

4

This is what delegates are for:

Action f = ()=>Console.WriteLine("foo");
f();

I assume using strings is not actually a requirement.

Comments

2

You can use delegates. MSDN: http://msdn.microsoft.com/en-us/library/900fyy8e(v=vs.71).aspx Exa:

public delegate void TestDelegate();

class TestDelegate
{
        public static void Test()
        {
                Console.WriteLine("In Test");
        }

        public static void Main()
        {
                TestDelegate testDelegate = new TestDelegate(Test);

                testDelegate();
        }
}

Comments

1

You can use the MethodInfo class

Type yourtype = yourObject.GetType();

MethodInfo method = yourtype.GetMethod(variable);
var result = method.Invoke(yourObject,null);

Comments

1
string className = "My.Program.CoolClass"; //including namespace
string method= "Execute";
var type = Type.GetType(className);
var method = type.GetMethod(method);
method.Invoke(classObj, null);

Comments

0

Check out this post.

Use reflection.

http://dotnetslackers.com/Community/blogs/haissam/archive/2007/07/25/Call-a-function-using-Reflection.aspx

Comments

0

You can use MethodMethodInfo.
http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.aspx
http://msdn.microsoft.com/en-us/library/a89hcwhh.aspx

Comments

0

Here's a sample how you can call a method via reflection:

public class MyClass
{
    public void PrintHello()
    {
        Console.WriteLine("Hello World");
    }
}

//...

public void InvokeMethod(object obj, string method)
{
  // call the method
  obj.GetType().GetMethod(method).Invoke(obj, null);
}

//...
var o = new MyClass();
var method = "PrintHello";
//...
InvokeMethod(o, method);

Comments

0

(I will complete @Matthew's excellent answer):

var x =  (Action) ( ()=>Print("foo") );    
x(); 

p.s. you can fully variable names too:

private Dictionary<string, dynamic> my =  new Dictionary<string, dynamic>();
my["x"]  = .....
my["x"]();

Comments

-1
public class FunctionTest
{

    void Main()
    {
        Action doSomething;

        doSomething = FirstFunction;
        doSomething();

        doSomething = SecondFunction;
        doSomething();
    }

    void FirstFunction()
    {
        Console.Write("Hello, ");
    }

    void SecondFunction()
    {
        Console.Write("World!\n");
    }
}

output:

Hello, World!

Doesn't get too much simpler than that.

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.