Delegates and Events
Define delegate types and publish events with safe subscription.
Code
using System;
public delegate void Notify(string message);
public class Button
{
// Event restricts external invocation
public event Notify? Clicked;
public void Click()
{
Console.WriteLine("Button.Click raising event");
Clicked?.Invoke("clicked at " + DateTime.Now.ToShortTimeString());
}
}
class Program
{
static void Main()
{
var btn = new Button();
// Subscribe with named methods
btn.Clicked += OnClickLog;
// Subscribe with lambda
btn.Clicked += msg => Console.WriteLine($"[lambda] {msg}");
btn.Click();
btn.Clicked -= OnClickLog; // unsubscribe
btn.Click();
}
static void OnClickLog(string message) =>
Console.WriteLine($"[logger] {message}");
}Explanation
A delegate is a type-safe function pointer; an event is a restricted delegate that only the owning class can invoke. Subscribers attach handlers with += and detach with -=, while the publisher raises the event with the null-conditional invoke pattern. This implements the observer pattern with built-in language support.
More C# Snippets
LINQ Query
Filter, project, sort, group, and aggregate sequences with LINQ.
Async and Await
Run I/O concurrently with async methods, await, and Task.WhenAll.
Properties
Encapsulate state with auto, computed, validated, and init-only properties.
Generics
Write type-parameterized methods and classes with constraints.
Reflection
Inspect type metadata and invoke members at runtime via System.Reflection.
Collections
Use List, Dictionary, HashSet, Queue, Stack, and read-only views.