views:

44

answers:

2

My Two versions of the following declarations work fine.

1) Func<int,int,int> findMax=Max;
   Console.WriteLine("Max={0}",findMax(10,20));

2)Func<int,int,int> findMax=new Func<int,int,int>(Max);
   Console.WriteLine("Max={0}",findMax(10,20));

where

public static T Max<T>(T a, T b) where T:IComparable
{
            if (a.CompareTo(b) > 0) return a;
            else return b;
}

In listing 2 , i instantiated the delegates,but in listing 1 i did not.How does the code work fine for listing 1 without instance creation of Func delegate?

+2  A: 

This is a new feature in C# 2; the compiler will implicitly create the delegate instance.

This a pure syntactic sugar; the compiled IL is identical.

SLaks
+4  A: 

No, in both cases you instantiated the delegate. It's just that in the first version it's hidden by a method group conversion. The first form is effectively syntactic sugar for the second.

Basically Max is a method group, and a method group can be converted to any compatible delegate type.

Jon Skeet
Opposite. I guess Jon meant that the first one is syntactic sugar for the second :), else it's spot on.
Øyvind Bråthen
@Øyvind: Fixed, thanks :)
Jon Skeet