Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TryParse with out var param

Tags:

c#

c#-6.0

c#-7.0

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: enter image description here

What I am doing wrong? P.S.: in project settings C# 6.0 and .NET framework 4.6 are set.

like image 567
Anton23 Avatar asked Jul 30 '15 12:07

Anton23


People also ask

What method parameter type is used by TryParse method?

The type of this parameter is System.

What is Int32 TryParse string Int32 for?

TryParse(String, Int32) Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded.

Does TryParse throw exception?

Parse throws an exception if it cannot parse the value, whereas TryParse returns a bool indicating whether it succeeded. TryParse does not just try / catch internally - the whole point of it is that it is implemented without exceptions so that it is fast.

Can you TryParse a string?

TryParse(String, NumberStyles, IFormatProvider, Single) Converts the string representation of a number in a specified style and culture-specific format to its single-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed.


2 Answers

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); } 
like image 138
Yuval Itzchakov Avatar answered Oct 18 '22 04:10

Yuval Itzchakov


Just found out by accident, in vs2017, you can do this for brevity:

if (!Int64.TryParse(id, out _)) {    // error or whatever... } 
like image 30
Fat Shogun Avatar answered Oct 18 '22 05:10

Fat Shogun