C# Hidden Gems - Discards Variable (_)

This will be a series of multiple blog posts to explore some of the hidden gems among C# features. Hidden gems are the surprisingly useful features of C#, not being used much by common developers.

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.

For example - this is when you are calling a method that returns the object but the caller is only interested in calling the method but not in the returned object. In such cases, we can use a discards variable so that it can reduce the memory allocation and make your code clear as well. 
How to use

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.

Without Discards Variable
  1. DateTime result;  
  2. if (DateTime.TryParse("02/29/2019"out result))  
  3. {  
  4.     Console.WriteLine("Date is valid");  
  5. }  
  6. else  
  7. {  
  8.     Console.WriteLine("Date is not valid");  
  9. }  

In the example above, we never used the result object. We are just checking if the given string is a valid DateTime or not.

With discards
  1. if (DateTime.TryParse("02/29/2019"out _))  
  2. {  
  3.     Console.WriteLine("Date is valid");  
  4. }  
  5. else  
  6. {  
  7.     Console.WriteLine("Date is not valid");  
  8. }  
With discards variable, we can completely ignore the result variable. If we want to ignore the returned result and are interested in the actual result object only, we can do the above example as below. 
  1. _ = 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.