-1

I'm beginner to C#, I have code where by accident I declared events skipping event keyword. I was sure that this is right code:

using System;

public class Player
{
    ...
    private float money;
    public Action<float> OnMoneyChanged; // missed `event` keyword.

    private void SetMoney(float amount)
    {
        money = amount;
        OnMoneyChanged?.Invoke(amount);
    }
}
public class Level
{
   public Level(Player player)
   {
      player.OnMoneyChanged += UpdateUi;
      ...
   }

   private void UpdateUi(float money)
   {
       ....
   }
}

And that's works perfect, no error, no bugs appear. I knows that formally by skipping event I didn't declare events but normal delegate.

The only drawback I came out is that this mislead other programmer who will read the code, they may conclude that something strange happening here.

The question is: what are the long consequences of missing event for delegate type?
What putting missing event keyword changes?

Sonny D
  • 897
  • 9
  • 29
  • Link: https://stackoverflow.com/questions/29155/what-are-the-differences-between-delegates-and-events solves all my considerations. – Sonny D Jul 31 '22 at 07:19

1 Answers1

1

If you add the event keyword (to Player.OnMoneyChanged), you won't be able to call Player.OnMoneyChanged.Invoke(...) outside of the Player class

ya_ilya
  • 26
  • 3