Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

out var _ and out _ difference? [duplicate]

Tags:

c#

var

out

c#-7.0

In C# 7 we can do like this:

byte.TryParse(p.Value, out _)

or like this

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

Are there any differences?

like image 843
AsValeO Avatar asked Dec 14 '22 18:12

AsValeO


1 Answers

The difference is how they handle an existing variable named _.

string _;

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

or

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"

The reason for this is that out _ already had a meaning, and the language maintains backward compatibility with that old meaning. But out typename identifier is new syntax in C# 7, so there's no backward compatibility constraint.

like image 74
Ben Voigt Avatar answered Dec 30 '22 23:12

Ben Voigt