Tuesday, August 24, 2010

Func< T,Tresult> , Action< T> and Predicate< T>

There are many Pre-defined delegates in C#, such as eventhandler, Predicate.

Func and Action two pre-defined delegate:

The syntax for Funcion is:

public delegate TResult Func(
T arg
)

The syntax for Action is:

public delegate void Action< in T>(
T obj
)

So Func and Action are essentially a special delegate:

We can use: Func myfunc=delegate(T para){ //Some method return Tout;}
//delegate calling an anonymous method;
Action myAction=delegate(T para){ //somemethod return void;}
//delegate calling an anonymous method;

As well, lambda expression can be considered as a special delegate calling an anonymous method: on the "=>" left side is the parameters to input, on the "=>" right side is the method, if the method return void, the delegate is void and if the method returns some type, the delegate returns some type.

So we can write:
Fun myFunc=(T para)=>(//Some method returns Tout);
Action myAct=(T para)=>(//Some method return void);

Here is some examples:

Func myFunc= delegate(string s)
{
return s.ToUpper();
};

We can write as: Func myFunct= (string s)=>s.ToUpper();

Console.WriteLine(myFunct("This is a test for Func delegate"));

As well for Action:

Action myAction=delegate(string s)
{
Console.WriteLine(s);
}

We can also write as Action myAction=(string s)=>{Console.WriteLine(s)};

Test the above code:

myAction("This is a test for Action delegate");

Predicate is the same thing, except the function called return boolean, it can also be written lambda expression.

No comments: