Delegates Actions, and Funcs

I think a worthwhile excursion for a .NET developer is to drill down the LINQ rabbit hole and see how far we can go.  A good first step is delegates.

There are delegates, multicast delegates and their syntactically sweeter versions, Actions, Funcs.

First, what is a delegate?

According to MSDN:
“A delegate is a type that references to methods with a particular parameter list and return type”.  

Delegates are a way of passing around a reference to a method that can be invoked whenever you want.  If thats still confusing think of events.  Events use multi-cast delegates that allow multiple subscribers to an event, and when that event is fired it will execute all the subscribers.

Simple Delegates

Output:

Displaying: Pipe to wall
Delegates are handy

 

You can see how declaring the delegates are completely separate from the method that is executed only when a delegate is instantiated with a method that has a matching signature are they linked.

Multicast Delegates

You can convert a delegate to a multicast delegate by using the “+=” to the delegate type variable.  .NET will automatically switch between a normal delegate and a multicast delegate.  The only caveat with multicast delegates is that they can have no return type.  Which makes sense as you won’t know what value was returned from what method executed.  In my example I just add the same method to the delegate, thus calling it 4 times, but you will most normally add different methods to execute.

Output:

Displaying: Pipe to wall
Displaying: Pipe to wall
Displaying: Pipe to wall
Displaying: Pipe to wall

 

Action and Func

Now enters the Action and Func types.  Action is a delegate that returns nothing, a void.  Func is a delegate that returns anything but.  These make usage much cleaner than using a delegate like above.  By changing the two delegates to an Action and a Func you now have:

 

Using Funcs you can easily squeeze in some useful functional programming into your code such as a useful Retry class:

 

Leave a Reply

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