Reprinted http://www.devsanon.com/c/using-discards-feature-of-c-7
Suppose you want to call a method return values and variables have also accepted out, but you do not want to use the out variable content will be returned.
So far, we are creating a dummy variable, the future will not use it or discard it .
Use C # 7, you can now use the " discard"
Discard the local variables, they can be assigned a value, and this value can not be read (discarded). In essence, they are "write-only" variable.
These discarded without a name, but with _ represents (underscore).
So let's look at the following example.
Suppose we have a ConcurrentQueue integer, we want something from the team, but not actually use it.
int outDummy; if(m_myQueue.TryDequeue(out outDummy)) { //do something here } else { //do something else here }
Now, using C # 7, we can use discarded.
if(m_myQueue.TryDequeue(out _)) { //do something here } else { //do something else here }
And has a column value will not be unusable.
For example, the following code
int x = 0; if(m_myQueue.TryDequeue(out _)) { x = _; }
Will not compile, it will not appear in IntelliSense.
Remember, however, due to the _ is contextual keyword, so if you use a name _ declare a variable, then the variable is used.
int x = 0; int _; if(m_myQueue.TryDequeue(out _)) { x = _; }
In the above code, it deleted from the queue values assigned to the variable X , as in the above case, used as a variable instead of discarding underlined.
in conclusion
C # discard function is provided a method ignore some local variables, which is a function of the design.
At runtime, you may need a variable, and the compiler may generate a name for.
Since _ keywords are contextual keyword, so you need to set the code strategies to avoid the use of the name _ declare local variables, in order to reduce confusion.
Earlier versions of this function is compatible with the .NET platform, because it does not need to change the CLR.