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


Just do:



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

      

+5


a source


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

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

+2


a source







All Articles