Search code examples
c#nullableroslyn-code-analysisnullable-reference-types

Dereference of a possibly null reference in child class


Is it possible to tell the compiler that I know a method will return an object with a non-null property, even though that property is marked as nullable?

For example:


var seat = GetOccupiedSeat();
Console.WriteLine(seat.Person.Name);
// 'Person' may be null here.
// Dereference of a possibly null reference.

private Seat GetOccupiedSeat()
{
    // This method will always return a seat with a valid person and a valid name
    return new Seat(new Person("Bob"));
}

public class Seat
{
    public bool IsAvailable => Person == null;
    public Person? Person { get; set; }

    public Seat(Person? person = null)
    {
        Person = person;
    }
}

public class Person
{
    public string Name { get; set; }
    public Person(string name)
    {
        Name = name;
    }
}

Nullable-analysis attributes seem like the most likely things to help here, but none seem suitable to use in this context.

The kind of thing I was hoping to see was something like

[return: NotNull("Seat.Person")]
private Seat GetOccupiedSeat()
{
    return new Seat(new Person("Bob"));
}

Just wondering if anyone knows whether or not this is possible. Thanks.


Solution

  • Not that I know of, in this case.

    If you're sure that it shouldn't, at that point in your code, you could add:

    Debug.Assert(seat.Person is not null);
    

    This will also tell the compiler to assume seat.Person is not null from there on, and remove the compiler warning (in Debug mode).