Thursday 30 June 2016

c# - Call one constructor from another



I have two constructors which feed values to readonly fields.



public class Sample
{

public Sample(string theIntAsString)
{
int i = int.Parse(theIntAsString);
_intField = i;
}

public Sample(int theInt) => _intField = theInt;
public int IntProperty => _intField;

private readonly int _intField;

}


One constructor receives the values directly, and the other does some calculation and obtains the values, then sets the fields.



Now here's the catch:




  1. I don't want to duplicate the
    setting code. In this case, just one

    field is set but of course there may
    well be more than one.

  2. To make the fields readonly, I need
    to set them from the constructor, so
    I can't "extract" the shared code to
    a utility function.

  3. I don't know how to call one
    constructor from another.




Any ideas?


Answer



Like this:



public Sample(string str) : this(int.Parse(str)) { }

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...