Home >Backend Development >C++ >How Can I Call One Constructor from Another in C# to Avoid Code Duplication?
Call another constructor in C#
When dealing with constructors that initialize read-only fields, it is desirable to avoid duplication of logic. Additionally, setting read-only fields only within the constructor ensures data integrity. However, constructors cannot directly call other constructors.
Solution: Method chain calling
To overcome this limitation, method chaining can be used. In C#, this involves calling a new constructor with parameters from an existing constructor. This syntax allows you to initialize multiple fields while centralizing your setup logic:
<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>
You can delegate field initialization to a constructor that takes an integer argument by calling it from a constructor that takes a string argument. This eliminates code duplication and ensures consistent field settings.
The above is the detailed content of How Can I Call One Constructor from Another in C# to Avoid Code Duplication?. For more information, please follow other related articles on the PHP Chinese website!