Constructor calling a constructor

R

Roger Webb

How do you go about calling a constructor in the same class from another
constructor? (see below)

- Roger

ie.

public class1()
{
Does some general initialization
}

public class1(string Thing1)
{
/// Call class1() for general initialization
/// set a property to Thing1
}
 
E

Eco

Hi,

This is how you do it:

public class1
{
public class1()
{
// Initialization code
}

public class1(string thing1) : this()
{
this._thing1 = thing1;
}

//...

}
 
V

Vagabond Software

Roger Webb said:
How do you go about calling a constructor in the same class from another
constructor? (see below)

- Roger

ie.

public class1()
{
Does some general initialization
}

public class1(string Thing1)
{
/// Call class1() for general initialization
/// set a property to Thing1
}

I believe you could do something like so:

public class1(string Thing1) : this ()
{
/// set properties
}

This is very useful for designing overloaded types.

- carl
 
P

Paul E Collins

Roger Webb said:
How do you go about calling a constructor in the
same class from another constructor?

Use the 'this' keyword (or 'base', to call the constructor of a base
class):

public Class1() { /* ... */ }
public Class1(string s) : this() { /* ... */ }

P.
 

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