KiynL
KiynL

Reputation: 4266

Event vs no Event Action in C#?

In general, I want to know, what is the effect of the event keyword behind the action and what is the difference between it and action without event and what feature does it add?

Hint: Please answer this question like this, because I did not find exactly that.

public event Action action; // event action

public Action action; // action

Upvotes: 0

Views: 535

Answers (1)

printf
printf

Reputation: 335

When you declare public Action action; you have a public delegate. It can be reassigned anywhere, which may be dangerous. When you declare public event Action action; you have a class with a hidden delegate field, and the class exposes only some functionality of delegates; in particular you can only attach and detach methods to it using += and -=, but not outright reassign using =. To clarify what this means: suppose you have the following code:

using System;

class Worker
{ 
  public Action action;

  public void DoWork() {
    action();
  }
}

static class Test
{  
  public static void Foo() {
    Console.WriteLine("Foo!");
  }

  public static void Main() {
    Worker w = new Worker();
    w.action = Foo;
    w.DoWork();
  }
}

The class Worker has a public delegate named action. In Main we create a new instance w and make its action point to the method Foo. Later we may reassign it by saying something like w.action = Bar. This may be seen as dangerous.

If the field action of class Worker were defined instead as event, i.e. public event Action action; then a direct assignment such as w.action = Foo would be illegal. Instead we can attach a particular handler to the event using +=. The following then works:

using System;

class Worker
{ 
  public event Action action;

  public void DoWork() {
    action();
  }
}

static class Test
{  
  public static void Foo() {
    Console.WriteLine("Foo!");
  }

  public static void Main() {
    Worker w = new Worker();
    w.action += Foo;
    w.DoWork();
  }
}

Upvotes: 3

Related Questions