Constructor Question

G

Greg

Hi,

I have a class that has 3 different constructors in it. In the base
constructor I want to have it set some default data. I don't want to
have the overloaded constructors do these same operations (event to
the extent of creating a function that each constructor calls).

Is it possible to ensure that the base constructor always gets called
when one of the overloaded constructors gets called?

i.e.

public myclass {

public myclass() {

//Set something
}

public myclass(string input) {

//Do some other stuff while knowing that the first constructor has
already executed.
}

Is this the only way to do this to create the first constructor as a
base class on it's own and inherit the constructor from it?

Thanks - Greg.

}
 
J

Jon Skeet [C# MVP]

Greg said:
I have a class that has 3 different constructors in it. In the base
constructor I want to have it set some default data. I don't want to
have the overloaded constructors do these same operations (event to
the extent of creating a function that each constructor calls).

Is it possible to ensure that the base constructor always gets called
when one of the overloaded constructors gets called?

Just to clarify, I don't think you actually mean a "base constructor"
(which sounds like the constructor of a base class) as a parameterless
constructor in the same class.

In that case, you use

public void MyClass (... parameters ...)
: this() // calls parameterless constructor
{
// etc
}

See http://pobox.com/~skeet/csharp/constructors.html

(Note that constructors aren't actually inherited, btw.)
 
N

Nicholas Paldino [.NET/C# MVP]

Greg,

Well, you could always use "this":

public myclass(string input) : this()
{
}

Although a cleaner approach (IMO) would be to reverse the process, have
one overload that takes all the possible input for the class, then have the
constructors with the more restrictive parameter list call the constructors
with the less restrictive parameter list with the default values:

public myclass() : this("default value")
{ }

public myclass(string input)
{
// Perfrom all assignments here.
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top