-2

I was just playing with delegate but I got confused about working of it. In below code

public delegate void HelloFunctionDelegate(string Message);

public static void Main()
{
    //HelloFunctionDelegate del = new HelloFunctionDelegate(Hello1);
    //del("hello from delegate");
    Console.WriteLine("Hello World");       
    Hello(Hello1);      
}

public static void Hello(HelloFunctionDelegate del)
{
    del("This is it");//we did not create instance of delegate 
}

public static void Hello1(string strMessage)
{
    Console.WriteLine(strMessage);
}

Here It is working in both ways.we can pass method by creating new instance (commented code)and without creating new instance of delegate (HelloFunctionDelegate )? What is the difference between them?

1 Answers1

1

There is no difference. Even if it looks like you are not creating a new instance of a delegate, you are still implicitly creating a new instance of a delegate, via a method group conversion.

Here:

Hello(Hello1);  

A method group conversion converts the method group expression Hello1 to an instance of the delegate type HelloFunctionDelegate, as specified in the spec:

The result of the conversion is a value of type D, namely a newly created delegate that refers to the selected method and target object.

Sweeper
  • 213,210
  • 22
  • 193
  • 313