TryParse with out var param
A new feature in C# 6.0 allows to declare variable inside TryParse method. I have some code:
string s = "Hello";
if (int.TryParse(s, out var result))
{
}
But I receive compile errors:
What I am doing wrong? P.S.: in project settings C# 6.0 and .NET framework 4.6 are set.
A new feature in C# 6.0 allows to declare variable inside TryParse method.
Declaration expressions was cut from C# 6.0 and wasn't shipped in the final release. You currently can't do that. There is a proposal for it on GitHub for C# 7 (also see this for future reference).
Update (07/03/2017)
With the official release of C#7, the following code compiles:
string s = "42";
if (int.TryParse(s, out var result))
{
Console.WriteLine(result);
}
Just found out by accident, in vs2017, you can do this for brevity:
if (!Int64.TryParse(id, out _)) {
// error or whatever...
}
That is a new feature from C# 7, which is a very nice feature often used in conjunction with pattern matching. This feature, and many more, are announced in the C# team blog What’s New in C# 7.0.
The thing the team tries to achieve here is more fluid code. Do you remember some cases where the list of out variables is getting extremely long for no use? Just a quick example:
int i;
Guid g;
DateTime d;
if (int.TryParse(o, out i)) { /*use i*/ }
else if (Guid.TryParse(o, out g)) { /*use g*/ }
else if (DateTime.TryParse(o, out d)) { /*use d*/ }
See the problem? It is useless to have all those out variables sitting there doing nothing. The number of lines can be cut in half by using C# 7:
if (int.TryParse(o, out int i)) { /*use i*/ }
else if (Guid.TryParse(o, out Guid g)) { /*use g*/ }
else if (DateTime.TryParse(o, out DateTime d)) { /*use d*/ }
Not only the number of lines is minimized, there is also no unneccessary list of variables in scope where you don't want to have them. This prevents you to use a variable you didn't intend to use, but which is visible to you now.
This feature is also useful with pattern matching in switch
statements, like in this code (which has a different behavior than the above code!):
switch (o)
{
case int i: { /*use i*/ break; }
case Guid g: { /*use g*/ break; }
case DateTime d: { /*use d*/ break; }
}