I\'ve just come across discards in c# and am wondering a couple things that I feel Microsoft Docs on Discards didn\'t explain very well.
In general, there is no sense to use discard in this sentence:
_ = nc.Read(someBuffer, 0, someSize);
since you can just ignore the return value. I did never anyone using standalone discards, but the documentation covers some specific cases when it can be useful.
The discards are used when you have to provide a variable, but don't need it.
As already covered in the provided documentation page, discards are very useful for:
switch (stream)
{
case MemoryStream _:
case FileStream _:
ProcessStream(stream);
break;
}
If you want to check if you can parse a string to an integer, but don't care about the result:
if (int.TryParse(str, out _))
{
// do something
}
Otherwise, you would have to declare an out variable, which you wouldn't use and which would consume some memory.
(_, _, area) = city.GetCityInformation(cityName);
Without discards you would deconstruct the result into 3 different variables, and use only one of them. With discards the code has cleaner intentions and more ineffective in terms of memory management.