Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# string formatting

Tags:

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?

like image 794
DarthVader Avatar asked Jun 11 '10 00:06

DarthVader


2 Answers

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 <"
like image 170
Mark Rushakoff Avatar answered Sep 24 '22 21:09

Mark Rushakoff


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.

like image 25
strager Avatar answered Sep 22 '22 21:09

strager