1

In c++, To a function that takes in a function pointer with void return type, eg:

void TakesFun(Func<void ()>  fun ){
    fun();
}

Above function can be called in these ways

//if foo is a function returning void but is declared in global space and not part of another class
TakesFun(bind(foo));   
//if foo is a function returning void but is declared in class called ClassX and the function is required to be called for object "obj".
TakesFun(bind(ClassX::foo, obj));   
//if foo is a function taking an integer as argument and returning void but is declared in class called ClassX and the function is required to be called for object "obj".
TakesFun(bind(ClassX::foo, obj, 5)); //5 is the argument supplied to function foo   

Could you help me write C# code for 3 similar function calls? I tried reading up on Delegates, but the examples do not cover all the above 3 cases.

Rajat Jain
  • 1,339
  • 2
  • 16
  • 29
sgowd
  • 946
  • 3
  • 10
  • 27

2 Answers2

1

As @Backs said, you can define TakesFun function like this:

void TakesFun(Action action) => action();

If you need to pass a parameter, you can use this:

void TakesFun<TParam>(Action<TParam> action, TParam p) => action(p);

Your 3 examples will be:

TakesFun(SomeClass.Foo); // 'Foo' is a static function of 'SomeClass' class
TakesFun(obj.Foo); // 'Foo' is a function of some class and obj is instance of this class
TakesFun(obj.Foo, "parameter"); // as above, but will pass string as parameter to 'Foo'
vasily.sib
  • 3,871
  • 2
  • 23
  • 26
  • Could I make the syntax of TakesFun be able to take any number of arguments for the action? – sgowd Jun 18 '18 at 08:13
  • Sure, with a little trick, see [this SO question](https://stackoverflow.com/questions/4059624/can-i-use-params-in-action-or-func-delegates) – vasily.sib Jun 18 '18 at 19:27
0

You can always pass an Action:

void TakesFun(Action action)
{
    action();
}
///...
TestFun(() => SomeMethod(1,2,3));
Backs
  • 24,430
  • 5
  • 58
  • 85