How to call an empty constructor withing it's class

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