views:

231

answers:

11

I m curious why would i use string formatting while i can use concatenation such as

Console.WriteLine("Hello {0} !", name);

Console.WriteLine("Hello "+ name + " !");

Why to prefer the first one over second?

+2  A: 

String formatting allows you to keep the format string separate, and use it where it's needed properly without having to worry about concatenation.

string greeting = "Hello {0}!";
Console.WriteLine(greeting, name);

As for why you would use it in the exact example you gave... force of habit, really.

Ignacio Vazquez-Abrams
In exceptional circumstances, also for performance/resource concerns. `string.format` uses StringBuilder, which is well-known to be an improvement over many concatenations.
Rex M
same again, i can have a equivalent statement, that i can do with concatenation. But mentioning the performance is a plus i guess.
Until you try to translate the greeting. Then concatenation falls on its keister.
Ignacio Vazquez-Abrams
+6  A: 

You can trade the string for a dynamic string later.

For example:

// In a land far, far away
string nameFormat = "{0} {1}";

// In our function
string firstName = "John";
string lastName = "Doe";

Console.WriteLine(nameFormat, firstName, lastName);

Here, you can change nameFormat to e.g. "{1}, {0}" and you don't need to change any of your other code. With concatination, you would need to edit your code or possibly duplicate your code to handle both cases.

This is useful in localization/internationalization.

strager
+1  A: 

You are using a trivial example where there is not much of a difference. However, if you have a long string with many parameters it is much nicer to be able to use a format string instead of many, many + signs and line breaks.

It also allows you to format numerical data as you wish, i.e., currency, dates, etc.

Ed Swangren
+20  A: 

You picked too simple of an example.

String formatting:

  • allows you to use the same variable multiple times: ("{0} + {0} = {1}", x, 2*x)
  • automatically calls ToString on its arguments: ("{0}: {1}", someKeyObj, someValueObj)
  • allows you to specify formatting: ("The value will be {0:3N} (or {1:P}) on {2:MMMM yyyy gg}", x, y, theDate)
  • allows you to set padding easily: (">{0,3}<", "hi"); // ">hi <"
Mark Rushakoff
Nice, I didn't know you could use formatting strings, too.
Mathias
+1 great answer, very complete
Claudio Redi
Wow, I didn't even consider all that. (I have, however, used most of those features.) +1
strager
+1  A: 

The first format is recommended. It allows you to specify specific formats for other types, like displaying a hex value, or displaying some specific string format.

e.g.

string displayInHex = String.Format("{0,10:X}", value); // to display in hex

It is also more consistent. You can use the same convention to display your Debug statement. e.g.

Debug.WriteLine (String.Format("{0,10:X}", value));

Last but not least, it helps in the localisation of your program.

Syd
+1  A: 

In addition to reasons like Ignacio's, many (including me) find String.Format-based code much easier to read and alter.

string x = String.Format(
  "This file was last modified on {0} at {1} by {2}, and was last backed up {3}."
  date, time, user, backupDate);

vs.

string x = "This file was last modified on " + date + " at "
+ time + " by " + user + " and was last backed up " + backupDate + ".";
Michael Petrotta
+2  A: 

I think a good example is about i18n and l10n

If you have to change a string between different languages, this: "bla "+variable+"bla bla.." Will give problems to a program used to create sobstitution for your strings if you use a different language

while in this way: "bla {0} blabla" is easily convertible (you will get {0} as part of the string)

Fire-Dragon-DoL
+1  A: 

I have found the former approach (using string.format) very useful when overriding ToString() methods in Entity classes.

For example, in my Product class;

public override string ToString()
{
    return string.format("{0} : {1} ({2} / {3} / {4}",
                              this.id,
                              this.description,
                              this.brand,
                              this.model);
}

Then, when users decide they want the product to appear differently it's easy to change the order/contents or layout of the string that is returned.

Of course you still concatentate this string together but I feel string.Format makes the whole thing a bit more readable and maintainable.

I guess that's the short answer I'm giving then isn't it - readability and maintainability for lengthy or complex strings.

Stuart Helwig
+2  A: 

There isn't a singular correct answer to this question. There are a few issues you want to address:

Performance

The performance differences in your examples (and in real apps) are minimal. If you start writing MANY concatenations, you will gradually see better memory performance with the formatted string. Refer to Ben's answer

Readability

You will be better off with a formatted string when you have formatting, or have many different variables to stringify:

string formatString = "Hello {0}, today is {1:yyyy-MM-dd}";
Console.WriteLine(formatString, userName, Date.Today);

Extensibility

Your situation will determine what's best. You tell me which is better when you need to add an item between Username and Time in the log:

Console.WriteLine(
   @"Error! 
    Username: " + userName + "
    Time: " + time.ToString("HH:mm:ss") + "
    Function: " + functionName + "
    Action: " + actionName + "
    status: " + status + "
   ---");

or

Console.WriteLine(@"Error! 
    Username: {0}
    Time: {1}
    Function: {2}
    Action: {3}
    status: {4}
   ---",
    username, time.ToString("HH:mm:ss"), functionName, actionName, status);

Conclusion

I would choose the formatted string most of the time... But I wouldn't hesitate at all to use concatenation when it was easier.

Jeff Meatball Yang
Very comprehensive answer. +1
Syd
+1  A: 

Formatting is usually preferred for most of the reasons explained by other members here. There are couple more reasons I want to throw in from my short programming experience:

  • Formatting will help in generating Culture aware strings.
  • Formatting is more performant than concatenation. Remember, every concatenation operation will involve creation of temporary intermediate strings. If you have a bunch of strings you need to concatenate, you are better off using String.Join or StringBuilder.
ponnu