What is this type of delegate called(C#)

192 Views Asked by At

I have these lines of code.

class Program
{
    public delegate void printer();

    public static void Method()
    {
        Console.WriteLine("Hello");
    }
    static void Main(string[] args)
    {
        printer del = delegate { Method(); };
        del();
        Console.ReadKey();
    }
}

Now what do i call this statement printer del = delegate { Method(); };.

Surely it cant be called anonymous method because here i have a named method.

4

There are 4 best solutions below

0
On BEST ANSWER

It's an anonymous delegate who's only function happens to be calling a named method.

13
On

It's called an Anonymous method

Surely it can't be called anonymous method because here I have a named method

It's still an anonymous method, as @Daniel pointed out in the comments what your doing is instantiating an instance of the printer delegate by assigning a method with the same signature (which happens to be...an anonymous method). You could avoid using an anonymous method completely by doing:

Printer del = Method;
0
On

It's an anonymous method, as the others have said.

You could also accomplish the same thing with this code:

Action del = () => Method();
del();

This way, you don't need to define the delegate and use the built-in Action type.

0
On

It's an anonymous method. The inside of the method does call a named one but that doesn't change the fact that the outher method is anonymous.

You can easily see this when you would expand del:

class Program
{
    public delegate void printer();

    public static void MethodA()
    {
        Console.WriteLine("Hello");
    }

    public static void MethodB()
    {
        Console.WriteLine("World");
    }
    static void Main(string[] args)
    {
        bool x = true;

        printer del = delegate 
        {
            if (x)
            {
                MethodA();
            }
            else
            {
                MethodB();
            }
        };

        del();
        Console.ReadKey();
    }
}

If you don't want to use a delegate you could do the same with an Action:

   Action delA = () => MethodA();
   delA();

Action points to a void returning method that takes no parameters.