Nullable Reference Types and HasValue-Style Properties

Viewed 400

Let's say we have this simple User class that has an optional (nullable) property for a phone number:

public class User
{
    public string? PhoneNumber { get; private set; }
}

And then, in other classes, I need to use the phone number of a user, if it has one:

public static void Example(User user)
{
    if (!(user.PhoneNumber is null))
    {
        DoSomething(user.PhoneNumber);
    }
}

This works fine, but is not even close to the readability of having something like:

public class User
{
    public string? PhoneNumber { get; private set; }
    public bool HasPhoneNumber => !(PhoneNumber is null);
}

And then using it like so:

public static void Example(User user)
{
    if (user.HasPhoneNumber)
    {
        DoSomething(user.PhoneNumber);
    }
}

This worked fine until C# 8's null safety changes. Now, the code above triggers a CS8604. This, of course, is the expected behavior of the compiler, but I am still looking for a way to avoid having is null (or != null) checks scattered all over the codebase. Is there a way to tell the compiler that a property is not null after a call to a method (or another property), similar to how the [NotNullWhen] attribute works for parameters?

1 Answers

Why don't you use an extension method like IsNullOrEmpty() or something like HasValue? You can use string rather than string? and checking null value will be like this:

public static void Example(User user)
{
    if (user.PhoneNumber.HasValue())
    {
        DoSomething(user.PhoneNumber);
    }
}
Related