Multicasting with Action

Func and Action are inherited from System.MulticastDelegate, which means that you could actually do multicasting with them and add multiple methods to the InvocationList. Let’s check how we do it.

Action Action1 = () => Console.WriteLine($"Hello From {nameof(Action1)}");
Action Action2 = () => Console.WriteLine($"Hello From {nameof(Action2)}");
Action Action3 = () => Console.WriteLine($"Hello From {nameof(Action3)}");
Action Action4 = () => Console.WriteLine($"Hello From {nameof(Action4)}");
Action Actions = Action1 + Action2 + Action3 + Action4;
Console.WriteLine($"Length of Invocation List :  {Actions.GetInvocationList().GetLength(0)}");
Actions();

Output of above code would be

Hello From Action1
Hello From Action2
Hello From Action3
Hello From Action4

The same can be done with Func as well. How do we remove one Action , same syntax as the delegates.

Actions -= Action4;

In fact, we could also use Actions instead of specifying delegates for events.

void Main()
{
  var demo = new DemoClass();
  demo.OutOfRange += ()=> Console.WriteLine("Out of Range");
  demo.NotAllowed += (x)=> Console.WriteLine($"Not Allowed : {x}");
  demo.Method1();
}
public class DemoClass
{
public event Action OutOfRange;
public event Action NotAllowed;
public void Method1()
{
       if(OutOfRange != null)
       OutOfRange();

       if(NotAllowed !=null)
       NotAllowed("Hey that's not allowed");
}
}
We could tweak it further by assigning a default action for our events. In this way, you can remove the checks for null. This is a possibility, but I am not quite sure if Microsoft Coding Conventions recommend Actions for events.
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s