views:

56

answers:

1

While learning on anonymous methods, i've found the following example on the internet:

namespace AnonymousMethods
{
    public class MyClass
    {
        public delegate void MyDelegate(string message);  //delegate accepting method with string parameter
        public event MyDelegate MyEvent;
        public void RaiseMyEvent(string msg)
        {
            if (MyEvent != null) MyEvent(msg);
        }
    }
    class Caller
    {
        static void Main(string[] args)
        {
            MyClass myClass1 = new MyClass();

// here the confusion
            myClass1.MyEvent += delegate
            {
                Console.WriteLine("we don't make use of your message in the first handler");
            };

            myClass1.MyEvent += delegate(string message)
            {
                Console.WriteLine("your message is: {0}", message);
            };

            Console.WriteLine("Enter Your Message");
            string msg = Console.ReadLine();
            myClass1.RaiseMyEvent(msg);
            Console.ReadLine();
        }
    }
}

I understand why this will work:

myClass1.MyEvent += delegate(string message){
    Console.WriteLine("your message is: {0}", message); }

But why this works too:

myClass1.MyEvent += delegate {
    Console.WriteLine("we don't make use of your message in the first handler"); }

When our delegate is declared like this:

public delegate void MyDelegate(string message);

Accepting methods with string as parameter.

+8  A: 

There is a difference between

delegate() { ...

and

delegate { ...

The first is an anonymous method that takes no arguments, while the latter omits the parameter list altogether. In this case, the compiler infers the parameters for you. You can use this form when you don't actually need the values of the parameters.

dtb