dotnet / dotnet/csharpstandard

The specification says ternary operator shouldn't compile when both alternatives have the same type

Open
#279 4 comments 0 reactions 0 assignees View on GitHub
type: bug
Dominant language
C#
Stars
815
Forks
99
Avg merge
1d 14h
Merged PRs (30d)
16

Description

_From @svick on September 17, 2016 19:53_

[The C# specification says this about the type of the ternary/conditional operator](https://github.com/ljw1004/csharpspec/blob/gh-pages/expressions.md#conditional-operator):

> The second and third operands, `x` and `y`, of the `?:` operator control the type of the conditional expression.
> - If `x` has type `X` and `y` has type `Y` then
> - If an implicit conversion ([Implicit conversions](https://github.com/ljw1004/csharpspec/blob/gh-pages/conversions.md#implicit-conversions)) exists from `X` to `Y`, but not from `Y` to `X`, then `Y` is the type of the conditional expression.
> - If an implicit conversion ([Implicit conversions](https://github.com/ljw1004/csharpspec/blob/gh-pages/conversions.md#implicit-conversions)) exists from `Y` to `X`, but not from `X` to `Y`, then `X` is the type of the conditional expression.
> - Otherwise, no expression type can be determined, and a compile-time error occurs.
> - If only one of `x` and `y` has a type, and both `x` and `y`, of are implicitly convertible to that type, then that is the type of the conditional expression.
> - Otherwise, no expression type can be determined, and a compile-time error occurs.

As far as I can tell, according to this, if `x` and `y` have the same type, it should be a compile-time error, because:
- `x` and `y` both have a type
- an implicit conversion (specifically, [identity conversion](https://github.com/ljw1004/csharpspec/blob/gh-pages/conversions.md#identity-conversion)) exists from `X` to `Y` and from `Y` to `X`

Since obviously code like that should (and does) compile, I think the specification should be fixed.

_Copied from original issue: dotnet/roslyn#13881_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.