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

1

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?

Hash answered 6/2, 2015 at 10:12 Comment(3)
The same rule that makes an single underscore acceptable as a parameter name in the general case? _ is a valid identifier in C#.Philcox
I did not knew that and I am very surprised... Thanks for pointing this.Hash
I want to mark as a duplicate of this but I don't want to Mjolnir it, so here's my vote.Sousa
E
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.

Ecbolic answered 6/2, 2015 at 10:24 Comment(2)
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".Chemaram
TIL _ is a valid variable nameShipboard

© 2022 - 2024 — McMap. All rights reserved.