One Constructor Calling Another

M

Mike Labosh

Greetings, all:

I want to invoke one constructor from another to gain code reuse.

In the snip below, I want my second constructor to pass its first argument
to the first constructor so that the first constructor can set the Provider
property and invoke the resetConnection() method first, before the second
constructor assigns the connection string to the Connection property, but I
can't seem to work out the syntax.

public class DataProcessor {

// all unrelated code omitted.

public DataProcessor(DataProvider provider) {
Provider = provider;
resetConnection();
}

public DataProcessor(DataProvider provider, string connectionString) {
// this.DataProcessor(provider); <-- How do I do this?
Connection.ConnectionString = connectionString;
}
}
 
J

John M Deal

Without the comment you are actually pretty close. What you do is call
it like:

public class DataProcessor {

// all unrelated code omitted.

public DataProcessor(DataProvider provider) {
Provider = provider;
resetConnection();
}

public DataProcessor(DataProvider provider, string
connectionString) : this(provider) {
Connection.ConnectionString = connectionString;
}
}

Have A Better One!

John M Deal, MCP
Necessity Software
 
S

SpotNet

Hi Mike,

Constructors have their 'own special way' of calling or utilising each
other, from the same class,

public class DataProcessor {

// all unrelated code omitted. OK...
public DataProcessor(DataProvider provider)
{
Provider = provider;
resetConnection();
}

public DataProcessor(DataProvider provider, string connectionString) :
this(provider)//<--Do this
{
// this.DataProcessor(provider); <-- No you don't do this?
Connection.ConnectionString = connectionString;
}
}

When doing so keep in mind how overloading works and 'this(...)' will work
for the appropriate constructor. HTH.

Regards,
SpotNet.
 

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