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:
Any ideas?
Constructor chaining can be done in two ways: Within same class: It can be done using this() keyword for constructors in the same class. From base class: by using super() keyword to call the constructor from the base class.
The invocation of one constructor from another constructor within the same class or different class is known as constructor chaining in Java. If we have to call a constructor within the same class, we use 'this' keyword and if we want to call it from another class we use the 'super' keyword.
Example 1: Java program to call one constructor from another Here, you have created two constructors inside the Main class. Inside the first constructor, we have used this keyword to call the second constructor. this(5, 2); Here, the second constructor is called from the first constructor by passing arguments 5 and 2.
To call one constructor from another constructor is called constructor chaining in java. This process can be implemented in two ways: Using this() keyword to call the current class constructor within the “same class”. Using super() keyword to call the superclass constructor from the “base class”.
Like this:
public Sample(string str) : this(int.Parse(str)) { }
If what you want can't be achieved satisfactorily without having the initialization in its own method (e.g. because you want to do too much before the initialization code, or wrap it in a try-finally, or whatever) you can have any or all constructors pass the readonly variables by reference to an initialization routine, which will then be able to manipulate them at will.
public class Sample { private readonly int _intField; public int IntProperty => _intField; private void setupStuff(ref int intField, int newValue) => intField = newValue; public Sample(string theIntAsString) { int i = int.Parse(theIntAsString); setupStuff(ref _intField,i); } public Sample(int theInt) => setupStuff(ref _intField, theInt); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With