Problem
I know this is meant to be an easy question, but I’ve been having trouble grasping the concept for quite some time.
How do you link constructors in C#, is my question?
I’m in my first OOP class, so I’m still figuring things out. I’m not sure how constructor chaining works, how to implement it, or why it’s better than doing constructors one at a time.
I’d want to see several instances with explanations.
So, what’s the best way to link them all together? I’m sure it goes like this with two:
public SomeClass this: {0}
public SomeClass
{
someVariable = 0
}
But what if there are three, four, and so on?
Again, I realize this is a basic question, but I’m having trouble understanding it for some reason.
Asked by Alex
Solution #1
Within the class, you select the overload using standard syntax (as if it were a method):
class Foo
{
private int id;
private string name;
public Foo() : this(0, "")
{
}
public Foo(int id, string name)
{
this.id = id;
this.name = name;
}
public Foo(int id) : this(id, "")
{
}
public Foo(string name) : this(0, name)
{
}
}
then:
Foo a = new Foo(), b = new Foo(456,"def"), c = new Foo(123), d = new Foo("abc");
Note also:
For “why?”:
However, object initializers can be used in a similar way (without having to write anything):
SomeType x = new SomeType(), y = new SomeType { Key = "abc" },
z = new SomeType { DoB = DateTime.Today };
Answered by Marc Gravell
Solution #2
I just want to make a valid point to anyone looking for this information. Please be aware that you must establish constructor chains as described above if you are working with.NET versions prior to 4.0 (VS2010).
If you want to stay in 4.0, though, I have some excellent news for you. It’s now possible to have a single constructor with optional arguments! I’ll make the Foo class example simple:
class Foo {
private int id;
private string name;
public Foo(int id = 0, string name = "") {
this.id = id;
this.name = name;
}
}
class Main() {
// Foo Int:
Foo myFooOne = new Foo(12);
// Foo String:
Foo myFooTwo = new Foo(name:"Timothy");
// Foo Both:
Foo myFooThree = new Foo(13, name:"Monkey");
}
Because defaults have been defined, you can use the optional arguments while implementing the constructor.
I hope you had a good time with this lesson! I can’t believe developers have been whining about construct chaining and the lack of ability to use default optional arguments since 2004/2005! It has now taken so long in the development industry that developers are hesitant to use it since it would be incompatible with previous versions.
Answered by ES3178
Solution #3
An example is the greatest way to demonstrate this. Assume we have a person of distinction.
public Person(string name) : this(name, string.Empty)
{
}
public Person(string name, string address) : this(name, address, string.Empty)
{
}
public Person(string name, string address, string postcode)
{
this.Name = name;
this.Address = address;
this.Postcode = postcode;
}
So we’ve got a constructor that sets some properties and uses constructor chaining to let you build the object with just a name or just a name and address. If you create an instance with only a name, the default value will be string. Empty is sent through to the name and address, which passes a default value for Postcode to the final constructor.
You’re lowering the amount of code you’ve written in the process. You’re not repeating yourself since only one constructor contains code in it; for example, if you change Name from a property to an internal field, you only need to modify one constructor; if you set that property in all three constructors, you’d have to change it three times.
Answered by blowdart
Solution #4
What does “Constructor Chain” mean? It’s used to invoke a constructor from another constructor.
How can “Constructor Chain” be implemented? After the constructor is defined, use the keyword “: this (yourProperties)”. as an example:
Class MyBillClass
{
private DateTime requestDate;
private int requestCount;
public MyBillClass()
{
/// ===== we naming "a" constructor ===== ///
requestDate = DateTime.Now;
}
public MyBillClass(int inputCount) : this()
{
/// ===== we naming "b" constructor ===== ///
/// ===== This method is "Chained Method" ===== ///
this.requestCount= inputCount;
}
}
What is the benefit of it? The main reason is to minimize coding and avoid duplicate code. such as duplicate code for property initialization Assume that a class property must be initialized with a certain value (In our sample, requestDate). There are two or more constructors in a class. You must repeat initialization code in all constractors of the class if you don’t use “Constructor Chain.”
So, how does it work? (Or, What is the “Constructor Chain” execution sequence?) In the preceding example, method “a” will be executed first, followed by the return of the instruction sequence to method “b.” In other words, the aforementioned code is the same as the following:
Class MyBillClass
{
private DateTime requestDate;
private int requestCount;
public MyBillClass()
{
/// ===== we naming "a" constructor ===== ///
requestDate = DateTime.Now;
}
public MyBillClass(int inputCount) : this()
{
/// ===== we naming "b" constructor ===== ///
// ===== This method is "Chained Method" ===== ///
/// *** --- > Compiler execute "MyBillClass()" first, And then continue instruction sequence from here
this.requestCount= inputCount;
}
}
Answered by M.i.T
Solution #5
I’m in a diary class, so I’m not writing down the values again and over.
public Diary() {
this.Like = defaultLike;
this.Dislike = defaultDislike;
}
public Diary(string title, string diary): this()
{
this.Title = title;
this.DiaryText = diary;
}
public Diary(string title, string diary, string category): this(title, diary) {
this.Category = category;
}
public Diary(int id, string title, string diary, string category)
: this(title, diary, category)
{
this.DiaryID = id;
}
Answered by Jhankar Mahbub
Post is based on https://stackoverflow.com/questions/1814953/how-to-do-constructor-chaining-in-c-sharp