Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Pass Method as Parameter using C#

I have a few techniques all with similar parameter types and return values however various names and blocks. I need to pass the name of the technique to run to another strategy that will invoke the passed strategy.

public int Method1(string)
{
// Do something
return myInt;
}

public int Method2(string)
{
// Do something different
return myInt;
}

public bool RunTheMethod([Method Name passed in here] myMethodName)
{
// Do stuff
int i = myMethodName("My String");
// Do more stuff
return true;
}

public bool Test()
{
return RunTheMethod(Method1);
}


This code doesn't work yet this is the thing that I am attempting to do. What I don't understand is the means by which to compose the RunTheMethod code since I need to characterize the parameter.
by

3 Answers

akshay1995
You can use the Func delegate in .net 3.5 as the parameter in your RunTheMethod method. The Func delegate allows you to specify a method that takes a number of parameters of a specific type and returns a single argument of a specific type. Here is an example that should work:

public class Class1
{
public int Method1(string input)
{
//... do something
return 0;
}

public int Method2(string input)
{
//... do something different
return 1;
}

public bool RunTheMethod(Func<string, int> myMethodName)
{
//... do stuff
int i = myMethodName("My String");
//... do more stuff
return true;
}

public bool Test()
{
return RunTheMethod(Method1);
}
}
RoliMishra
The solution involves Delegates, which are used to store methods to call. Define a method taking a delegate as an argument,

public static T Runner<T>(Func<T> funcToRun)
{
// Do stuff before running function as normal
return funcToRun();
}


Then pass the delegate on the call site:

var returnValue = Runner(() => GetUser(99));
sandhya6gczb
From OP's example:

public static int Method1(string mystring)
{
return 1;
}

public static int Method2(string mystring)
{
return 2;
}

You can try Action Delegate! And then call your method using

public bool RunTheMethod(Action myMethodName)
{
myMethodName(); // note: the return value got discarded
return true;
}

RunTheMethod(() => Method1("MyString1"));

Or

public static object InvokeMethod(Delegate method, params object[] args)
{
return method.DynamicInvoke(args);
}

Then simply call method

Console.WriteLine(InvokeMethod(new Func<string,int>(Method1), "MyString1"));

Console.WriteLine(InvokeMethod(new Func<string, int>(Method2), "MyString2"));

Login / Signup to Answer the Question.