C # string inserts confuse with optional parameters
I am new to C # and am trying to figure out string inserts (i.e. "some {0} string", toInsert
) and ran into a problem that I did not expect ...
In case you have two constructors:
public MyClass(String arg1) { ... }
public MyClass(String arg1, String arg2) { ... }
Can I use the first insert row constructor?
...
toInsert = "def"
myClass = new MyClass("abc{0}ghi", toInsert)
...
Or will C # interpret this as a second constructor and pass a literal as the first argument "abc{0}ghi"
?
0
a source to share
3 answers
Yes, it will be interpreted as just the second parameter.
The behavior you're describing is called string formatting, and anything that accepts strings in this style uses string.Format () in the background. See the documentation for this method for details.
To get the desired behavior use this code:
myClass = new MyClass(string.Format("abc{0}ghi", toInsert));
+9
a source to share