26

Consider the following code:

#nullable enable
class Foo
{
    public string? Name { get; set; }
    public bool HasName => Name != null;
    public void NameToUpperCase()
    {
        if (HasName)
        {
            Name = Name.ToUpper();
        }
    }
}

On the Name=Name.ToUpper() I get a warning that Name is a possible null reference, which is clearly incorrect. I can cure this warning by inlining HasName so the condition is if (Name != null).

Is there any way I can instruct the compiler that a true response from HasName implies a non-nullability constraint on Name?

This is important because HasName might actually test a lot more things, and I might want to use it in several places, or it might be a public part of the API surface. There are many reasons to want to factor the null check into it's own method, but doing so seems to break the nullable reference checker.

4
  • 1
    IMO you should use HasValue on a nullable type, not check it against null. It probably doesn't affect your problem though. Commented Nov 24, 2019 at 14:45
  • I think for you case, you can wrap you code with #nullable disable then #nullable enable or restore again afterwards (learn.microsoft.com/en-us/dotnet/csharp/…). Commented Nov 24, 2019 at 15:10
  • 6
    you could use the "dammit" ! operator. if(HasName) { Name = Name!.ToUpper(); } Commented Nov 24, 2019 at 21:39
  • 1
    for a multi-thread application, you could have Name being null after the HasName check, using the variable locally instead of going back to the property (who knows what the property might do in its getter) is going to give some funky bugs (remember the using of an event handler where this has happened alot) Commented Nov 28, 2019 at 9:36

3 Answers 3

16

UPDATE:

C# 9.0 introduced what you're looking for in the form of MemberNotNullWhenAttribute. In your case you want:

#nullable enable
class Foo
{
    public string? Name { get; set; }

    [MemberNotNullWhen(true, nameof(Name))]
    public bool HasName => Name != null;
  
    public void NameToUpperCase()
    {
        if (HasName)
        {
            Name = Name.ToUpper();
        }
    }
}

There's also MemberNotNullAttribute for unconditional assertions.

Old answer:

I looked around at the different attributes from System.Diagnostics.CodeAnalysis and I couldn't find anything applicable, which is very disappointing. The closest you can get to what you want appears to be:

public bool TryGetName([NotNullWhen(true)] out string? name)
{
    name = Name;
    return name != null;
}

public void NameToUpperCase()
{
    if (TryGetName(out var name))
    {
        Name = name.ToUpper();
    }
}

It looks pretty cumbersome, I know. You can look at the MSDN docs for nullable attributes, maybe you'll find something neater.

Sign up to request clarification or add additional context in comments.

11 Comments

Seems like we need more attributes or something like typescript's assertions
I'll pick this one as the answer, because it appears that the real answer, as I feared, is "no, c# doesn't do that yet."
@JohnMelville I wasn't able to find a proposal for such a feature either, so I don't think we can expect this changing anytime soon.
@XIU The compiler is already lax in this aspect. If you do if(Name != null) return Null.ToUpper(), there will be no warning for a null dereference, even though technically it's a TOCTOU race condition. I remember Mads Torgersen speaking about how they considered that, but it would generate so many false positives the entire nullable reference types feature would be effectively useless - 99% of the time your properties won't be changed by another thread. So all you'd need to do is make an attribute that would make the check on this property be treated as a check for null on another property.
I fixed the "can't find a proposal for this" problem. (github.com/dotnet/csharplang/issues/2997) Wish me luck.
|
1

In C# 9.0 check out [MemberNotNull(nameof(Property))] and [MemberNotNullWhen(true, nameof(Property))] attributes.

https://github.com/dotnet/runtime/issues/31877

Comments

-10

String is a reference type, and nullable (e.g. int?) is nullable value types. So you can't really do this string? myString; What you need is this:

class Foo
{
    public string Name { get; set; }
    public bool HasName => !String.IsNullOrEmpty(Name);  ////assume you want empty to be treated same way as null
    public void NameToUpperCase()
    {
        if (HasName)
        {
            Name = Name.ToUpper();
        }
    }
}

2 Comments

@AluanHaddad I believe you meant to send this instead learn.microsoft.com/en-us/dotnet/csharp/nullable-references

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.