Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Compiler error when combines throw expression together with generic types and null-coalescing operator #17754

Closed
sgjsakura opened this issue Mar 12, 2017 · 4 comments

Comments

@sgjsakura
Copy link

sgjsakura commented Mar 12, 2017

Version Used:
Visual Studio 2017
Steps to Reproduce:
The following code can reproduce the error:

public void Test<T>(T value)
{
  var x = value ?? throw new ArgumentNullException(nameof(value));
}

Expected Behavior:
The above code should be compiled correctly.
Actual Behavior:
CS0019: The '??' operator cannot be apply between type T and <throw expression>

@0xd4d
Copy link

0xd4d commented Mar 12, 2017

Try public void Test<T>(T value) where T : class

@gafter
Copy link
Member

gafter commented Mar 12, 2017

The interaction with the throw expression is a red herring. This also fails, as it should:

        var y = value ?? default(T);

The problem is that value isn't a nullable type or a reference type. Try the suggestion made by @0xd4d .

@sgjsakura
Copy link
Author

sgjsakura commented Mar 13, 2017

While the C# language sepcification says comparison between an unrestricted genertic value and null is accepable, and it will returns true/false if the actual type is non-nullable. actually, the following code can pass the compilation check:

var x = (value != null) ? value : default(T);

So does it possible to enhance the compiler to accept nul-coalescing for unrestricted genertic value?

Thanks~

@gafter
Copy link
Member

gafter commented Mar 13, 2017

@sgjsakura Yes, the language specification can be changed to make the compiler support that. Language feature requests are taken at https://github.com/dotnet/csharplang

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants