Can I tell C# nullable references that a method is effectively a null check on a field
Asked Answered
C

3

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.

Cephalopod answered 24/11, 2019 at 14:16 Comment(4)
IMO you should use HasValue on a nullable type, not check it against null. It probably doesn't affect your problem though.Isogamy
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/…).Grassgreen
you could use the "dammit" ! operator. if(HasName) { Name = Name!.ToUpper(); }Eyebrow
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)Zoezoeller
N
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.

Nightgown answered 24/11, 2019 at 15:13 Comment(11)
Seems like we need more attributes or something like typescript's assertionsPolicewoman
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."Cephalopod
@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.Nightgown
this is the only acceptable solution in a multi-threaded system, Name could be null between the check and the usageZoezoeller
@Zoezoeller 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.Nightgown
Found the article: devblogs.microsoft.com/dotnet/… under "Avoiding dereferencing of nulls"Nightgown
I fixed the "can't find a proposal for this" problem. (github.com/dotnet/csharplang/issues/2997) Wish me luck.Cephalopod
@JohnMelville I've seen your proposal get closed today with the info that this feature was implemented in C#9. Updated the answer.Nightgown
Still doesn't really help when you have assertions that internally check & throw on nulls, and you expect proceeding code to no longer null check that field/property. Similar to how it works in TS.Doall
@DouglasGaskell That should be doable with MemberNotNull, can you elaborate on your issue?Nightgown
For me, I have a null check (plus other checks) wrapped in an extension method called IsValid(this object o). Adding the "old" NotNullWhen did the trick for me.Elbring
C
1

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

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

Cephalopod answered 19/4, 2021 at 22:29 Comment(0)
P
-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();
        }
    }
}
Pfister answered 24/11, 2019 at 14:47 Comment(2)
You are out of date learn.microsoft.com/en-us/dotnet/csharp/language-reference/…Urbai
@AluanHaddad I believe you meant to send this instead learn.microsoft.com/en-us/dotnet/csharp/nullable-referencesCochabamba

© 2022 - 2024 — McMap. All rights reserved.