dotnet / csharplang

The official repo for the design of the C# programming language
11.62k stars 1.03k forks source link

Documentation: switch expressions #3255

Open azygis opened 4 years ago

azygis commented 4 years ago

Add a warning into msdn of switch expressions that the final return type is upcasted, depending on return type of all arms.

Example depicting the issue: https://dotnetfiddle.net/6nLmxT Notice how line 39 itself does go into .ToObject<bool>(), but then it's casted back to JToken. If at least one arm has a return type of object - it works the same way as usual switch/case.

There is also a similar SO question.

This case should be documented as it might be quite a breaking change for some projects.

I am not entirely sure that this repo should have documentation issues - please let me know it should be reported somewhere else and I will do that!

333fred commented 4 years ago

@BillWagner I'd just transfer this over, but I'm not sure if your system will tag it correctly if I do that. Can you move it over?

alrz commented 4 years ago

@CyrusNajmabadi do you think it's worthwhile to skip/warn on such cases when we offer to use switch expressions?

CyrusNajmabadi commented 4 years ago

@alrz can you give a specifi example of what the user code would be and what the warning would be?

alrz commented 4 years ago

@CyrusNajmabadi

The implicit conversion on switch expression arms should match with the implicit conversion on returned expressions in the original code.

As shown in the example, all switch expression arms have an implicit conversion to Double which is not present in the original tree.

Does that make sense?

CyrusNajmabadi commented 4 years ago

i'd rather the fix just introduce the right cast somewhere to amke that work. Would that be possible?

alrz commented 4 years ago

I took a stab at it and it seems like dynamic is the only exception here. Maybe we should only generate cast if we have dynamic as target type.

https://github.com/dotnet/roslyn/compare/master...alrz:fix-switch

Could we prove that no other conversion has this property? i.e. GetSwitchTypeIfIncompatible returns non-null for anything other than dynamic