Artur
Artur

Reputation: 5532

Use NotNullWhenAttribute when `#nullable disable`

How can we use NotNullWhen attribute (or some alternative?) when #nullable disable?

For example I have an extension method:

public static bool IsNullOrEmpty<T>([NotNullWhen(false)] this IEnumerable<T> e)
{
    return e == null || !e.Any();
}

And usage

if(ids.IsNullOrEmpty()
{
    throw new Exception();
}

var id = ids.First();

The compiler shows me warning on ids.First():

Possible 'System.NullRefernceException'

If I do #nullable enable the warning disappears. I want to achieve same effect with #nullable disable. Is it possible?

Update Screenshot enter image description here

Upvotes: 2

Views: 1511

Answers (1)

Artur
Artur

Reputation: 5532

@МаксимКошевой's comment pointed me to the correct direction: it's was Resharper's warning, not Roslyn. To hide this warning I installed JetBrains.Annotations nuget packages and used [ContractAnnotation] attribute like this:

[ContractAnnotation("null => true")]
public static bool IsNullOrEmpty<T>(this IEnumerable<T> e)
{
    return e == null || !e.Any();
}

Upvotes: 1

Related Questions