Fragrance
|
We all might have encountered in which sometimes we need to ignore the returned values, especially the "out" arguments, and the best example is the TryParse method in which we check whether the string can be parsed to another type.
In the aboe code I want to ignore "boolParsedValue" and also want to make this variable inaccessible for developers so that they can reference it. With new C# 7.0, you can achieve this goal using "discards"
Discards Discards are write-only local variable, in which you can assign but cannot read. They don't have names but are represented by "_ (underscore)". Since _ cannot be read, it will not appear on the right side of an assignment. Discard in the above code will be as below.
Because _ is not readable, it will not appear in IntelliSense nor will compile the code.
Now suppose in the above code you explicitly define the _ variable and assign the value true, in that case _ will be not considered as discard since you are explicitly declaring the _ local variable.
Interesting trick
Value of v in the above code false, if you see properly in the check condition we have written out var _, and it will overrides the scope of previously declared _ variable. Assignment v = _ just reads the previously declared local variable (false) and assigns to v.
Comments
|
Categories
All
Archives
May 2020
|