From version 7.0, C# introduced a new feature called discards to create dummy variables, defined by the underscore character _. Discards are equal to unassigned variables. The purpose of this feature is to use this variable when you want to intentionally skip the value by not creating a variable explicitly.
Every developer will have come across the scenarios like checking if the given string is a valid DateTime object or not, by using the tryparse method. However, the tryparse method expects the out parameter to produce the DateTime result in addition to returning the boolean result, so we must declare DateTime result variable to use it in the out parameter even if we don't use it. This would be an ideal situation to use discards variable if we are not going to use the result object.
- DateTime result;
- if (DateTime.TryParse("02/29/2019", out result))
- {
- Console.WriteLine("Date is valid");
- }
- else
- {
- Console.WriteLine("Date is not valid");
- }
In the example above, we never used the result object. We are just checking if the given string is a valid DateTime or not.
- if (DateTime.TryParse("02/29/2019", out _))
- {
- Console.WriteLine("Date is valid");
- }
- else
- {
- Console.WriteLine("Date is not valid");
- }
- _ = DateTime.TryParse("02/29/2019", out result);
Additional Points
- The Discards variable was introduced in C# 7. So, it will work only on version 7 and above.
- If you have a value tuple that expects multiple values and you are interested in one or two values, you can use Discards without creating other variables. For example, var (a, _, _) = (1, 2, 3)
- In Async programming, if we use the Task.Run method to call some methods and if you are not interested in return result, we can use it. For example, _ = Task.Run(() => { }
Discards in C# provide a way to ignore local variables if not used, instead of creating them. I think this is a very nice hidden feature of C# that people may not be using very often. I will keep sharing more of the hidden gems in my upcoming blogs. If you have something to share, do post it in the comments section.

Conax LearnPosted Mar 18, 2021, 10:34 PM
Very well explained.