views:

341

answers:

3

I'm fairly new to C#, and trying to figure out string insertions (i.e. "some {0} string", toInsert), and ran across a problem I wasn't expecting...

In the case where you have two constructors:

public MyClass(String arg1) { ... }

public MyClass(String arg1, String arg2) { ... }

Is it possible for me to use the first constructor with a string insertion?

...
toInsert = "def"
myClass = new MyClass("abc{0}ghi", toInsert)
...

Or will C# interpret this as the second constructor and pass a literal "abc{0}ghi" as the first argument?

+9  A: 

Yes, this will be interpreted as just a second parameter.

The behavior you describe is called string formatting and everything that accepts strings in this style uses string.Format() in the background. See the documentation of that method for details.

To get the desired behavior, use this code:

myClass = new MyClass(string.Format("abc{0}ghi", toInsert));
Sander
Actually, String.Format() calls out to StringBuilder.AppendFormat()
Joel Coehoorn
So, should I always wrap my formatting in string.Format() to avoid bugs down the road where classes with one constructor get a new one?
tgray
No, that is an unjustified conclusion. new MyClass(A) calls the ctor that accepts one param, and new MyClass(A,B) calls the ctor that accepts 2 params, regardless what you substitute for A and B. You have substituted "abc{0}ghi" for A. This does not change the fact that you have passed 2 params.
Cheeso
@Cheeso, it sounds like you are confirming my supposition that, when using string formatting in an argument, the formatting should always be inside string.Format(), but my reason for doing so was wrong.
tgray
+4  A: 

Just do:

public MyClass(string format, params object[] args)
{
  this.FormattedValue = string.Format(format, args);
}
leppie
+2  A: 

Or will C# interpret this as the second constructor and pass a literal "abc{0}ghi" as the first argument?

This is the right answer. I think If you use String.Format("abc{0}ghi", toInsert) then it will take the first constructor

PoweRoy