So one may ask “What is the advantage of using discards in C#?”, and if you don’t know what discards are you can check out the MS C#7 Documentation about it.

Basically discards are variables in simple terms, and the declaration of the variable as a discard is by assigning it the underscore (_) as its name. Let’s look at an example of it using tuples. And if you want to know more about tuples look at my older post on tuples.

Example discard in C#

As you can see above I have declare lastname as a discard, the advantage is that the lastname variable may not even be allocated any storage. Thus in a sense discards can reduce memory allocations, that is one of the main advantage of discards. Not to mention that it the intent of the code above clearer, readability wise and maintainability wise. There are other places you can use discards also.

Out parameters methods

The code below shows using discard in a TryParse method like below, where we use the out method for getting the value, but if we don’t really care about the value discards comes in handy here.

Pattern Matching

One can also use discards in pattern matching in C#. In the below example I am using pattern matching to process a user where a user can be a student or partime student, and they both are process the same way for example.

Deconstruct method

In C# you can also use discards for deconstruct methods, where you use a method name Deconstruct with out parameters, let’s look at an example of it. It is another handy way to get data out of class, structures and get them into tuples.

Summary

I hope this helps in explaining where you can see potentials of using discards in C#, it is a way of intentionally not wanting a variable, the plus side of it, allows one to read the code more clearly.