As I was answering this question, I observed a very strange behaviour unique to switch expressions - they seem to be able to infer their types when they have an ambiguous type.
For example, This doesn't compile
double a = new Random().Next(2) == 0 ? (short)1 : (uint)1;
because the compiler "doesn't look" at the double a part when type checking, and sees that the expression is either of type short or uint. An expression can't be of two types, so an error is output. This is fine. It is quite well-known that C# doesn't look at the type of variable that you are assigning to, just like in generics:
static T F<T>() => default(T);
double d = F(); // can't infer that T is double
However, switch expressions break this "rule". If I rewrite the first code snippet with switch expressions:
double a = (new Random().Next(2) == 0) switch {
true => (short)1,
false => (uint)1
};
Then suddenly it compiles! Unlike the first code snippet, the compiler seems to have paid attention to the double a part and figured out that I want a double. I tried looking at the docs for switch expressions, but it doesn't mention that it will perform any automatic conversions to the result type or anything like that.
Why is C# so smart when dealing with switch expressions, but not with other kind of expressions (such as ternary operator)?