C# Hidden Gems – Discards Variable ( _ )

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

From version 7.0, C# introduced the new feature called discards to create dummy variable defined by 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 variable explicitly.

For example, if you are calling the method and it returns the object but caller is only interested in calling the method but not interested in the return object. In such case, we can use discards variable so that it can reduce in terms of memory allocation and make your code clear as well.

How to use

Every developer would have come across the scenarios like checking the given string is valid datetime object or not by using tryparse method. However, tryparse method expects the out parameter to produce the datetime result in addtion to returing the boolean result so we must declare datetime result variable to use it in out parameter even if we dont use it. This would be ideal situation to use discards variable if we are not going to use the result object.

Without Discards Variable

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 result object. we are just checking the given string is valid datetime or not.

With discards

if (DateTime.TryParse("02/29/2019", out _))  
{
Console.WriteLine("Date is valid");
}
else
{
Console.WriteLine("Date is not valid");
}

With discards variable, we can completely ignore the result variable.

If we want to ignore the return result and interested in actual result object only, we can do the above example as below.

_ = DateTime.TryParse("02/29/2019", out result);

Additional Points

  • Discards variable introduced in C# 7. So, it will work only on version 7 and above.

  • If you have 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 Task.Run method to call some methods and not interested in return result. For example, _ = Task.Run(() => { }

Conclusion

The discards in C# provides a way to ignore local variables if not used instead of creating it. I think this is a very nice hidden feature of c# that people may not be using it very often. I will keep sharing more of hidden gems in my upcoming blogs. If you have something to share, please do post it in comments section.