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

StackOverflow https://stackoverflow.com/questions/15976517

  •  03-04-2022
  •  | 
  •  

Question

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);

?

Was it helpful?

Solution

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);

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top