C# 7: What are discards and how to use them

Let’s assume that you wish to call a method that has a return value and also accepts an out variable, but you do not wish to use the contents of the out variable that will be returned.
So far we were creating a dummy variable that will later not be used, or discarded.
With C# 7 you can now use Discards

Discards are local variables which you can assign a value to them and that value cannot be read (discarded). In essence they are “write-only” variables.

These discards do not have names, but rather they are represented with a _ (underscore).

So let’s go with the following example.
Assume we have a ConcurrentQueue of integers, from which we wish to dequeue something, without actually using that something.

What would we do?

Now, with C# 7 we can utilize discards.

And the value that has been dequeued will not and can not be used.

For example the following piece of code

will not compile, nor will it appear in IntelliSense.

Please remember though, that since _ is a contextual keyword, if you declare a variable with the name _ the variable will be used.

In the above code, the value that will removed from the queue will be assigned to the variable x, as in the above case the underscore is used as a variable and not as a discard.

Conclusion

The discards in C# enables a way to ignore some local variables, it is a design time feature.
At runtime a variable may be required and the compiler may generate a name for it.
Since the _ keyword is a contextual keyword, you need to set a code policy to avoid declaring local variables with the name _ to reduce confusions.
This feature is compatible with previous versions of .NET platforms as it does not require a CLR change.

Leave a Reply