I was messing around with C# switch expression and I encountered something quite weird.
Here is the code:
static void Main(string[] args)
{
Console.WriteLine(Test('a'));
Console.ReadLine();
}
public static string Test(char x)
{
return (x switch
{
'a' => (Func<int, string>)(i => "hello"),
_ => (Func<int, string>)(i => "world")
})(1);
}
The IDE (Visual studio), warns me about a IDE0004 C# Cast is redundant. So I trust it and decide to remove the cast. It applies to both (Func<int, string>) casts.
So, I decide to remove one of them:
public static string Test(char x)
{
return (x switch
{
'a' => i => "hello",
_ => (Func<int, string>)(i => "world")
})(1);
}
But now, the IDE underlines the "switch" keyword in red. The "error"'s message is "No best type was found for the switch expression". At this point, I assume that the suggestion from the IDE about redundancy was invalid and that following it inserts an error. However... When I run the program, even though the keyword is underlined red and there is an error, it compiles with no error and runs normally (it prints "hello" and blocks on the ReadLine).
So the question is: Is this a bug (either from the IDE or the compiler)? If it is, where can I report this? If it isn't... would someone care to elaborate on why this is happening?
Bonus: Also, let's pretend that "x" was instead a DateTimeOffset:
public static string Test(char x)
{
return (x switch
{
'a' => i => $"hello {i.DayOfWeek}",
_ => (Func<DateTimeOffset, string>)(i => "world")
})(DateTimeOffset.FromUnixTimeSeconds(1599335154));
}
Now, "switch" is still red with the same errot but, additionally, "DayOfWeek" is in red and mouse over tells "Cannot resolve symbol 'DayOfWeek'" but the definition of the type is there and everything still compiles and works as expected to output "hello Saturday".
From there, if I remove the second cast (Func<DateTimeOffset, string>), it won't compile because of error CS0149: Method name expected (I assume it somehow fails to properly parse the expression).