Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Class Constructors

Hi, I'm pacify and this is my first time posting.

Anyways, I have simple, class design type of question.

I'm reading up a little bit on C# programming. The book that I'm reading recommends creating constructors in the following way: "the root constructor should represent the constructor with the most parameters. This should then call the constructor with the next level of paramets setting any data not handled by that constructor itself"(Guide to C# and..... (http://www.amazon.com/gp/product/1852335815/104-1089590-5156748?v=glance&n=283155) )

The book goes on to talk about a constructor syntax:

ClassConstructor(<paramaters>) : this(person){
...
}

.....where ": this(person)" calls the next, most parameter encompassing constructor.

I do not understand the reasoning behind calling all the constructors in a class. It seems to me that some variables would be continously reinitialized as your progressed from the simplest, 0-parameter constructor, to the most parameter encompassing (most overloaded constructor).

Here is the example from the book:

using System;

public class Account{
private double balance = 0.0;
private String name= "";

Account(double amount, String person) : this(person){
balance = amount;
Console.WriteLine("(double amount, String person) constructor");
}

Account(String person) : this(){
name = person;
Console.WriteLine("(String person) constructor"));
}

Account(){
Console.WriteLine("Default Constructor");
}

public static void Main(){
Account acc = new Account(120.00, "J B");
}
}

---output -----
Default Constructor
(String person) constructor
(double amount, String person) constructor

Bottom line, what is the point of this?
[1980 byte] By [pacify] at [2007-11-11 8:37:48]
# 1 Re: Class Constructors
One reason -

If, when I created an object, I wanted to do something additional, I could make the change in one loacation and know it will be implimented regardless of which constructor is called. If I had made each of the constructors separate, then I'd have to make the change in each one, thus opening up the chance that I'd forget or mess one up...

using System;

public class Account{
private double balance = 0.0;
private String name= "";

Account(double amount, String person) : this(person){
balance = amount;
Console.WriteLine("(double amount, String person) constructor");
}

Account(String person) : this(){
name = person;
Console.WriteLine("(String person) constructor"));
}

Account(){
Console.WriteLine("Default Constructor");
// do something here and it happens regardless of which constructor I call...
Console.WriteLine("Doing something additional....");

}

public static void Main(){
Account acc = new Account(120.00, "J B");
}
}
Brad Jones at 2007-11-11 21:47:17 >