Search code examples
c#constructornullmember

Why are my member variables null after construction?


I have a simple C# class constructor I'm running through a unit test. There are two members:

public class AnObject
{
    private Func<List<string>> function;
    private SHA256 sha256;

and a pair of nested constructors:

    public AnObject()
    {
        new AnObject(InternalFunction);
    }
    
    public AnObject(Func<List<string>> function)
    {
        this.function = function;
        this.sha256 = SHA256.Create();
    }

the first of which passes the function

    private List<string> InternalFunction()
    {
        return ...
    }
}

to the second.

While within the second constructor having been called from the first, the class members are being set correctly. When focus breaks back to the first constructor, both member variables revert to 'null'. Why?

Debugging unit test in Visual Studio Community 2022.


Solution

  • You are creating a new object in your parameterless constructor, not calling the other. Try this instead

    public AnObject() : this(InternalFunction)
    {
    
    }