Mastodon

Discards(_) in C#

Sep 26, 2019 by Kolappan N

Sometimes you might have to create a variable in C# code that you will not use, like that out parameter that you don’t need. It would be nice if you don’t have to declare a variable just for the sake of it. Well, Discard solves this problem.

Discard is represented by underscore( _ ) character. You can use it in place of any temporary dummy variable and it will do the job. It will act like a variable. According to the C# Guide,

C# supports discards, which are temporary, dummy variables that are intentionally unused in application code. Discards are equivalent to unassigned variables; they do not have a value.

Here is an example use case,

public void CheckResult(out bool isFail, out double totalMarks) {
  // Function logic here
}

public callingFunction() {
  bool isFail;
  CheckResult(isFail, _); // The _ is the discard variable
}

The C#’s built in int.TryParse method is also a good example of this. This method has an out param which contains the parsed numerical value but you can use a discard if you are only using the function to check if a string contains a number.

Some of the popular use cases for a discard are

Why should you use discards instead of temp variables?

Technically it improves code performance. Discards are not allocated storage. Using discards in a program reduces its memory consumption.

But far more importantly it makes you code clean. You don’t have to create those temp, temp1 or t, t1 variables often. The readability of the code is greatly improved.