MrJD
MrJD

Reputation: 1889

String.Format certain argument

I would assume this is a common question but I couldn't seem to find anything on SO or google.

Is it possible to only format a single argument. For example, format string foo = "{0} is {1} when {2}"; so that it returns read "{0} is cray when {2}"?

Intentions:
I am trying to format the string while overriding a method before it gets formatted in it's base method

Success
Got it thanks to this answer, all answers were helpful :).

This unit test worked:

string foo = String.Format("{0} is {1} when {2}", "{0}", "cray", "{2}");
Assert.AreEqual("{0} is cray when {2}", foo);
string bar = string.Format(foo, "this", null, "it works");
Assert.AreEqual("this is cray when it works", bar);

Upvotes: 4

Views: 302

Answers (2)

Paul Bellora
Paul Bellora

Reputation: 55213

Taking your question at face value, I suppose you could do the following:

string foo = String.Format("{0} is {1} when {2}", "{0}", "cray", "{2}");

That is, simply replace each unevaluated format item with itself.

Upvotes: 6

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137398

No, this is not possible. String.Format is going to try and replace every bracketed placeholder. If you do not supply the correct number of arguments, an exception will be raised.

I'm not sure why you are trying to do this, but if you want the output to look like that, you'll have to escape the brackets:

var foo = String.Format("{{0}} is {0} when {{1}}", "cray");
// foo is "{0} is cray when {1}"

Perhaps if you tell us what exactly you're trying to do, we'll be able to better help you.

Upvotes: 2

Related Questions