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

Delegates and Generics

Almost all .NET developers know about delegates; its one of the feature which makes .NET distinct from other VMs…Here’s one lame example

class Program
{
    delegate double SimpleDelegate(int[] values);
 
    static double average(int[] values)
    {
        return values.Average();
    }
 
    static double sum(int[] values)
    {
        return values.Sum();
    }
 
    static void Main(string[] args)
    {
        SimpleDelegate averageLogic = new SimpleDelegate(Program.average);
        Console.WriteLine("Average of 1, 2, 3 is {0}", averageLogic(new int[] { 1, 2, 3 }));
 
        Console.ReadLine();
    }
}

Now some of these .NET developers might know that you can use Generics while defining the delegate…e-g

class Program
{
    delegate double SimpleDelegate(int[] values);
    delegate T ComplexDelegate<S, T>(S[] values);
 
    static double average(int[] values)
    {
        return values.Average();
    }
 
    static double sum(int[] values)
    {
        return values.Sum();
    }
 
    static void Main(string[] args)
    {
        SimpleDelegate averageLogic = new SimpleDelegate(Program.average);
        ComplexDelegate<int, double> sumLogic = new ComplexDelegate<int, double>(Program.sum);
        Console.WriteLine("Average of 1, 2, 3 is {0}", averageLogic(new int[] { 1, 2, 3 }));
        Console.WriteLine("Sum of 1, 2, 3 is {0}", sumLogic(new int[] { 1, 2, 3 }));
 
        Console.ReadLine();
    }
}

If you get yourself comfortable with Delegates with Generics…you can easily then go through many of the delegates in Base Class Library; like family of Action<T> and family of Func<T> delegates which appears to be heavily used in the source code of Silverlight Toolkit

Published Thursday, March 05, 2009 11:21 AM by khurram
Filed under: ,

Comments

No Comments

New Comments to this post are disabled