Call another constructor within a constructor
In a class, the constructor is used to initialize fields when the object is created. In some cases, multiple constructors may provide values to read-only fields. Consider the following class:
<code class="language-c#">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; }</code>
There are two constructors here. However, the problem arises when you want to avoid duplicating field setup code, since read-only fields need to be initialized in the constructor.
Fortunately, there is a solution: use constructor chaining. By adding the following line in the string argument constructor:
<code class="language-c#">public Sample(string str) : this(int.Parse(str)) { }</code>
You can call the integer parameter constructor from the string parameter constructor. This delegates field initialization to existing code, eliminating the need for duplication.
The above is the detailed content of How Can I Avoid Code Duplication When Initializing Readonly Fields in Multiple Constructors?. For more information, please follow other related articles on the PHP Chinese website!