Skip to content

Roslyn analyzer suggestion to convert a switch statement to switch expression alters runtime code behavior #58636

@rotemdan

Description

@rotemdan

Version Used:
.NET 6.0.0

Steps to Reproduce:

var s = "a";
object result;

switch (s) // Analyzer suggestion: "Use 'switch' expression"
{
	case "a":
		result = (int) 1234;
		break;
	case "b":
		result = 3.14;
		break;
	default:
		throw new Exception("");
};

Console.WriteLine(result.GetType().Name); // Prints "Int32"!

When applying the fix. The following code is produced:

var s = "a";

object result = s switch
{
	"a" => (int) 1234,
	"b" => 3.14,
	_ => throw new Exception(""),
};

Console.WriteLine(result.GetType().Name); // Prints "Double"!

Expected Behavior:
The fix should not alter runtime behavior of the code, or the suggestion shouldn't be given at all.

Actual Behavior:
The analyzer suggestion changes the runtime behavior of the conditional, it produces an object containing a value of type Double instead of Int32.

I have reported the unnecessary implicit coercion of Int32 (as well as Int64, which is a lossy cast to Double) before it is assigned to an object target as a compiler bug, but it was immediately dismissed as "By Design". Based on the fact that this "fix" is erroneously suggested by the analyzer as a "lossless" equivalent, I doubt it was intended. However, there's not much I can do except to report it.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions