close
close
c# pass function as parameter

c# pass function as parameter

3 min read 24-02-2025
c# pass function as parameter

C# allows you to pass functions as parameters to other methods, a powerful technique known as delegates and lambda expressions. This capability enables flexible and reusable code, especially beneficial in scenarios requiring callbacks, event handling, or customizable algorithms. This article will explore the different ways to achieve this, providing clear explanations and practical examples.

Understanding Delegates

Before diving into how to pass functions, we need to understand delegates. A delegate in C# is a type that represents a reference to a method. Think of it as a placeholder that can hold a method. Once a delegate holds a reference, you can invoke the method through the delegate.

// Declare a delegate type
public delegate int MathOperation(int x, int y);

// Methods that match the delegate signature
public int Add(int x, int y) => x + y;
public int Subtract(int x, int y) => x - y;

public static void Main(string[] args)
{
    // Create delegate instances
    MathOperation addDelegate = Add;
    MathOperation subtractDelegate = Subtract;

    // Invoke methods through delegates
    Console.WriteLine({{content}}quot;Addition: {addDelegate(5, 3)}"); // Output: 8
    Console.WriteLine({{content}}quot;Subtraction: {subtractDelegate(5, 3)}"); // Output: 2
}

This example defines a delegate MathOperation that expects two integer inputs and returns an integer. Add and Subtract methods are created to match this signature. Delegates addDelegate and subtractDelegate hold references to these methods.

Passing Delegates as Parameters

Now, let's see how to pass these delegates as parameters to another method:

public static int PerformOperation(int a, int b, MathOperation operation)
{
  return operation(a, b);
}

public static void Main(string[] args)
{
    // Using the PerformOperation method with different delegates
    Console.WriteLine({{content}}quot;Addition: {PerformOperation(5, 3, Add)}"); // Output: 8
    Console.WriteLine({{content}}quot;Subtraction: {PerformOperation(5, 3, Subtract)}"); // Output: 2
}

The PerformOperation method accepts a MathOperation delegate as a parameter. Depending on which delegate is passed, a different operation is performed. This demonstrates the power of passing functions as parameters—the same method can perform various operations based on the provided function.

Using Lambda Expressions

Lambda expressions offer a more concise way to define anonymous methods directly where they are used. They are particularly useful when you need a simple function that won't be reused elsewhere.

public static int PerformOperation(int a, int b, Func<int, int, int> operation)
{
    return operation(a, b);
}

public static void Main(string[] args)
{
    // Using lambda expressions
    Console.WriteLine({{content}}quot;Multiplication: {PerformOperation(5, 3, (x, y) => x * y)}"); // Output: 15
    Console.WriteLine({{content}}quot;Division: {PerformOperation(6, 2, (x, y) => x / y)}"); // Output: 3
}

Here, Func<int, int, int> is a built-in delegate type representing a function that takes two integers and returns an integer. Lambda expressions (x, y) => x * y and (x, y) => x / y define the multiplication and division operations directly within the PerformOperation call.

Action and Func Delegates

C# provides predefined delegate types like Action (for void-returning methods) and Func (for methods returning a value). These simplify delegate declarations, eliminating the need to define custom delegate types for common scenarios.

Example using Action:

public static void PrintMessage(string message, Action<string> printAction)
{
    printAction(message);
}

public static void Main(string[] args)
{
    PrintMessage("Hello, world!", (msg) => Console.WriteLine(msg));
}

This uses Action<string>, a delegate that takes a string as input and doesn't return a value.

Advanced Scenarios: Event Handling

Delegate passing is fundamental to event handling in C#. Events allow objects to notify other objects when something significant happens. The event handler (the function that responds to the event) is passed as a delegate.

This comprehensive guide demonstrates the versatility of passing functions as parameters in C#. Through delegates and lambda expressions, you can create highly flexible and reusable code, handling various scenarios efficiently. Mastering this concept significantly enhances your ability to write efficient and elegant C# programs.

Related Posts