Sean
Sean

Reputation: 8731

Execute a function from a variable in C#

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();
}

Upvotes: 5

Views: 10638

Answers (11)

T.Todua
T.Todua

Reputation: 56421

(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"]();

Upvotes: 0

nathanchere
nathanchere

Reputation: 8098

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.

Upvotes: -1

M4N
M4N

Reputation: 96571

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

Upvotes: 0

jgauffin
jgauffin

Reputation: 101150

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

Upvotes: 1

Chandu
Chandu

Reputation: 82913

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();
        }
}

Upvotes: 2

Gregoire
Gregoire

Reputation: 24832

You can use the MethodInfo class

Type yourtype = yourObject.GetType();

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

Upvotes: 1

Matthew Flaschen
Matthew Flaschen

Reputation: 284836

This is what delegates are for:

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

I assume using strings is not actually a requirement.

Upvotes: 4

Guffa
Guffa

Reputation: 700372

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;
}

Upvotes: 9

C.Evenhuis
C.Evenhuis

Reputation: 26446

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.

Upvotes: 5

Related Questions