0

SAMPLE CODE

Using callback works as expected:

public void DoWork(object state)
{
    Console.WriteLine(state.ToString());
}

WaitCallback waitCallback = new WaitCallback(this.DoWork);
ThreadPool.QueueUserWorkItem(
   waitCallback, 
   "Via: WaitCallback");

Using anonymous method also works:

ThreadPool.QueueUserWorkItem(
   (object stateInfo) => { DoWork(stateInfo); },
   "via: anonymous method");

Using delegate with similar signature...

AlternateWaitCallback alternateCallback = new AlternateWaitCallback(this.DoWork);
ThreadPool.QueueUserWorkItem(
   alternateWaitCallback, 
   "Via: alternate WaitCallback");

...generates a compiler error: "cannot convert from AlternateWaitCallback to WaitCallback'

QUESTION

I understand that the delegate keyword is being used to define two new types that will act as callbacks. What I don't understand is: why can the compiler match the method signature of the anonymous method against WaitCallback... but it can't do the same for AlternateWaitCallback?

Pressacco
  • 2,815
  • 2
  • 26
  • 45

1 Answers1

2

why can the compiler match the method signature of the anonymous method against WaitCallback... but it can't do the same for AlternateWaitCallback?

An anonymous method has no intrinsic type (in other words, it's not definitely typed); it's just convertible to any delegate type with a compatible signature (WaitCallback in this case). AlternateWaitCallback, on the other hand, is its own type; you can't convert a type to another unless they have an inheritance relation or there is a conversion defined between them.

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758