Docs: Last code sample is incorrect

Created on 9 Sep 2020  Â·  2Comments  Â·  Source: dotnet/docs

Please check the last code sample given here. It should contain an explicitly declared variable. It seems like a classic copy-paste error.

string numberAsString = "1640";
// Missing the following line
// int number;
if (Int32.TryParse(numberAsString, out var number))
Console.WriteLine($"Converted '{numberAsString}' to {number}");
else
Console.WriteLine($"Unable to convert '{numberAsString}'");
// The example displays the following output:
// Converted '1640' to 1640


Document Details

⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Area - C# Guide product-question

Most helpful comment

The original one works fine. Please check:

Starting with C# 7.0, you can declare the out variable in the argument list of the method call, rather than in a separate variable declaration.

So, this example doesn't have a separate declare.
```c#
string numberAsString = "1640";

if (Int32.TryParse(numberAsString, out int number))
Console.WriteLine($"Converted '{numberAsString}' to {number}");
else
Console.WriteLine($"Unable to convert '{numberAsString}'");
// The example displays the following output:
// Converted '1640' to 1640
```

All 2 comments

The original one works fine. Please check:

Starting with C# 7.0, you can declare the out variable in the argument list of the method call, rather than in a separate variable declaration.

So, this example doesn't have a separate declare.
```c#
string numberAsString = "1640";

if (Int32.TryParse(numberAsString, out int number))
Console.WriteLine($"Converted '{numberAsString}' to {number}");
else
Console.WriteLine($"Unable to convert '{numberAsString}'");
// The example displays the following output:
// Converted '1640' to 1640
```

Thanks for asking the question @elninoisback

The comment by @JohyPark is correct. Starting with C# 7, the declaration can be inline where the variable is used.

I'll close this.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

stanuku picture stanuku  Â·  3Comments

JagathPrasad picture JagathPrasad  Â·  3Comments

tswett picture tswett  Â·  3Comments

sebagomez picture sebagomez  Â·  3Comments

Eilon picture Eilon  Â·  3Comments