dearn44 dearn44 - 2 days ago 5
C# Question

Chaining constructors not updating variables as expected

I have created a class that looks similar to the one below. As you can see I created a few constructors that I am trying to chain using

: this()


class RTTutils
{
#region Variables

private bool verbose = false;
private bool canWrite = false;

private int x;
private int y;

public RTTutils()
{
x = 5;

y = 5;

RTTCalc();
}

public RTTutils(int samples, bool verbose) : this()
{
this.verbose = verbose;
this.samples = samples;
}

public RTTutils(int samples, bool verbose, bool canWrite) : this()
{
this.verbose = verbose;
this.samples = samples;
this.canWrite = canWrite;
}

public RTTutils(int samples) : this(samples, false, false)
{
}

public RTTutils(bool verbose) : this()
{
this.verbose = verbose;
}

private void RTTCalc()
{
if (this.verbose)
Console.WriteLine("Test");
}


I am trying to initialize it using

RTTutils rttcalculator = new RTTutils(true);


or any other combination for
verbose
and
canWrite
, they still remain
false
though. As an example in this case we will see nothing printed in the console, even though I indicated
true
when initializing the class.

What am I doing wrong in this case?

Answer

You expect (wrongly) boolean class fields used in method RTTCalc to have values you set in constructors with parameters. However, the parameterless constructor executes before these assignments.

Do not call RTTCalc in parameterless constructor. Provide static factory methods instead:

class RTTutils
{
    private bool verbose = false;
    private bool canWrite = false;

    private RTTutils()
    {
        sampleList.Add(100);    // First sample should be 100
        optionChosen.Add("E");

        x = 5;
        y = 5;

        System.IO.File.Delete(this.path);
    }

    private RTTutils(bool verbose) : this()
    {
        this.verbose = verbose;
    }

    private void RTTCalc()
    {
        if (this.verbose)
            Console.WriteLine("Test");
    }    

    public static RTTutils Create(bool verbose)
    {
      RTTutils result = new RTTutils(verbose);
      result.RTTCalc();
      return result;
    }
}
Comments