C#
method parameters
programming
software development
C# tutorials

Pass Method as Parameter using C

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions
markdown
1In C#, passing methods as parameters is a powerful feature that enables developers to write flexible and reusable code. This feature is primarily facilitated through delegates and lambda expressions, allowing you to pass behavior or action in the form of methods to other methods. This article will delve into the technical aspects of passing methods as parameters in C#, demonstrate its usage with examples, and explore additional related topics.
2
3## What Are Delegates?
4
5Delegates are type-safe pointers to methods. When you use a delegate, you can define a reference that encapsulates a method. This is particularly useful when you want to pass a method as a parameter. The syntax of a delegate defines the signature of the method it can point to, which includes the return type and parameter types.
6
7### Example of a Delegate
8
9```csharp
10// Define a delegate
11public delegate int MathOperation(int x, int y);
12
13// A method that matches the delegate signature
14public static int Add(int a, int b)
15{
16    return a + b;
17}
18
19// Using the delegate
20MathOperation operation = new MathOperation(Add);
21int result = operation(5, 3); // result is 8

In the above example, the MathOperation delegate can encapsulate any method that takes two integers and returns an integer. The Add method perfectly matches this signature.

Passing Methods as Parameters Using Delegates

When you pass a method as a parameter, you typically pass the corresponding delegate. C# allows you to pass these delegates directly into methods, thereby passing the behavior you want to execute.

Example of Passing Delegate as a Parameter

csharp
1// Method that accepts a delegate as a parameter
2public static int PerformOperation(int x, int y, MathOperation operation)
3{
4    return operation(x, y);
5}
6
7// Usage
8int sum = PerformOperation(10, 20, Add); // sum is 30

In the PerformOperation method, we pass the Add method using the delegate type MathOperation. This flexibility allows different operations to be performed without modifying the PerformOperation method.

Lambda Expressions

Lambda expressions are a more concise way to define method-like behavior inline and are often used with delegates. They use the => syntax and can capture variables from the surrounding context.

Example of Lambda Expression

csharp
1// Using lambda expression to define the delegate inline
2int result = PerformOperation(10, 5, (a, b) => a - b); // result is 5
3
4// Using lambda with Func
5Func<int, int, int> multiply = (a, b) => a * b;
6int product = multiply(4, 5); // product is 20

In this example, a lambda expression (a, b) => a - b is passed to PerformOperation method, showcasing how inline method definitions can replace traditional method references.

The System.Action and System.Func Delegates

C# provides built-in delegates Action and Func for common cases where you pass a method as a parameter. They eliminate the need to declare custom delegates for common scenarios. Action is used for methods that do not return a value, while Func is used for methods that return a value.

Example with System.Action

csharp
1public static void ExecuteAction(int x, int y, Action<int, int> action)
2&#123;
3    action(x, y);
4&#125;
5
6// Using Action to print sum
7ExecuteAction(5, 3, (a, b) => Console.WriteLine(a + b)); // Output: 8

Example with System.Func

csharp
1public static int ExecuteFunc(int x, int y, Func<int, int, int> func)
2&#123;
3    return func(x, y);
4&#125;
5
6// Using Func to add numbers
7int sumResult = ExecuteFunc(3, 7, (a, b) => a + b); // sumResult is 10

Table of Key Points

ConceptDescription
DelegateType-safe method pointers in C#.
Lambda ExpressionInline, concise method definitions using =>.
System.ActionDelegate for methods that do not return a value.
System.FuncDelegate for methods that return a value.
Syntax FlexibilityEnables method behavior to be passed as parameters.
Type SafetyEnsures delegate signature matches the method.

Additional Topics

Anonymous Methods

Before lambda expressions were introduced, anonymous methods were used to define inline methods. Though superseded by lambdas, anonymous methods are still part of C# and can be used as:

csharp
MathOperation subtraction = delegate (int a, int b) &#123;
    return a - b;
&#125;;

Covariance and Contravariance

Covariance and contravariance in delegates allow a more flexible matching of method signatures, specifically related to return types and parameter types. Covariance allows a method to return a more derived type than specified in the delegate, while contravariance permits the method to accept parameters of a less derived type.

Conclusion

Passing methods as parameters using delegates and lambda expressions adds an essential level of flexibility and reusability to C# programming. By understanding and utilizing these capabilities, you can design cleaner, more efficient code through encapsulated behavior that conforms to interfaces, patterns, and functional paradigms.

 

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.