Programming in C# – Delegates and raising events

public class Pub
{
     public event Action OnChange = delegate { };
     public void Raise()
     {
          OnChange();
     }
}


 

Event Syntax protects your field from unwanted access.

not using a public property but a public field

 

An event cannot be directly assigned to operator so no one can remove previous subscriptions.

No outside users can access the delegates.

Also some special syntax to initialise the event to an empty delegate. You can remove the is null as we know that it will never be null.

Example shown below:-

public class MyArgs : EventArgs

{

public MyArgs(int value)

{

Value = value;

}

public int Value { get; set; }

}

public class Pub

{

public event EventHandler<MyArgs> OnChange = delegate { };

public void Raise()

{

OnChange(this, new MyArgs(42));

}

}

public void CreateAndRaise()

{

Pub p = new Pub();

p.OnChange += (sender, e)

=> Console.WriteLine(“Event raised: {0}”, e.Value);

p.Raise();

}

Custom Event Accessor allows custom addition and removal of events

much like GET And set but it uses add / remove instead.

public class Pub
{
     private event EventHandler<MyArgs> onChange = delegate { };
     public event EventHandler<MyArgs> OnChange
     {
          add
          {
               lock (onChange)
               {
                    onChange += value;
               }
          }
          remove
          {
               lock (onChange)
               {
                    onChange -= value;
               }
          }
     }
     
     public void Raise()
     {
          onChange(this, new MyArgs(42));
     }
}

Summary

* Delegates are a type that defines a method signature and contain a reference to a method

* Delegates can be instantiated, passed around, and invoked

* Lambda expression use the => operator

* Events are a layer of synthetic sugar on top of delegates to easially implement the publish-subscribe pattern.

* Events can only ber raised from the declaring class. Users of events can only remove and add methods in the invocation list.

* You can customise events by adding custom event accessor and by directly using the underlying delegate type.

Leave a Reply

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