Moffen
Moffen

Reputation: 2003

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

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?

Upvotes: 3

Views: 5735

Answers (1)

Jeff Mercado
Jeff Mercado

Reputation: 134601

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.

Upvotes: 12

Related Questions