10 November 2017

stop creating your own delegates, start using Action delegates

If you are still defining custom delegates, you can stop creating them. In place of them, you can use Action And Func delegates. Sounds cryptic!, don't worry, we will go into detail.

How we define custom delegates?

Delegates are function pointers, which are defined like below.

public delegate void ClickEventHandler (object sender, EventArgs args);

And then you will use the delegate to define an event.

public event ClickEventHandler Click = null;

So in practice, every time you need a new delegate to match the signature of the target method. In this way, you end up creating new delegates just to match the target method signatures. Creating custom delegates is no longer necessary in latest C# .NET, you easily use built-in Action Delegates.

Use Action delegates in place of custom delegates

The Click event can be defined using an Action delegate like below. Using Action delegate we can almost ALL the time stop worrying about creating new delegates. How cool is that!

public event Action<object, EventArgs> Click = null;

Now if you are wondering what are these Action Delegates, refer my another blog post on generic delegates.

No comments:

Post a Comment