In last few posts about I have written lots of things about delegates and this post is also part of that series. In this post we are going to learn about Action delegates in C#. Following is a list of post related to delegates. Delegates in C#. Multicast Delegates in C#. Func Delegates in C#. Action Delegates in c#: As per MSDN action delegates used to pass a method as parameter without explicitly declaring custom delegates. Action Delegates are used to encapsulate method that does not have return value. C# 4.0 Action delegates have following different variants like following. It can take up to 16 parameters. Action – It will be no parameter and does not return any value. Action(T) Action(T1,T2) Action(T1,T2,T3) Action(T1,T2,T3,T4) Action(T1,T2,T3,T4,T5) Action(T1,T2,T3,T4,T5,T6) Action(T1,T2,T3,T4,T5,T6,T7) Action(T1,T2,T3,T4,T5,T6,T7,T8) Action(T1,T2,T3,T4,T5,T6,T7,T8,T9) Action(T1,T2,T3,T4,T5,T6,T7,T8,T9,T10) Action(T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11) Action(T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12) Action(T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13) Action(T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14) Action(T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15) Action(T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16) So for this Action delegate you can have up to 16 parameters for Action. Sound interesting!!… Enough theory now. It’s time to implement real code. Following is a code for that. using System;
using System.Collections.Generic;
namespace DelegateExample
{
class Program
{
static void Main(string[] args)
{
Action<String> Print = p => Console.WriteLine(p);
Action<String,String> PrintAnother = (p1,p2)=> Console.WriteLine(string.Format("{0} {1}",p1,p2));
Print("Hello");
PrintAnother("Hello","World");
}
}
}
In the above code you can see that I have created two Action delegate Print and PrintAnother. Print have one string parameter and its printing that. While PrintAnother have two string parameter and printing both the strings via Console.Writeline.
Now it’s time to run example and following is the output as expected.
That’s it. Hope you liked it. Stay tuned for more updates!!