tags:

views:

550

answers:

6

Like Anonymous Methods ,the delegates i am declaring down using "delegate" keyword are anonymous delegates?

namespace Test
{
    public delegate void MyDelegate();
    class Program
    {
        static void Main(string[] args)
        {
            DelegateTest tst = new DelegateTest();
            tst.Chaining();
            Console.ReadKey(true);
        }
    }

    class DelegateTest
    {
        public event MyDelegate del;

        public void Chaining()
        {
            del += delegate { Console.WriteLine("Hello World"); };
            del += delegate { Console.WriteLine("Good Things"); };
            del += delegate { Console.WriteLine("Wonderful World"); };
            del();
        }
    }
}
+2  A: 

Yes, they are anonymous delegates (or, more specific, delegates calling an anonymous method).

Lucero
+2  A: 

Yes. Anonymous delegates cannot be referred to directly by name, so using the delegate(){} syntax means they are anonymous.

barkmadley
+5  A: 

Your delegate collection in the example points to a number of anonymous methods. A delegate is "just a method pointer". It doesn't matter if it points to a real method or an anonymous method.

Please see http://msdn.microsoft.com/en-us/library/0yw3tz5k%28VS.80%29.aspx

Brian Rasmussen
+1  A: 

They are delegates to anonymous methods. This is one way to make anonymous methods, which was available since .NET 2.0. With .NET 3.0 you can also use lambda expressions which are simpler to write (but compile to the same code). I suppose that's what you meant with "anonymouse methods". But really, they are one and the same thing.

Vilx-
Lambda expressions and anonymous methods in lambda syntax are not really the same. Your statement is true if you use the lambda syntax with curly braces: (x) => {y();}
Lucero
+1  A: 

That's correct, you have assigned a number of anonymous methods to an event.

If you're using a newer version of c#, you can also do something similar with lambdas. for example:

class DelegateTest
{
    public event Action del;

    public void Chaining()
    {
        del += () => Console.WriteLine("Hello World");
        del += () => Console.WriteLine("Good Things");
        del += () => Console.WriteLine("Wonderful World");
        del();
    }
}
Greg D
Do you mean C# 3.0 ?
+2  A: 

There's no such thing as an "anonymous delegate" (or rather, that's not a recognised term in the C# specification, or any other .NET-related specification I'm aware of).

There are anonymous functions which include anonymous methods and lambda expressions.

Your code shows plain old anonymous methods - although they are using the one feature lambda expressions don't have: the ability to not express the parameters at all when you don't care about them.

Jon Skeet