Roslyn: NotNullIfNotNull is not working with implicit operator

Created on 13 Nov 2019  路  5Comments  路  Source: dotnet/roslyn

Probably Roslyn compiler ignores NotNullIfNotNullAttribute when it is applied to implicit operator.
Let's assume that we have a class

public sealed class Foo
{
  private readonly int value;

  internal Foo(int value) => this.value = value;

  [return: NotNullIfNotNull("foo")]
  public static implicit operator string?(Foo? foo) => foo is null ? null : foo.value.ToString();
 }

Now we can convert it into string implicitly as follows:

string str = new Foo(10);

In this case the compiler emits CS8600 warning: Converting null literal or possible null value to non-nullable type. However, it is obviously that new operator is null-safe.

Area-Compilers Bug New Language Feature - Nullable Reference Types

Most helpful comment

Moving issue up to 16.8.

All 5 comments

IMHO, if input argument has type A (not A?) and method return type is marked with this attribute then return type should be treated as non nullable.

This happens with explicit casts as well.

I have a project to test both cases if you want it.

@jcouv @cston - I think this is going to be a pretty big issue in .NET 5 now that XElement is fully annotated. The most common way to make an XElement is to pass in a string to the ctor. But XElement's ctor takes an XName, which has an implicit op from string. Now any dev who has nullable enabled will get a warning when creating an XElement this way:

image

Any chance we can look into fixing this?

Moving issue up to 16.8.

Was this page helpful?
0 / 5 - 0 ratings