Search code examples
c#delegatesanonymous-methods

(_) => DoWork(); How an underscore is valid as a anonymous delegate parameter?


In an excellent answer about starting a timer immediately, I could see the following code:

    timer.Elapsed += timer_Elapsed;
    ThreadPool.QueueUserWorkItem((_) => DoWork());
...

void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
    DoWork();
}

void DoWork() {
    // etc...
}

I tried it myself, and I bumped on this line, where I thought there was a typo in the anonymous delegate construction:

                                What?
                                  |
                                  V
    ThreadPool.QueueUserWorkItem((_) => DoWork());

Which hidden rule make a underscore "_" acceptable as a parameter name in an anonymous delegate?


Solution

  • An underscore is a normal identifier character in C#. For example my_money is valid. So _ is just as valid as x.

    You could also write _ => DoWork() which I think is more common.