Skip to content

Switch expression with 'object' receiver type inconsistently casts int to double #58634

@rotemdan

Description

@rotemdan

Version Used:
.NET 6.0.0

Steps to Reproduce:

var s = "a";

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

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

Compare with:

var s = "a";

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

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

Expected Behavior:
Second example should behave like first, and not implicitly cast to Double, since it has an object-typed target.

Actual Behavior:
Second example implicitly casts to Double, costing me hours of unnecessary bug tracking to try to understand why some values in my program unexpectedly came out as Double instead of Int after I removed some cases from a simple switch expression.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Area-CompilersuntriagedIssues and PRs which have not yet been triaged by a lead

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions