Lecture Topics:
Action
, Func
, Predicate
DelegatesLab:
Delegates are type-safe function pointers in .NET, allowing methods to be passed as parameters or assigned to variables.
Definition:
Declared with the delegate
keyword, specifying a method signature.
Example:
public delegate void DisplayMessage(string message);
public class Messenger
{
public void SayHello(string message) => Console.WriteLine($"Hello: {message}");
}
Messenger messenger = new Messenger();
DisplayMessage del = messenger.SayHello;
del("World"); // Outputs: Hello: World
Calling Methods using Delegates:
Delegates invoke methods with matching signatures.
Example:
public class Calculator
{
public delegate int MathOperation(int a, int b);
public int Add(int a, int b) => a + b;
public int Subtract(int a, int b) => a - b;
public int PerformOperation(MathOperation operation, int a, int b)
{
return operation(a, b);
}
}
Calculator calc = new Calculator();
Calculator.MathOperation op = calc.Add;
Console.WriteLine(calc.PerformOperation(op, 5, 3)); // Outputs: 8
op = calc.Subtract;
Console.WriteLine(calc.PerformOperation(op, 5, 3)); // Outputs: 2
Uses of Delegates:
Event Handling: Used in event-driven programming (e.g., UI events, covered in Session 9).
Callback Methods: Pass methods as arguments for asynchronous or customizable behavior.
Functional Programming: Enable higher-order functions.
Example: Filtering a list using a delegate.
List<int> Filter(List<int> numbers, Func<int, bool> predicate)
{
List<int> result = new List<int>();
foreach (int n in numbers)
if (predicate(n)) result.Add(n);
return result;
}
Multicast Delegates:
A delegate can reference multiple methods, invoked sequentially.
Example:
public delegate void Notify();
public class System
{
public void Log() => Console.WriteLine("Logging...");
public void Alert() => Console.WriteLine("Alerting...");
}
System sys = new System();
Notify notify = sys.Log;
notify += sys.Alert;
notify(); // Outputs:
// Logging...
// Alerting...
Key Points:
+=
creates a new delegate.Action
, Func
, Predicate
Delegates:
Predefined delegates in System
namespace.
Action: Represents a method with void
return type, up to 16 parameters.
Action<string> action = msg => Console.WriteLine(msg);
action("Hello Action"); // Outputs: Hello Action
Func: Represents a method with a return type, up to 16 input parameters.
Func<int, int, int> add = (a, b) => a + b;
Console.WriteLine(add(5, 3)); // Outputs: 8
Predicate: Represents a method returning bool
, typically for filtering.
Predicate<int> isEven = n => n % 2 == 0;
Console.WriteLine(isEven(4)); // Outputs: True
Why This Matters: