Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Exploring Action Delegate

0.00/5 (No votes)
25 Sep 2010 1  
In the last few days, I found a very elegant way to use the delegate...

We used delegate a lot in some or the other way. Like we know, the event base model that we use in Windows as web programming, is based on delegate only. I am in the habit of using delegates often. In the last few days, I found a very elegant way to use the delegate. I was in the habit of using only generic delegates that allows us type safety and a lot more flexibility.

In our traditional programming, we use the delegate as in the following steps:

  1. Declaring the delegate
  2. Creating object of the delegate and assigning it to the appropriate function
  3. Calling the delegate

Let's see the code:

.NET 2.0 introduced one generic delegate Action which takes a single parameter and returns nothing. Its declaration is:

C#
Public delegate void Action<T1>(T1 t1) // Takes 1 parameter and returns nothing

This is a very elegant way to use the delegate.

And C# 3.0 introduced 4 delegates which are as follows:

  1. C#
    Public delegate void Action() 	// Takes no parameter and returns nothing 
  2. C#
    Public delegate void Action<T1,T2>(T1 t1,T2 t2) 	// Takes 2 parameters 
    						// and returns nothing 
  3. C#
    Public delegate void Action<T1,T2,T3>(T1 t1,T2 t2,T3 t3) // Takes 3 parameters 
    						// and returns nothing 
  4. C#
    Public delegate void Action<T1,T2,T3,T4>(T1 t1,T2 t2,T3 t3),T4 t4) // Takes 4 
    					// parameters and returns nothing 

Let's see them running.

As from the code, we can also see that Action delegate also provides a method invoke to call the method.

These Action delegates can also be used with Anonymous methods as:

They can also be used with lambda function. Let's see:

So code diligently and efficiently.

Note: The ForEach and ForEach<T> methods each take an Action<T> delegate as a parameter. The method encapsulated by the delegate allows us to perform an action on each element in the array or list.

Happy .NETing….

Cheers,

Brij


License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here