Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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 objet in your parameterless constructor, not calling the other. Try this instead

public AnObject() : this(InternalFunction)
{

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading