7

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?

Community
  • 1
  • 1
Larry
  • 17,605
  • 9
  • 77
  • 106
  • 5
    The same rule that makes an single underscore acceptable as a parameter name in the general case? `_` is a valid identifier in C#. – Frédéric Hamidi Feb 06 '15 at 10:13
  • I did not knew that and I am very surprised... Thanks for pointing this. – Larry Feb 06 '15 at 10:17
  • I want to mark as a duplicate of [this](http://stackoverflow.com/questions/950616/what-characters-are-allowed-in-c-sharp-class-name) but I don't want to Mjolnir it, so here's my vote. – Rawling Feb 06 '15 at 10:22

1 Answers1

12

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.

usr
  • 168,620
  • 35
  • 240
  • 369
  • 7
    It is also worth noting that conceptually an underscore signifies that the parameter it represents it not used in the inner function, but it needs to be supplied to satisfy the compiler. Basically a shorthand way of saying "don't mind me". – Adam Houldsworth Feb 06 '15 at 10:26
  • TIL `_` is a valid variable name – Shashank Shekhar Mar 22 '16 at 21:56