Thursday, January 14, 2010

Func<T,TResults> – Flexible delegate to create reusable functions

Today while googling i found an interesting feature of delegate Func<T,TResults> ,it allows us to represent a method that can be passed as a parameter without declaring a custom delegate explicitly and the method must have one parameter that is passed to it by value and must return a value.

In the following example we need to explicitly define a new delegate and assign a named method to it.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BlogSamples
{
delegate int ConvertMethod(int _x);
class Program
{
static void Main(string[] args)
{
ConvertMethod objConv = SquareMe;
int val = 5;
//delegate is called
Console.WriteLine(objConv(val));
Console.ReadKey();
}
private static int SquareMe(int myInt)
{
return myInt * myInt;
}
}
}

Without explicitly defining a new delegate it can be simplified as below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BlogSamples
{
class Program
{
static void Main(string[] args)
{
Func convertMethod = SquareMe;
int val = 6;
Console.WriteLine(convertMethod(val));
Console.ReadKey();
}
private static int SquareMe(int myInt)
{
return myInt * myInt;
}
}
}


Please see the msdn link for more references.