Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(_) => 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?

like image 268
Larry Avatar asked Feb 06 '15 10:02

Larry


1 Answers

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.

like image 130
usr Avatar answered Oct 21 '22 03:10

usr