In C#7, you are allowed to do
if (int.TryParse("123", out int result))
Console.WriteLine($"Parsed: {result}");
or - if you don't use the result and just want to check if the parsing succeeds, discard the out value:
if (int.TryParse("123", out _))
Console.WriteLine("Syntax OK");
That works fine usually, but in Visual Studio 2017 the second example, where the out
parameter is empty, generates the warning
Warning AD0001: Analyzer 'Microsoft.CodeAnalysis.CSharp.Diagnostics.SimplifyTypeNames.CSharpSimplifyTypeNamesDiagnosticAnalyzer' threw an exception of type 'System.NullReferenceException' with message 'Object reference not set to an instance of an object.'.
The Visual Studio Versions where I could verify that it occurs is
Visual Studio Enterprise 2017 Version 15.1 (26403.7) Release
Visual Studio Enterprise 2017 Version 15.2 (26430.4) Release
Is this a bug, or is the usage of int.TryParse("123", out _)
not officially supported? I could not find any hint so far.
For completeness, here's the code of the console application showing the issue:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
if (int.TryParse("123", out _))
Console.WriteLine("Syntax OK");
}
}
}
I submitted a bug request (request #19180) to the development team, and they confirmed it is a bug. You can see the entire status here at GitHub dotnet/roslyn.
Pilchie commented 16 hours ago
I can repro that in 15.2, but not 15.3. Moving to compiler based on the stack, >Abut I'm pretty sure this is a dupe. @jcouv?jcouv commented 16 hours ago
Yes, this is a duplicate (of #17229 and possibly another one too). It was fixed in dev15.3 (#17544) and we were unfortunately unable to pull the >fix into dev15.2. Thanks @Matt11 for filing the issue and sorry for the bug.
It seems to be already fixed and will be - as far as I understood - available in the next update. But there is no announced date when it will be included by Microsoft, so I submitted an issue through "Send Feedback/Report a Problem" in Visual Studio 2017.
Notes:
The issue is not limited to TryParse. I verified that it also occurs if you write your own function, i.e. the following sample shows the warning AD0001 as well:
static void Main(string[] args)
{
bool myOutDemo(string str, out int result)
{
result = (str??"").Length;
return result > 0;
}
// discard out parameter
if (myOutDemo("123", out _)) Console.WriteLine("String not empty");
}
I noticed that there is now a VS Version 15.3 preview available, which should contain the fix mentioned in the GitHub comments. Check out the following link: Visual Studio 2017 Version 15.3 Preview. After installing it, I verified the issue again and can confirm it is fixed there.
Thanks to all who participated in the discussion above! (question comments)