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.

2 Answers 2

2

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'
Sign up to request clarification or add additional context in comments.

2 Comments

Could I make the syntax of TakesFun be able to take any number of arguments for the action?
Sure, with a little trick, see this SO question
0

You can always pass an Action:

void TakesFun(Action action)
{
    action();
}
///...
TestFun(() => SomeMethod(1,2,3));

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.