tags:

views:

66

answers:

2

If i declare a delegate

public delegate void firstDelegate(string str);

firstDelegate handler = Strfunc;

handler("Hello World");

  ..
  static void Strfunc(string str)
  {
        Console.WriteLine(str);
  }

will the compiler translate the following line

firstDelegate handler=Strfunc;

into

firstDelegate=new firstDelegate(Strfunc);
+1  A: 

So far I can tell, YES.

This is called as "delegate inference".

BTW, if you want to "append" another function to this delegate, use:

handler += AnotherFunctionName;

And here is the words from C# Pros in the book professional-C#-2008, chapter 7:

For less typing, at every place where a delegate instance is needed, you can just pass the name of the address. This is known by the term delegate inference. This C# feature works as long as the compiler can resolve the delegate instance to a specific type. The code that is created by the C# compiler is the same. The compiler detects that a delegate type is required, so it creates an instance of that delegate type and passes the address of the method to the constructor.

Michael Mao
So for all function , i will pass only a single message.What i mean is,can i pass different messages,one for func1, and another for func2 ?
I am afraid NOT.multicase delegate, well, you can think of it as a bunch of functions to be executed in THAT order, each of which is passed with the same function agrument(s). So they all handle the same argument(s).This is a trick that is extremely useful when dealing with GUI since a spcific event might trigger multiple listeners(handler objects) to react.
Michael Mao
+2  A: 

That's right. Here is the disassembly from reflector:

.method private hidebysig static void Main(string[] args) cil managed
{
    .entrypoint
    .maxstack 3
    .locals init (
        [0] class ConsoleApplication4.Program/firstDelegate handler)
    L_0000: nop 
    L_0001: ldnull 
    L_0002: ldftn void ConsoleApplication4.Program::Strfunc(string)
    L_0008: newobj instance void ConsoleApplication4.Program/firstDelegate::.ctor(object, native int)
    L_000d: stloc.0 
    L_000e: ldloc.0 
    L_000f: ldstr "Hello World"
    L_0014: callvirt instance void ConsoleApplication4.Program/firstDelegate::Invoke(string)
    L_0019: nop 
    L_001a: ret 
}

which looks like this in C#:

private static void Main(string[] args)
{
    firstDelegate handler = new firstDelegate(Program.Strfunc);
    handler("Hello World");
}
Luke Quinane