Search code examples
c#nullable

How to refactor constructor-chaining in enable nullability context?


I have old code base with constructor chaining which looks like this:

public class Foo
{   
    public Foo(string first, string second, string third)
    {
        this.First = first; 
        this.Second = second;
        this.Third = third;
    }

    public Foo(string first, string second) : this(first, second, null)
    {

    }
    public Foo(string first) : this(first, null)
    {
    }
    public string First { get; set; }

    public string Second { get; set; }

    public string Third { get; set; }
}

I added the <Nullable>enable</Nullable> setting, so as to protect the code from NullReferenceException.

As you can imagine when calling from a constructor with less parameters a constructor with more parameters and passing null - I get a warning on passing null that "Cannot convert null literal to non-nullable reference type."

One solution I see is to keep just 1 constructor with all nullable parameters and default values to null. Is there a better solution?


Solution

  • Since it is possible for Second and Third to have the value null by calling the constructors with fewer parameters, they are nullable, so you should mark them, and their corresponding parameters, as such. Change their type to string?:

    public class Foo
    {   
        public Foo(string first, string? second, string? third)
        {
            this.First = first; 
            this.Second = second;
            this.Third = third;
        }
    
        public Foo(string first, string? second) : this(first, second, null)
        {
    
        }
        public Foo(string first) : this(first, null)
        {
        }
        public string First { get; set; }
    
        public string? Second { get; set; }
    
        public string? Third { get; set; }
    }