Pass Method as Parameter using C#
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Passing a method as a parameter in C# means passing a delegate, a lambda expression, or a method group that matches a delegate type. This is one of the core techniques behind callbacks, strategy selection, LINQ-style APIs, and many event-driven designs.
The Core Idea: Delegates
A delegate is a type-safe reference to a method. If a method parameter expects a delegate, any compatible method can be supplied.
Here, Execute accepts an Action<string>, and PrintMessage is passed in as the method parameter.
Action And Func Are Usually Enough
You do not always need a custom delegate type. C# already provides:
- '
Actionfor methods that returnvoid' - '
Funcfor methods that return a value' - '
Predicate<T>for boolean checks on one argument'
This pattern is common when you want the caller to choose the behavior.
Lambdas Work Too
Instead of passing a named method, you can pass a lambda directly.
Lambdas are often the cleanest choice when the callback is short and used only once.
Custom Delegate Example
If the meaning of the callback deserves a domain-specific name, define a custom delegate.
This is more descriptive than a raw Func<int, bool> when the delegate has a clear role in the API.
Why This Is Useful
Passing methods as parameters is especially useful for:
- callbacks after work completes
- sorting or filtering logic chosen by the caller
- retry or validation policies
- replacing large
switchorifchains with injected behavior
It also supports separation of concerns. One method manages the workflow, while the caller supplies the behavior.
Method Groups Versus Invocation
One common beginner mistake is writing Execute(PrintMessage()). That calls the method immediately and passes its result, which is not what you want. To pass the method itself, use Execute(PrintMessage).
That difference is small syntactically but fundamental semantically.
Common Pitfalls
The most common mistake is passing the result of a method call instead of the method group itself.
Another mistake is choosing a delegate signature that does not match the target method. The parameter types and return type must line up.
A third issue is overusing custom delegates when Action or Func would already express the intent clearly and keep the API simpler.
Summary
- In C#, methods are passed as delegates.
- '
ActionandFunccover most common callback signatures.' - Named methods, method groups, and lambdas can all be passed as parameters.
- This pattern is useful for callbacks, strategy selection, and reusable workflow code.
- Pass the method reference, not the result of invoking the method.

