Func is probably most commonly used in LINQ - for example in projections: list.Select(x => x.SomeProperty) or filtering: list.Where(x => x.SomeValue == someOtherValue) or key selection: list.Join(otherList, x => x.FirstKey, y => y.SecondKey, ...)
Action is more commonly used for things like List
Traditional way of using Delegate
//Declare delegate
public delegate void PrintMessage(string message);
public delegate int Calculate(int x, int y);
class SimpleClass
{
public void SayHello(string name)
{
Console.WriteLine("Hello {0}", name);
}
public int Add(int x, int y)
{
return x+y;
}
}
//Use delegate
var sc = new SimpleClass();
var printer = new PrintMessage(sc.SayHello);
printer("Pollux");
var calculator = new Calculate(sc.Add);
var result = calculator(5,10);
Action
This delegate was introduced in Framework 2.0. We can now use Action
Action act = delegate(string name)
{
Console.WriteLine("Hello ", name);
};
Call the delegate use
act(4, 5)
Func
This was introduced in Framework3.5. This delegate is different from Action
Func fn = delegate(int x, int y)
{
return x+y;
};
Call the delegate use
Console.WriteLine(“Using Func<> :” + fn(6, 6));
No comments:
Post a Comment