roslyn icon indicating copy to clipboard operation
roslyn copied to clipboard

False CS0023 error message

Open explorest opened this issue 4 years ago • 4 comments

Version Used:
Latest . Running 'dotnet --info' at command line gives: .NET SDK (reflecting any global.json): Version: 6.0.101 Commit: ef49f6213a

Runtime Environment: OS Name: ubuntu OS Version: 20.04 OS Platform: Linux RID: ubuntu.20.04-x64 Base Path: /usr/share/dotnet/sdk/6.0.101/

Steps to Reproduce:

  1. dotnet new console
  2. Change Console.WriteLine("Hello, World!"); to Console.WriteLine("Hello, World!" + + " ");
  3. dotnet build

Expected Behavior: Some error message indicating that operator '+' when applied to operand of string type is a string concatenation operator which is a binary operator requiring two operands of type string.

Actual Behavior:

Ouput: ... error CS0023: Operator '+' cannot be applied to operand of type 'string' ...

This is obviously false as the operator '+' applied to operands of type string does string concatenation. From https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/addition-operator : "When one or both operands are of type string, the + operator concatenates the string representations of its operands"

explorest avatar Jan 22 '22 23:01 explorest

The error message looks correct to me.

Operator '+' can be applied to operands of type string and string, but it cannot be applied to operand of type string.

In other words, it's valid as a binary operator, not a unary operator.

For the code you have, the + " " is a unary expression where the error occurs. And it's correct that a unary + isn't applicable to a string.

Youssef1313 avatar Jan 23 '22 06:01 Youssef1313

A possible error message improvement is to mention the operator type. ie, Unary operator '+' cannot be applied .......

Youssef1313 avatar Jan 23 '22 06:01 Youssef1313

This is definitely an error case, and the compiler is right to error. That said, it could be clearer here as Youssef points out.

CyrusNajmabadi avatar Jan 24 '22 00:01 CyrusNajmabadi

I imagine we'd take a diagnostic message update here. Checking with @jaredpar that he agrees.

CyrusNajmabadi avatar Jan 24 '22 00:01 CyrusNajmabadi