A delegate is a type-safe reference to a method — like a function pointer that also knows the method's signature. Func, Action and Predicate are built-in generic delegate types, so you rarely need to declare your own. Custom delegate public delegate decimal TaxCalculator(decimal amount); TaxCalculator gst = amount => amount * 0.18m; decimal tax = gst(1000); // 180 Action — returns nothing (void) Up to 16 parameters: Action, Action<T>, Action<T1, T2>, ... Action<string> log = message => Console.WriteLine($"[{DateTime.Now:T}] {message}"); log("Order created"); Func — returns a value The last type parameter is the return type: Func<TResult>, Func<T, TResult>, Func<T1, T2, TResult>, ... Func<int, int, int> add = (a, b) => a + b; Func<Order, bool> isLarge = o => o.Total > 10_000; int sum = add(2, 3); Predicate — returns bool for one input Predicate<T> is equivalent to Func<T, bool> and is used by some older APIs like List<T>.Find, FindAll and RemoveAll. Predicate<int> isEven = n => n % 2 == 0; var evens = numbers.FindAll(isEven); LINQ methods use Func (Where(Func<T, bool>)), not Predicate, so in modern code Func<T, bool> is more common. Where delegates are used - LINQ: Where, Select, OrderBy take Func delegates. - Callbacks and strategies: pass behaviour into methods (Retry(action, attempts)). - Events: event EventHandler<OrderEventArgs> OrderPlaced; built on delegates. - Dependency injection factories: services.AddScoped<IClock>(sp => new SystemClock()). - Minimal APIs: app.MapGet("/", () => "Hello"). Multicast delegates A delegate can hold several methods (log += WriteToFile;). Invoking it calls all of them in order; for Func, only the last return value is returned. Lambdas and anonymous methods Lambdas (x => x * 2) are the usual way to create delegate instances. A lambda can also be converted to an expression tree (Expression<Func<T, bool>>), which is how EF Core translates LINQ into SQL. Summary: Delegate = method reference type; Action = no return value; Func = returns a value; Predicate = returns bool for one argument.
Ravindra Wadile · · 0 likes