Constructor Chaining in C#: A Solution for Readonly Field Initialization
Sometimes, you need to initialize readonly
fields using multiple constructors. Since readonly
fields can only be assigned values within a constructor, simply duplicating initialization logic across constructors is inefficient and error-prone. C# offers a clean solution: constructor chaining.
The Power of this
Constructor chaining leverages the this
keyword to call one constructor from another. This redirects the initialization process, eliminating redundant code.
Here's an example:
<code class="language-csharp">public class Sample { public Sample(string theIntAsString) : this(int.Parse(theIntAsString)) { } public Sample(int theInt) => _intField = theInt; public int IntProperty => _intField; private readonly int _intField; }</code>
This Sample
class demonstrates two constructors. The first constructor takes a string, parses it into an integer, and then chains to the second constructor, passing the parsed integer. The second constructor directly initializes the readonly
field. This approach keeps the initialization logic centralized while providing flexibility in how the class is instantiated.
Using constructor chaining promotes cleaner, more maintainable code by avoiding duplicated initialization logic, thereby improving code reusability and reducing the risk of inconsistencies.
The above is the detailed content of How Can I Call One Constructor from Another in C# to Initialize Readonly Fields?. For more information, please follow other related articles on the PHP Chinese website!