Welcome to weblogs.com.pk Sign in | Join | Help

Delegates and Lambdas

Happy Eid Melad-un-Nabi!

In my last post about Delegates and Generics, we had the following delegate to play with…

delegate T ComplexDelegate<S, T>(S[] values);

Over the different releases of .NET / C#, defining delegate instances is becoming compact…Due to anonymous method, instead of establishing a separate method altogether; we can have an inline code..

ComplexDelegate<int, double> averageLogic = new ComplexDelegate<int, double>(
   delegate(int[] values)
   {
       return values.Average();
 
   });
 
//if you dont need the delegate parameters e-g
ComplexDelegate<int, double> alwaysReturn1Logic = new ComplexDelegate<int, double>(
   delegate
   {
       return 1;
   });

With support of lambda expressions in C# 3 / .NET 3.5; we dont need to repeat things i-e first telling what the type of variable is and then telling again while “newing” it up…

ComplexDelegate<int, double> sumLogic = ( values ) =>
{
   return values.Sum();
};
//And its more compact variation can be
ComplexDelegate<int, double> maxLogic = values => values.Max();

And in case you are wondering from where these .Average(), .Sum() and .Max() are coming; its due to Extension Methods in System.Linq; another feature they introduced in .NET 3.5 / C# 3. Lets define one to get our hands dirty with it too :)

//The class needs to be static; i-e you can only have static methods in this class
static class ExtensionMethods
{
    public static int MyRandom(this IEnumerable<int> values)
    {
        int len = values.Count();
        Random r = new Random(DateTime.Now.Second);
        int random = r.Next(len - 1);
 
        IEnumerator<int> enumerator = values.GetEnumerator();
        int looper = 0;
        int toReturn = default(int);
        while(looper<=random && enumerator.MoveNext())
        {
            toReturn = enumerator.Current;
            looper++;
        }
        return toReturn;
    }
}

Now you can magically call this method to any instance of int[]; all you need is to import this class’ namespace e-g

//I guess use of lambda is clear by now
ComplexDelegate<int, double> randomLogic = values => values.MyRandom();
Published Tuesday, March 10, 2009 3:22 PM by khurram
Filed under: ,

Comments

No Comments

New Comments to this post are disabled