If the same val is used to replace two separate string.Format placeholders, must it be provided twice?
Asked Answered
I

2

5

Given this:

string msg = string.Format("Duckbill {0} Platypus has not been loaded. Fetch Duckbill {1}'s Platypus then continue.", userDuckbill, userDuckbill);

...would it suffice to do this instead:

string msg = string.Format("Duckbill {0} Platypus has not been loaded. Fetch Duckbill {1}'s Platypus then continue.", userDuckbill);

?

Ijssel answered 12/4, 2013 at 16:32 Comment(6)
A moment of testing would have saved you a couple of moments on stackoverflow. It really would be easier to test than to ask in this case.Wasp
Not in my case; it takes several minutes to test the simplest thing.Ijssel
I recommend linqpad.netWasp
I've got Linqpad, but I'd either forgotten or didn't know that it worked with non-LINQ stuff.Ijssel
With this in LINQPad: MessageBox.Show("This is {0}", "this"); ...and "C# Statement[s]" selected, when I mash the Green Arrow [!TM], I get, "The name 'MessageBox' does not exist in the current context"Ijssel
You've got a good point, though - I tried to give myself a thumb's down, but it won't let me do that. The reason for my failed attempt at self-flagellation: I should have fired up VS2010 to test it out, even though with the project I'm working on I've got to use VS1903 (well, VS2003, but it's effectually the same thing).Ijssel
P
23

You can specify a parameter any number of times. Use this instead:

string msg = string.Format("Duckbill {0} Platypus has not been loaded. Fetch Duckbill {0}'s Platypus then continue.", userDuckbill);

The official documentation has several examples like this. Here's just one:

  string formatString = "    {0,10} ({0,8:X8})\n" + 
                        "And {1,10} ({1,8:X8})\n" + 
                        "  = {2,10} ({2,8:X8})";
  int value1 = 16932;
  int value2 = 15421;
  string result = String.Format(formatString, value1, value2, value1 & value2);
Pritchett answered 12/4, 2013 at 16:33 Comment(0)
K
4

Use {0} twice:

string msg = string.Format(
    "Duckbill {0} Platypus has not been loaded. Fetch Duckbill {0}'s Platypus then continue.",
    userDuckbill);

Your second code sample would result in a FormatException with the following message:

Index (zero based) must be greater than or equal to zero and less than the size of the argument list.

So, whenever you use {n}, you must have at least n parameters after your format string. Having more than n would be useless however.

Kristykristyn answered 12/4, 2013 at 16:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.