1.
An Action is a type of delegate
2.
Encapsulates a method that has a single parameter and does not
return a value.
3.
Internally it is
deligate and defined as below
Action is a Delegate. It is defined like
this:
public delegate void Action();
4.
It may take 0 parameter to 16 parameters.
5.
You can use the
lambda expression in the action as shown below exapmle
6.
You use Anynonymos method using action as below
Definition
|
Action<string>
sample1 =
(string
x) => Console.WriteLine("String : 0}", x);
|
Call
|
sample1.Invoke("My string ");
|
Internally
Defined
|
public delegate
void Action<in T>(T obj);
|
|
|
Definition
|
Action<string,
string> example2 =
(x, y) => Console.WriteLine("Write {0} and {1}", x, y);
|
Call
|
example2.Invoke("string 1", "string
2");
|
Internally
Defined
|
public delegate
void Action<in T1, in T2>(T1
arg1, T2 arg2);
|
|
|
7.
Here is a small example that shows the usefulness of the Action
delegate
using
System;
using
System.Collections.Generic;
class Program
{
static void Main()
{
Action<String> displayString = new Action<String>(Program.DisplyString);
List<String> collectionOfStrings = new List<String> { "Ajay",
"Aarav" };
collectionOfStrings.ForEach(displayString);
Console.Read();
}
static void DisplyString(String
s)
{
Console.WriteLine(s);
}
}
Notice
that the foreach method iterates the collection of names and executes the
print
method against each member of the collection.
This a bit of a paradigm shift for us C# developers as we move towards a more
functional style of programming. (For more info on the computer science behind
it read this
No comments:
Post a Comment