Search code examples
c#nullreferenceexceptionconstructor-overloading

How can I avoid NullReferenceException when overloading the constructor?


I made up an example in order to explain better my situation

void Main()
{
    var a = new Lol(null);
}

public class Lol
{
    public Lol(string a, string b)
    {
        if(a == null || b == null)
        {
            throw new Exception();
        }
    }

    public Lol(Tuple<string, string> k)
        : this(k.Item1, k.Item2)
    {
    }
}

In this case I'm getting a NullReferenceException in the second constructor. Is there a way to handle it from inside the method, keeping the same structure, or should I create a private method and have both constructor called this method?


Solution

  • You can abstract the logic into a helper method and have both constructors call the helper.

    public class Lol
    {
        public Lol(string a, string b)
        {
            LolHelper(a, b);
        }
    
        public Lol(Tuple<string, string> k)
        {
            (k!=null)
                ?LolHelper(k.Item1, k.Item2)
                :LolHelper(null, null);
        }
    
        private void LolHelper(string a, string b)
        {
            if(a == null || b == null)
            {
                throw new Exception();
            }
        }
    }