Search code examples
c#generic-programming

C# - passing a function of unknown type to another function and calling it


In my program i'm suppose to get a function as a parameter, and call it from within another function. can it be done?
thank you


Solution

  • Sure, you could just take in a Delegate and utilize Delegate.DynamicInvoke or Delegate.Method.Invoke. Barring more information, this answers your question.

    Thus:

    class Foo {
        public void M(Delegate d) {
            d.DynamicInvoke();
        }
    }
    
    Action action = () => Console.WriteLine("Hello, world!");
    var foo = new Foo();
    foo.M(action);