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);
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With