Delegates & EventsBeginner
1Question 1 of 1
csharpWhat is the difference between Delegates, Actions, Funcs, and Events in C#?
Explanation & Concept
• Delegate: A type-safe function pointer referencing methods matching a specific signature. • `Func<T, TResult>`: Built-in generic delegate that takes parameters and returns a value. • `Action<T>`: Built-in generic delegate that takes parameters and returns `void`. • Event: A mechanism that wraps a delegate to provide publisher-subscriber encapsulation. Outside classes can only subscribe (`+=`) or unsubscribe (`-=`), but cannot invoke or clear the event directly.
Code Example
csharp
using System;
public class OrderService {
// Declaring a strongly-typed event using Action
public event Action<string> OnOrderPlaced;
public void PlaceOrder(string orderId) {
Console.WriteLine($"Order {orderId} processed.");
// Safely invoke subscribers using null-conditional operator
OnOrderPlaced?.Invoke(orderId);
}
}How It Works & Key Takeaways
The `event` keyword protects delegates from being maliciously overwritten (`= null`) from outside the publishing class.
Mock Test · 1 Questions · Optional
Ready for Generics?
Take a quick test to evaluate yourself, or move straight to the next module.
Beginner2 questions