I m curious why would i use string formatting while i can use concatenation such as
Console.WriteLine(\"Hello {0} !\", name);
Console.WriteLine(\"Hello \"+
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 <"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.
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)
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:
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 + ".";