Out var _ and out _ difference?

In C # 7, we can do this:

byte.TryParse(p.Value, out _)

or how is it

byte.TryParse(p.Value, out var _)

Are there any differences?

+4
source share
2 answers

Unlike what others in their comments said: No, there are no differences. Both of them produce the same IL.

Both

byte.TryParse(p.Value, out _);
Console.WriteLine(_);

and

byte.TryParse(p.Value, out var _);
Console.WriteLine(_);

will result in a compiler error with C # 7, as it is _not intended to be used.

Usage is _not limited to parameters, but can also be used for returns (as pointed out by Euc)

byte.TryParse(p.Value, out var _); // I don't care about the out variable
_ = SomeMethod(); // I don't care about the return value

There is an excellent answer, covering most things about missing parameters here .

: out _ out var _, out _ out var legalVariableName.

, . , . Ben Voigts .

+3

, _.

string _;

int.TryParse("123", out var _); // legal syntax for discard
int.TryParse("123", out _); // compile error, string _ is incompatible with out int parameter

int _;

int.TryParse("123", out var _); // discard
Console.WriteLine(_); // error: variable is not assigned
int.TryParse("123", out _); // passes existing variable byref
Console.WriteLine(_); // ok: prints "123"

, out _ , . out typename identifier - # 7, .

+3

Source: https://habr.com/ru/post/1693668/


All Articles