Programming in C# – Events

You can subscribe to an event and then you are notified by the publisher that a new event has been raised

public class Pub
{
    public Action OnChange { get; set; }
    public void Raise()
    {
        if (OnChange != null)
        {
            OnChange();
        }
    }
}

public void CreateAndRaise()
{
   Pub p = new Pub();
   p.OnChange += () => Console.WriteLine(“Event raised to method 1”);
   p.OnChange += () => Console.WriteLine(“Event raised to method 2”);
   p.Raise();
}

Event Syntax

  • no longer public property but public fields
  • the compiler protects your field from unwanted access.
  • It cannot be added to a delegate.
  • No outside users can raise an event.

Leave a Reply

Your email address will not be published. Required fields are marked *