Constructors or properties

  • Thread starter Thread starter john sutor
  • Start date Start date
J

john sutor

Is it better to set a class's properties or to pass arguments to the class
initially in the constructor?
 
john sutor said:
Is it better to set a class's properties or to pass arguments to the class
initially in the constructor?

It depends - there are certainly times when it's nice to have a
parameterless constructor, but at other times it's often worth making
sure that by the time the constructor returns, the object is in a valid
state - and that will often mean you *have* to give parameters.

Also, if you give the parameters in the constructor you may be able to
make the object immutable (ie nothing changes its state) which is handy
for multithreading, parameter passing etc.
 
It depends on what you want to do. If you want to set the value once and not
try to set it again use the constructor. But if you want to change the value
of the field more than once, make the property settable.

HTH,
Martha
 
Is it better to set a class's properties or to pass arguments to the class
initially in the constructor?

The two concepts are not related. You pass arguments to the constructor when
you want to use that data to initialize your object. You set properties when
you want to change the current value of the property. One is not better than
the other.

Another thing constructors are good for is letting you know what the
*minimum* information for constructing an object is. For example, look at
this class:

class Person {
private string name;
private int age;

public Person(string name) {
this.name = name;
}

public Person(string name, int age) {
this.name = name;
this.age = age;
}

public string Name {
get {
return this.name;
}
}

public int Age {

get {
return this.age;
}

set {
this.age = value;
}
}
}

You can choose to construct a new Person passing both the name and age as
arguments to the constructor, or just the name. But in all cases you *must*
provide the name. You can set the age later, when you have the data
available or when it changes.

I hope that clears it up,
-JG
 
Back
Top