Saturday, February 8, 2020

C# Discard


C# 7 allows us to discard the returned value which is not required. Underscore (_) character is used for discarding the parameter. The discard parameter (_) is also referred to as write-only. We cannot read the value from this parameter.

Let us explain C# discard concept with a simple example

public void IntegerValidator()
{
   WriteLine("Please enter a numeric value"); 
   if (int.TryParse(ReadLine(), out int x)) 
   { 
       WriteLine("Entered data is a number"); 
   }
}


The above code uses a local variable x just for passing it as a parameter without using this variable anywhere else. So, if the variable is not used, then it should not have a name and no value should be assigned to it.

Discard does the same thing, i.e. instead of using the variable name, we can just use the underscore character. Same code can be rewritted using Discard as below:

public void IntegerValidator()
{
   WriteLine("Please enter a numeric value"); 
   if (int.TryParse(ReadLine(), out int _)) 
   { 
       WriteLine("Entered data is a number"); 
   }
}


This discard option is not limited to a single variable. You can use discard with any number of variable.

Discard is a way to intentionally ignore local variables which are irrelevant for the purposes of the code being produced. It's like when you call a method that returns a value but, since you are interested only in the underlying operations it performs, you don't assign its output to a local variable defined in the caller method.

1 comment: