|
|||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
IntroductionFun with Func <T, TResult> : Generic Delegate
In C# 1.1, we had code like the one shown below: Step 1delegate bool IsGreaterThan(int inputNumber);
Step 2static bool IsGreaterThan3(int number)
{
return number > 3 ? true : false;
}
Step 3IsGreaterThan igt = new IsGreaterThan(IsGreaterThan3);
Console.WriteLine("Number is greater than 3 : {0}", igt(4));
In step 1, we have a IsGreaterThan igt1 = delegate(int number1)
{
return number1 > 3 ? true : false;
};
Notice the anonymous method call. In Func<int, bool> testFunc = delegate(int number2)
{
return number2 > 3 ? true : false;
};
Console.WriteLine("Number is greater than 3 : {0}", testFunc(4));
Here, the anonymous method will take an integer as an input parameter and will return a boolean value based on the comparison result. Notice: We did not define any Func<int, bool> testFuncWithLambda = inNum => inNum > 3 ? true : false;
Console.WriteLine("Number is greater than 3 : {0}", testFuncWithLambda(4));
One good example of We can use Func<int, int, int, int> ManyFunc = (int a, int b,int c) => a + b+ c;
Console.WriteLine("ManyFunc is {0}", ManyFunc(2, 2, 3));
If you use Reflector on this code, you will find code like the one shown below: Func<int, int, int, int> ManyFunc = delegate (int a, int b, int c)
{
return (a + b) + c;
};
Console.WriteLine("ManyFunc is {0}", func123(2, 2, 3));
Also, Func<int, int, int, int> ManyFunc = (int a, int b,int c) => a + b+ c;
Console.WriteLine("ManyFunc is {0}", ManyFunc(2, 2, 3));
Expression<Func<int,int, int>> ExpressionFunc = (int a, int b) => a + b ;
InvocationExpression ie =
Expression.Invoke(ExpressionFunc, Expression.Constant(4), Expression.Constant(5));
Console.WriteLine(ie.ToString());
Console.WriteLine(ExpressionFunc.Body);
Console.WriteLine(ExpressionFunc.Body.NodeType);
foreach (var paramname in ExpressionFunc.Parameters)
{
Console.WriteLine("parameter name is {0}", paramname.Name);
}
Console.WriteLine(ExpressionFunc.Type);
In this example, we have a lambda expression as I refactored some .NET 1.1 code with History
|
||||||||||||||||||||||||||||||||||||||||