sonar-dotnet icon indicating copy to clipboard operation
sonar-dotnet copied to clipboard

Fix S3440 FP: Variable assignment and switch expression

Open a10r opened this issue 4 years ago • 1 comments

Description

We believe we found a false positive of rule S3440 ("Remove this useless conditional"). Consider the following method:

public static Uri ToWebsocketUri(this Uri uri)
{
	var builder = new UriBuilder(uri);
	builder.Scheme = uri.Scheme switch
	{
		"https" => "wss",
		"http" => "ws",
		"wss" => "wss", // <--
		"ws" => "ws", // <--
		_ => throw new ArgumentException($"Cannot convert URI scheme '{uri.Scheme}' to a websocket scheme."),
	};
	return builder.Uri;
}

S3440 is raised at the two marked lines. We believe S3440 is incorrect here since these two conditionals cannot be removed without changing the behaviour of the code.

After some testing, we think that this FP occurs whenever there is a switch expression with a conditional of the form X => X and the result is assigned to any assignment target, unless the assignment target is a newly declared local variable. For example, S3440 is not raised when we change the method to the following:

public static Uri ToWebsocketUri2(this Uri uri)
{
	var builder = new UriBuilder(uri);
	string scheme = uri.Scheme switch
	{
		"https" => "wss",
		"http" => "ws",
		"wss" => "wss",
		"ws" => "ws",
		_ => throw new ArgumentException($"Cannot convert URI scheme '{uri.Scheme}' to a websocket scheme."),
	};
	builder.Scheme = scheme;
	return builder.Uri;
}

Related information

C#/VB.NET Plugins version: SonarLint for Visual Studio 2019 (5.3.0.41207) Visual Studio version: Visual Studio 2019 (16.11.8) MSBuild / dotnet version: .NET Core 3.1 SonarScanner for .NET version (if used): no Operating System: Windows 10

a10r avatar Jan 07 '22 12:01 a10r

Another example

string M(string s) =>
    s switch
    {
        null => null, // S3440 <- FP
        "" => "Empty",
        _ => "Not empty",
    };