9️⃣ C# Advanced Concepts
Estimated reading: 3 minutes 276 views

C# Delegates – Type-Safe Function Pointers for Flexible Code Execution


Introduction – Why Use Delegates in C#?

In modern C# applications, especially those requiring callbacks, event-driven logic, or functional programming techniques, you often need to treat methods as data. Delegates make this possible by acting as type-safe function pointersβ€”allowing you to pass methods around just like variables.

In this guide, you’ll learn:

  • What a delegate is and why it’s useful
  • How to declare, instantiate, and invoke delegates
  • The difference between single-cast and multicast delegates
  • Real-world applications like callbacks and events

Core Concept – What Is a Delegate?

A delegate in C# is a type-safe object that refers to a method with a specific signature and return type. Delegates allow methods to be passed as arguments, stored in variables, or invoked dynamically.


Delegate Declaration Syntax

delegate void Greet(string name);

This defines a delegate named Greet that can point to any method that takes a string and returns void.


Code Example – Declaring and Using a Delegate

delegate void Greet(string name);

class Program
{
    static void SayHello(string name)
    {
        Console.WriteLine($"Hello, {name}!");
    }

    static void Main()
    {
        Greet greeter = SayHello;
        greeter("Alice");
    }
}

Output:

Hello, Alice!

Explanation:

  • SayHello matches the Greet delegate signature.
  • greeter("Alice") invokes the method indirectly.

Multicast Delegates

A multicast delegate points to multiple methods and invokes them in order.

delegate void Notify();

void Email() => Console.WriteLine("Email sent");
void SMS() => Console.WriteLine("SMS sent");

Notify notify = Email;
notify += SMS;

notify(); 

Output:

Email sent  
SMS sent

Use Case: Trigger multiple listeners, such as event handlers.


Delegates as Parameters

delegate int Operation(int x, int y);

int Add(int a, int b) => a + b;

int Calculate(Operation op, int x, int y) => op(x, y);

int result = Calculate(Add, 5, 3);  // Output: 8

Use Case: Pass different operations into a reusable method.


Built-in Delegates

Delegate TypeSignature
ActionNo return value (void)
FuncReturns a value
PredicateReturns a bool

Example – Using Action, Func, and Predicate

Action<string> print = Console.WriteLine;
Func<int, int, int> add = (a, b) => a + b;
Predicate<int> isEven = x => x % 2 == 0;

Best Practices & Tips

Tip: Use delegates when you want methods as first-class citizens.

Pitfall: Multicast delegates only return the last method’s return valueβ€”not suitable when return values are needed from all calls.

Best Practice: Prefer built-in delegates (Action, Func, Predicate) when possible for clarity and reuse.


Real-World Use Cases

  • Callbacks in async programming
  • Filtering and transformation in LINQ
  • Game engine events (e.g., OnPlayerDeath)
  • Plug-in systems and dynamic method execution
  • Form validation pipelines

Summary – Recap & Next Steps

Key Takeaways:

  • Delegates enable method references and flexible code execution.
  • Support single-cast and multicast patterns.
  • Built-in types like Action, Func, and Predicate simplify common patterns.

Real-world relevance: Delegates power events, callbacks, LINQ, and functional programming patterns in C#.


FAQ Section

What is the difference between a delegate and an event?
A delegate is a type-safe method pointer, while an event is a wrapper around a delegate designed for publish/subscribe patterns.


Can a delegate point to multiple methods?
Yes. A multicast delegate can reference multiple methods using the += syntax.


Are delegates reference types or value types?
Delegates are reference types, even though they often wrap method logic.


Can I pass a lambda expression to a delegate?
Yes. Lambda expressions are fully compatible with delegate types.


Is it better to use delegate or Action/Func?
For simple cases, prefer built-in delegates (Action, Func) to reduce boilerplate and improve readability.


Share Now :
Share

πŸš€ C# Delegates

Or Copy Link

CONTENTS
Scroll to Top