C# Improve code Quality with Discards

With this article i will be exploring a newer C# language feature called discards. Discards are represented with the underscore character. As implied by the name, discards basically tell the reader of your code (and the compiler) that you will not utilize the result.

Consider the following code as our first example:

So again the underscore is the discard. In this example we are discarding the results of the MyMethod call. Just calling MyMethod without the return assignment would work the same. However by using a discard you are improving your code quality because you identify that there is a return type and you are explictly ignoring it. Without a discard the reader of your code may be left wondering – did they know there was a return type? or was that an omission on their part? With discards the code author’s intent is clear.

Discards can also be used with out parameters as in this example:

And finally, discards can be used as a stand-alone as in this example:

In this article I have shown you several situations in which you can utilize the discard language feature to improve your C# code quality.

References:

https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/discards

Tags: