Junior — Middle
How can delegation of responsibility be implemented using delegates?
sobes.tech AI
Answer from AI
Delegates in C# allow passing methods as parameters, which simplifies responsibility delegation. This means one object can delegate the execution of a specific task to another object via a delegate.
Example:
public delegate void Notify(string message);
public class Process
{
public Notify OnCompleted;
public void Start()
{
// Perform task
OnCompleted?.Invoke("Task completed");
}
}
// Usage
var process = new Process();
process.OnCompleted = msg => Console.WriteLine(msg);
process.Start();
Here, the method called upon completion is passed via a delegate, allowing flexible behavior changes without modifying the Process class.