-1

Hello I'd like to create a generic function that accepts a Function T and invokes it.

for example : The magic Function should be like this

 public void Test() 
 {
    InvokeFunction(Test1, "st", "sn");
    InvokeFunction(Test2, 7);
 }

public void InvokeFunction(Function f)
{ 
  f();
}

 public void Test1(string sT, string sFN)
 {
   Console.WriteLine(sT + " : " + sFN);
 }

 public string Test2(int p)
 {
    return p + "";
 }

Is there a way to do it? If so how?

Thanks!

dan
  • 105
  • 1
  • 13

2 Answers2

1

You could do that as an Action but you have to pass a lambda that calls the method with the desired arguments.

public void Test() 
{
   InvokeFunction(() => Test1("st", "sn"));
}

public void InvokeFunction(Action f)
{ 
    f();
}

public void Test1(string sT, string sFN)
{
    Console.WriteLine(sT + " : " + sFN);
}

However if your method has a return value that you want you'd need a separate generic method using a Func for that.

public void Test() 
{
    var result = InvokeFunction(() => Test2(7));
    Console.WriteLine(result);
}

public T InvokeFunction<T>(Func<T> f)
{ 
    return f();
}

public string Test2(int p)
{
    return p + "";
}
juharr
  • 31,741
  • 4
  • 58
  • 93
  • Thank You! If I have both void and returns a value? It is still posible? if i have a write and read action where write is void and read returns a value – dan Oct 27 '16 at 18:50
  • @dan Sure, but you'd need to have both overloads, or better yet give them separate names, maybe `InvokeFunction` and `InvokeAction`. – juharr Oct 27 '16 at 18:51
  • Thats Great Thanks! – dan Oct 27 '16 at 18:53
0

Your method can has a return value or void. So, you must have two generic function.

TValue InvokeFunction<TValue>(Func<TValue> func)
{
    return func();
}

void InvokeFunction(Action func)
{
    func();
}

Usage,

var result = InvokeFunction(() => Test2(3));
InvokeFunction(() => Test1("p1", "p2"));
selami
  • 2,478
  • 1
  • 21
  • 25