JStevens
JStevens

Reputation: 2152

Nullable Class as a Property is not Nullable. Why?

I have a class that I created where a property is another class I wrote. I am being warned that my property is non-nullable and I don't understand why. Aren't all properties of nullable classes nullable?

  public class Yeast
{
    public int? Id { get; set; }
    public Code Brand { get; set; }
    public Code Style { get; set; }
    public string? Trademark { get; set; }
    public int? TempMin { get; set; }
    public int? TempMax { get; set; }
    public double? Alcohol { get; set; }
    public string? Note { get; set; }   
}

enter image description here

 /// <inheritdoc cref="ICode"/>
public class Code : ICode
{
    /// <inheritdoc cref="ICode.Id"/>
    public int? Id { get; set; }

    /// <inheritdoc cref="ICode.ParentId"/>
    public int? ParentId { get; set; }

    /// <inheritdoc cref="ICode.Literal"/>
    public string? Literal { get; set; }

    /// <inheritdoc cref="ICode.Enabled"/>
    public bool? Enabled { get; set; }

    /// <inheritdoc cref="ICode.Description"/>
    public string? Description { get; set; }
}

public interface ICode
{
    /// <summary>
    /// Code Unique Identifier
    /// </summary>
    int? Id { get; set; }

    /// <summary>
    /// Code Foreign Key
    /// </summary>
    /// <remarks>Optional</remarks>
    int? ParentId { get; set; }

    /// <summary>
    /// Literal Name of Code
    /// </summary>
    string? Literal { get; set; }

    /// <summary>
    /// Description of Code
    /// </summary>
    string? Description { get; set; }

    /// <summary>
    /// Enabled for Use
    /// </summary>
    bool? Enabled { get; set; }


}

Upvotes: 1

Views: 365

Answers (2)

Oliver
Oliver

Reputation: 9498

It looks to me that you have nullable reference types enabled in your project, but are not aware of that fact.

With nullable reference types enabled, when you define a property to be of type Code you are actually telling the compiler that it will never be null, and the compiler will try to assert that analyzing your code and generating warnings.

If null is a valid and expected value of your Brand property, then simply declare it as Code?. If not, then you need to guarantee that it will always have a not-null value once its containing class is instantiated.

Upvotes: 1

Jimmy
Jimmy

Reputation: 28386

The issue here is that if you do new Yeast().Brand.Id you'll get a NullReferenceException because Brand is null - but you declared it wouldn't be.

So either the constructor needs to set Brand to a non-null Code value, or you need to mark it as nullable so the compiler can flag it in the consuming code (i.e. say that new Yeast().Brand needs to handle the possibility of a null value).

Upvotes: 3

Related Questions