Why are my member variables null after construction?

38 Views Asked by At

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.

2

There are 2 best solutions below

0
Mad hatter On BEST ANSWER

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

public AnObject() : this(InternalFunction)
{

}
0
MakePeaceGreatAgain On

because that's not how constructor-chaining works. Instead of chaining them together, you're effectivly creating a completely new instance of your type within your first constructor, that has nothing to do with the other instance.

Use this instead:

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