Version Used: VS 16.0 Preview 1.1
Steps to Reproduce:
static bool F(object o1, object o2)
{
var s1 = o1 as string;
var s2 = o2 as string;
if (s1 != null && s2 != null)
{
return s1 == s2;
}
if (s1 == null || s2 == null)
{
return false;
}
return o1 == o2;
}
Actual Behavior:
Applying suggested "Use pattern matching" code fixes produce the following code:
static bool F(object o1, object o2)
{
if (s1 != null && s2 != null)
{
return s1 == s2;
}
if (!(o1 is string s1) || !(o2 is string s2))
{
return false;
}
return o1 == o2;
}
The declaration site of s1 and s2 is beyond the first use of the variables, thus making the first line produce "use before declare" errors.
Simpler repro:
static void F(object o)
{
var s = o as string;
if (s != null)
{
return;
}
if (s == null)
{
return;
}
}
produces
static void F(object o)
{
if (s != null)
{
return;
}
if (!(o is string s))
{
return;
}
}
I think this is the same issue that https://github.com/dotnet/roslyn/pull/32440 fixed. (use of pattern variable before null check).
Dave , can you validate this with latest build
Verified that there is no longer a pattern matching suggestion after https://github.com/dotnet/roslyn/pull/32440. This fix will go into 16.0.Preview3