So one may ask “What is the advantage of using discards in C#?”, and if you don’t know what discards are you can check out the MS C#7 Documentation about it.
Basically discards are variables in simple terms, and the declaration of the variable as a discard is by assigning it the underscore (_) as its name. Let’s look at an example of it using tuples. And if you want to know more about tuples look at my older post on tuples.
Example discard in C#
//GetUserName returns a tuple of firstname, lastname
var (firstname, _) = GetUserName(5);
As you can see above I have declare lastname as a discard, the advantage is that the lastname variable may not even be allocated any storage. Thus in a sense discards can reduce memory allocations, that is one of the main advantage of discards. Not to mention that it the intent of the code above clearer, readability wise and maintainability wise. There are other places you can use discards also.
Out parameters methods
The code below shows using discard in a TryParse method like below, where we use the out method for getting the value, but if we don’t really care about the value discards comes in handy here.
if(Int32.TryParse("1234", out _))
{
//do something
}
Pattern Matching
One can also use discards in pattern matching in C#. In the below example I am using pattern matching to process a user where a user can be a student or partime student, and they both are process the same way for example.
switch (user)
{
case Student _:
case PartTimeStudent _:
ProcessStudent(user);
break;
}
Deconstruct method
In C# you can also use discards for deconstruct methods, where you use a method name Deconstruct with out parameters, let’s look at an example of it. It is another handy way to get data out of class, structures and get them into tuples.
public class Match
{
public string HomeTeamName { get; set; }
public string AwayTeamName { get; set; }
public int HomeTeamScore { get; set; }
public int AwayTeamScore { get; set; }
public void Deconstruct(out string homeTeamName, out string awayTeamName)
{
homeTeamName = HomeTeamName;
awayTeamName = HomeTeamName;
}
public void Deconstruct(out string homeTeamName, out string awayTeamName, out int homeTeamScore, out in awayTeamScore)
{
homeTeamName = HomeTeamName;
awayTeamName = HomeTeamName;
homeTeamScore = HomeTeamScore;
awayTeamScore = AwayTeamScore;
}
}
var match = new Match { HomeTeamName = "Ravens", AwayTeamName ="Bulls", HomeTeamScore = 0, AwayTeamScore = 1 };
//get the home and away team name only
var (home, away) = match;
//using discards
var (homeName, _, homeScore, _) = match;
Summary
I hope this helps in explaining where you can see potentials of using discards in C#, it is a way of intentionally not wanting a variable, the plus side of it, allows one to read the code more clearly.