Discards in C#

The other day I ran into an everyday run-of-the-mill issue that I never never thought much about. We’ve all been here, where we

want to check that a date string is valid using a predetermined format. This would be quite trivial to do using DateTime.TryParse. But

what got me thinking was the ugliness of having to use the Out parameter which is not bad to say, but having to declare a variable just

to never use it never really bothered me until today.

Lets consider the code below:

In the example above, all we want is the result whether the string is a valid DateTime. No need for the extra unused variable right?

Hello Discards

In C# 7.0 we have the ability to use Discards, which are like dummy variables. They are local variable that are read-only, they don't have names

and are represented as an _ (underscore). Below is how we can improve our code above using Discards.

By using the _ underscore in place of the out variable this reduces your keystrokes and cleans up your code files a bit.

With Tuples:

Discards are especially great when working with tuples and you need to ignore certain values from time- to time.

Summary:

There you have it, no more local variable that are never going to be used.

Share: