Discard variable in C# .NET
In C#, the discard variable _
(underscore) is a special syntax introduced in C# 7.0. Discards are placeholder variables intentionally unused in application code. They are equivalent to unassigned variables and do not hold any value.
You indicate that a variable is a discard by naming it with an underscore (_).
Here we are going to discuss a few use cases of discard variables_
in day-to-day development activities, but there are many more depending on specific scenarios:
Ignoring Return Values
If a method returns a value that you don’t need, you can use the discard variable (_) to ignore it.
bool ValidateMemberAge()
{
return isValid;
}
_ = ValidateMemberAge();
Use in switch expression
In switch expressions, the discard variable (_) can be used to handle default cases.
int memberGroup = 5;
string result = number switch
{
1 => "Gold",
2 => "Silver",
_ => "Other"
};
Console.WriteLine(result); // Output: Other
Ignoring Task Result
A task result can be discarded when its value is not needed for further processing by using the discard variable (_).
internal async Task LongRunningTask()
{
_ = Task.Run(() =>
{
//Long running operation...
});
await GetOrderByID(Guid.NewGuid());
}
Ignoring Tuple elements
When working with tuples, you can ignore elements that you don’t need by using the discard variable (_).
var (name, _, _, dateOfBirth) = GetMemberInfo("21024000129");
Console.WriteLine($"Name: {name}, DateOfBirth: {dateOfBirth}");
Discard Out Parameters
When using methods with out
parameters, you might not need all of them. You can use the discard variable (_) to ignore the ones you don't need.
if (SampleMethod("test", out string statusCode, out _))
{
Console.WriteLine($"Status Code is: {statusCode}");
}
Pattern Matching
In pattern matching, you can use discards (_) to ignore parts of the pattern that you don’t care about.
if (person is Employee { Department: _ })
{
Console.WriteLine("This person is an employee.");
}
Discarding Values in LINQ Queries
When using LINQ, you can use the discard variable (_) to ignore certain values in a projection.
var numbers = new[] { 8, 15, 28, 60, 93 };
var query = numbers.Select((number, index) => (index, number, number % 2 == 0));
//ignoring number index
foreach (var (_, number, IsEven) in query)
{
Console.WriteLine($"{number} is even:{IsEven}");
}
Console.ReadLine();
Output
Null Exception Handling using the null coalescing operator (??
)
The right side of the assignment utilizes the null coalescing operator to throw a System.ArgumentNullException
when the argument is null. The code does not require the result of the assignment, so it is discarded. This expression ensures a null check. The use of discard clarifies the intent that the assignment result is not needed or used.
_ = arg ?? throw new ArgumentNullException(paramName: nameof(arg), message: "arg can't be null");
This example is applicable to older versions of .NET. In newer versions, we have a more streamlined approach to handle argument null exceptions using the ArgumentNullException.ThrowIfNull
method.
https://learn.microsoft.com/en-us/dotnet/api/system.argumentnullexception.throwifnull?view=net-8.0
Reference https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/discards
Thanks for reading.