Junior — Middle
Explain the purpose and operation of delegates in the context of C# programming.
sobes.tech AI
Answer from AI
Delegates in C# are types that represent references to methods with a specific signature. They allow invoking methods indirectly, passing them as parameters, and implementing callbacks.
Key points:
- A delegate defines the signature of a method (parameter types and return value).
- Any method with a matching signature can be assigned to a delegate.
- They enable implementing events and the observer pattern.
Example:
public delegate void Notify(string message);
public class Process
{
public Notify OnCompleted;
public void Start()
{
// ... work
OnCompleted?.Invoke("Process completed");
}
}
Here, the delegate Notify is used to notify about the process completion.