Monday, March 19, 2012

What is Func<T> and Action<T> ?

These two are inbuilt delegate types which can use without defining a new delegate type with each and every parameter type and return type.

Func(Of TResult)

Which can hold method references  which have return types with input parameters or not.As well as there are bunch of overloads
example-:Here I need to add two integers and return the result.. 
Here my Adding method ,which expects the Func with two inputs and one out put.
public static void PerformAction(Func<int,int,int> method,int x,int y)
{
   int result=method.Invoke(x, y);
}
Here my is my controller class
static void Main(string[] args)
{
   Func<int, int, int> addingFunc = (x, y) => (x + y);
   PerformAction(addingFunc , 5, 10);
}

Action(Of T)


Which can hold method references which have no return types.There are bunch of overloads for the Action delegate,
here i use same example without retuning the result,instead of that i write it in to a just Console.
public static void PerformAction(Action<int,int> method,int x,int y)
{
   method.Invoke(x, y);
}
Here my is my controller class
static void Main(string[] args)
{
   Action<int, int> addingAction = (x, y) => Console.WriteLine(x + y);
   PerformAction(addingAction, 5, 10);
}      

No comments:

Post a Comment