Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

?

like image 608
B. Clay Shannon-B. Crow Raven Avatar asked Apr 12 '13 16:04

B. Clay Shannon-B. Crow Raven


2 Answers

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);
like image 131
p.s.w.g Avatar answered Nov 12 '22 01:11

p.s.w.g


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.

like image 35
Thorarin Avatar answered Nov 12 '22 03:11

Thorarin