Search code examples
c#.netlambdaanonymous-methods

About in case,C# the syntax of anonymous methods simpler than syntax of lambda expressions. Book:Professional C# 5.0 and .NET 4.5.1


Recently, i read "Professional C# 5.0 and .NET 4.5.1 by Christian Nagel; Jay Glynn; Morgan Skinner" book. And i confused about: "in case,the syntax of anonymous methods simpler than syntax of lambda expressions" in book.

Details in Chapter 8: Delegates, Lambdas, and Events

LAMBDA EXPRESSIONS "NOTE The syntax of lambda expressions is simpler than the syntax of anonymous methods. In a case where a method to be invoked has parameters and you don’t need the parameters, the syntax of anonymous methods is simpler, as you don’t need to supply parameters in that case."

Can anyone explain/sample why anonymous methods don't need to supply parameters in that case?


Solution

  • Can anyone explain/sample why anonymous methods don't need to supply parameters in that case?

    Because if you're not using the delegate parameters, you can leave it up to the compiler to auto-generate them for you.

    Example:

    internal delegate void MyDelegate(string s);
    
    public class Foo
    {
        public void F()
        {
            MyDelegate del = delegate { Console.WriteLine("hello!"); };
        }
    }
    

    When i specify no parameters (because im not explicitly using them in my delegate), the compiler translates it into the following:

    public void F()
    {
        MyDelegate del = delegate(string param0)
        {
            Console.WriteLine("hello!");
        };
    }
    

    Or if you want the real nasty stuff:

    [CompilerGenerated]
    private static void <F>b__0(string param0)
    {
        Console.WriteLine("hello!");
    }
    
    public void F()
    {
        if (Foo.CS$<>9__CachedAnonymousMethodDelegate1 == null)
        {
            Foo.CS$<>9__CachedAnonymousMethodDelegate1 = new MyDelegate(Foo.<F>b__0);
        }
        MyDelegate del = Foo.CS$<>9__CachedAnonymousMethodDelegate1;
    }