Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# What's the difference between Action and event Action

Tags:

c#

Reading some code I noticed that a few classes have Actions, but only some of them were also events:

public Action OnAction1;
public event Action OnAction2;

What is the difference?

like image 621
Moffen Avatar asked Aug 31 '25 00:08

Moffen


1 Answers

It's effectively the same as the difference between fields and properties, it adds a level of indirection to allow you to add or remove subscribers safely without exposing the underlying field much in the same way a property protects access to the field value.

public Action OnAction1; // field
public Action OnAction2 { get; set; } // property
public event Action OnAction3; // event

As with properties, events can be "auto-implemented" meaning that there's an underlying backing field generated for you.

Just like properties can have explicit getters and setters:

private Action onAction2;
public Action OnAction2
{
    get
    {
        return onAction2;
    }
    set
    {
        onAction2 = value;
    }
}

Events can have explicit add and remove handlers:

private Action onAction3;
public event Action OnAction3
{
    add
    {
        onAction3 += value;
    }
    remove
    {
        onAction3 -= value;
    }
}

There's no way an outside class can directly access the underlying onAction3 field through the OnAction3 event just as you cannot directly access the onAction2 field through the OnAction2 property.

And of course, by explicitly implementing these accessors, you can perform other actions as well such as value validation or transformation.

like image 101
Jeff Mercado Avatar answered Sep 02 '25 14:09

Jeff Mercado