False CS0023 error message
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:
dotnet new console- Change
Console.WriteLine("Hello, World!");toConsole.WriteLine("Hello, World!" + + " "); 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"
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.
A possible error message improvement is to mention the operator type. ie, Unary operator '+' cannot be applied .......
This is definitely an error case, and the compiler is right to error. That said, it could be clearer here as Youssef points out.
I imagine we'd take a diagnostic message update here. Checking with @jaredpar that he agrees.