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?
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?
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.
It depends: http://geekswithblogs.net/BlackRabbitCoder/archive/2010/05/10/c-string-compares-and-concatenations.aspx
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.
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.
You picked too simple of an example.
String formatting:
("{0} + {0} = {1}", x, 2*x)
ToString
on its arguments: ("{0}: {1}", someKeyObj, someValueObj)
("The value will be {0:3N} (or {1:P}) on {2:MMMM yyyy gg}", x, y, theDate)
(">{0,3}<", "hi"); // ">hi <"
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.
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 + ".";
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)
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.
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.
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: