Fix MA0067 false positive on default parameter values

Merged
ME
2mo ago
+26-0

What

MA0067 reports new Guid() when it is the default value of a parameter:

void Test(System.Guid value = new System.Guid()) { }

Guid.Empty is not a compile-time constant, so it cannot be used there (CS1736). Applying the code fix breaks the build.

Expected: no diagnostic. Actual: MA0067 is reported.

Fix

new Guid() without arguments is not reported when its parent operation is an IParameterInitializerOperation. The other forms (new Guid("..."), new Guid(0, ...), Guid.Parse(...)) are not constant expressions, so they cannot appear in a default value anyway. Attribute arguments cannot be of type Guid, so they need no handling.

The rule documentation now mentions this case.

Tests

Added ShouldNotReportError_ParameterDefaultValue, which covers a method, a local function and a lambda. UseGuidEmptyAnalyzerTests passes on roslyn5.9 (16/16) and roslyn4.8 (16/16).