0
0
CsharpHow-ToBeginner · 3 min read

How to Create Event in C#: Syntax and Example

In C#, create an event by declaring it with the event keyword and a delegate type, then raise it inside a method. Subscribers can attach methods to this event to respond when it is triggered.
📐

Syntax

To create an event in C#, you declare it inside a class using the event keyword followed by a delegate type. The delegate defines the signature of methods that can handle the event. You then raise the event by calling it like a method, usually inside a protected method.

  • delegate: Defines the method signature for event handlers.
  • event: Declares the event based on the delegate.
  • raising the event: Calls the event to notify subscribers.
csharp
public delegate void MyEventHandler(object sender, EventArgs e);

public class MyClass
{
    public event MyEventHandler? MyEvent;

    protected virtual void OnMyEvent()
    {
        MyEvent?.Invoke(this, EventArgs.Empty);
    }
}
💻

Example

This example shows how to declare an event, subscribe to it with a method, and raise it to trigger the subscriber's method.

csharp
using System;

public class Publisher
{
    public event EventHandler? RaiseEvent;

    public void DoSomething()
    {
        Console.WriteLine("Doing something...");
        OnRaiseEvent();
    }

    protected virtual void OnRaiseEvent()
    {
        RaiseEvent?.Invoke(this, EventArgs.Empty);
    }
}

public class Subscriber
{
    public void HandleEvent(object? sender, EventArgs e)
    {
        Console.WriteLine("Event received by subscriber.");
    }
}

public class Program
{
    public static void Main()
    {
        Publisher pub = new Publisher();
        Subscriber sub = new Subscriber();

        pub.RaiseEvent += sub.HandleEvent; // Subscribe

        pub.DoSomething();
    }
}
Output
Doing something... Event received by subscriber.
⚠️

Common Pitfalls

Common mistakes when creating events in C# include:

  • Not checking if the event is null before invoking it, which causes a NullReferenceException.
  • Using a delegate type that does not match the expected signature for event handlers.
  • Forgetting to subscribe to the event, so the event is raised but no method runs.
  • Raising the event from outside the class without proper access control.

Always use the null-conditional operator ?. when raising events to avoid errors if no subscribers exist.

csharp
public class WrongExample
{
    public event EventHandler? MyEvent;

    public void Raise()
    {
        // Wrong: no null check, can throw exception if no subscribers
        // MyEvent(this, EventArgs.Empty);

        // Right: safe invocation
        MyEvent?.Invoke(this, EventArgs.Empty);
    }
}
📊

Quick Reference

ConceptDescription
delegateDefines the method signature for event handlers.
eventDeclares an event based on a delegate type.
subscribeAttach a method to an event using += operator.
unsubscribeRemove a method from an event using -= operator.
raise eventInvoke the event to notify subscribers, usually with null check.

Key Takeaways

Declare events using the event keyword and a delegate type in your class.
Raise events safely using the null-conditional operator to avoid errors.
Subscribe to events with += and unsubscribe with -= to manage handlers.
Event handlers must match the delegate signature defined by the event.
Always raise events from within the class to maintain encapsulation.