4

I have a constructor like:

public Blah(string a, string b)
{

}

public Blah(string a, string b, string c)
{
  this.a =a;
  this.b =b;
  this.c =c;
}

How can I call the 2nd constructor from the 1st one?

like:

public Blah(string a, string b)
{
   Blah(a,b, "");
}
1
  • 4
    BTW, that's generally referred to as constructor chaining. Commented Apr 15, 2010 at 15:29

4 Answers 4

9
public Blah(string a, string b) : this(a, b, "")
{
}

public Blah(string a, string b, string c)
{
    // etc
}
Sign up to request clarification or add additional context in comments.

5 Comments

It's better to use String.Empty instead of ""
@abatishchev: Do you have a reference for that? As far as I'm concerned it's just down to personal preference and what you find more readable. I prefer "".
"" (potentially) creates an object, String.empty doesn't.
@Anders: object.ReferenceEquals("", string.Empty) evaluates as true on my machine - ie, they're the same interned string object. (And even if that isn't always the case, I can live with one extra, tiny interned string per assembly.)
yep, has very little practical impact in most cases
5
public Blah(string a, string b): this(a, b, String.Empty)
{

}

public Blah(string a, string b, string c)
{
  this.a =a;
  this.b =b;
  this.c =c;
}

Comments

1
public Blah(string a, string b) : this(a,b, "default_C_String")
{ 

} 

--- whatever your desired default value is for C ...

Comments

-2

public Blah(string a, string b): this(a, b, String.Empty) {

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.