Constructor calling a constructor

  • Thread starter Thread starter Roger Webb
  • Start date Start date
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
}
 
Hi,

This is how you do it:

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

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

//...

}
 
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
 
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.
 
Back
Top