Discards, in C#7 can be used wherever a variable is declared, to - as the name suggests - discard the result. So a discard can be used with out variables:
p.GetCoordinates(out var x, out _);
and it can be used to discard an expression result:
_ = 42;
In the example,
p.GetCoordinates(out var x, out _);
_ = 42;
There is no variable, _
, being introduced. There are just two cases of a discard being used.
If however, an identifier _
exists in the scope, then discards cannot be used:
var _ = 42;
_ = "hello"; // error - a string cannot explicitly convert from string to int
The exception to this is when a _
variable is used as an out variable. In this case, the compiler ignores the type or var
and treats it as a discard:
if (p.GetCoordinates(out double x, out double _))
{
_ = "hello"; // works fine.
Console.WriteLine(_); // error: _ doesn't exist in this context.
}
Note that this only occurs if, in this case, out var _
or out double _
is used. Just use out _
and then it's treated as a reference to an existing variable, _
, if it's in scope, eg:
string _;
int.TryParse("1", out _); // complains _ is of the wrong type
Finally, the *
notation was proposed early in the discussions around discards, but was abandoned in favour of _
due to the latter being a more commonly used notation in other languages.
out _
_
is not a variable, you do not declare it and you cannot use it by name. Inint _
that is a variable. – Monogeneticyou cannot use it by name
. I don't think so. I can doif (int.TryParse(str, out var _)) _ = 8;
– Goldenout *
, there is a comment to the blog mentioning this, so this was probably just an error in the post. – Sounderout _
, withoutvar
. Withvar
it's indeed the same as before. – Monogeneticif (int.TryParse(str, out _)) _ = 8;
– GoldenConsole.WriteLine(_)
- this won't compile claiming that there is no such variable. Quite weird. Even more: if you do something like_ = SomeMethodCall()
- this will be replaced by justSomeMethodCall()
in compiled code. So after all you still cannot really use that variable in any meaningful sense. – Monogenetic_
is a general purpose discard now, and the behavior is fully intended. – Sounderout _
andout var _
mean exactly the same thing and behave the same. @NikhilAgrawal You can assign anything to discards, you just can never get anything back from it. – Oteliaotero