One Constructor Calling Another

  • Thread starter Thread starter Mike Labosh
  • Start date Start date
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;
}
}
 
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
 
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.
 
Back
Top