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?
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 <"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With