How to call an empty constructor withing it's class

P

Pierre

Hi,

How do I call the 1st constructor in the second one (as this(); doesn't
work)? Or is it automatic?

public User(){
this._dtMngmt=new DataMngmt();
}

public User(String login, String password){
this();
this._login=login;
this._pwd=password;
}

Thank you for your answers.
 
S

Steve Walker

In message said:
Hi,

How do I call the 1st constructor in the second one (as this(); doesn't
work)? Or is it automatic?

public User(){
this._dtMngmt=new DataMngmt();
}

public User(String login, String password){
this();
this._login=login;
this._pwd=password;
}

Thank you for your answers.

public User(String login, String password):this()
{
this._login=login;
this._pwd=password;
}
 
H

Hans Kesting

Pierre said:
Hi,

How do I call the 1st constructor in the second one (as this();
doesn't work)? Or is it automatic?

public User(){
this._dtMngmt=new DataMngmt();
}

public User(String login, String password){
this();
this._login=login;
this._pwd=password;
}

Thank you for your answers.

it's not automatic. You can use:

public User(String login, String password) : this()
{
this._login=login;
this._pwd=password;
}

It's called *before* the rest of the code.

An other solution is to have all constructors call some private method
for the common initialisation.


Hans Kesting
 
F

Flip

The other's have it right, it's the
: this();
that is the key to calling the empty constructor.

I make that mistake all the time too. I'm coming from java where you have
to put the call to any constructor first. The C# way at least enforces you
not to do any object creation when the other constructor is called.
 
B

Bruce Wood

You should, in general, call your constructors in the opposite fashion:
the no-args constructor should call the other one with default values,
even if they're null:

public User() : this(null, null)
{ }

public User(string login, string password)
{
this._dtMngmt = new DataMngmt();
this._login = login;
this._password = password;
}

This is so that you never forget to initialize fields, and the default
values for the fields are explicitly written into your code, rather
than silently defaulting the way they did in your original code.
 
F

Flip

You should, in general, call your constructors in the opposite fashion:
I like this way, the only problem I find with VS2k3 is there is no
intellisense for arguments, especially when you're calling base methods. Is
this fixed in vs2k5? Or are you able to get the intellisense to work for
you in this case?

Thanks.
 

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