Home > Backend Development > C++ > How Can I Avoid Code Duplication When Initializing Readonly Fields in Multiple Constructors?

How Can I Avoid Code Duplication When Initializing Readonly Fields in Multiple Constructors?

DDD
Release: 2025-01-12 11:46:41
Original
617 people have browsed it

How Can I Avoid Code Duplication When Initializing Readonly Fields in Multiple Constructors?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template