String.Format(“Stuff {0} didn’t know”, _pronoun);

I’ve been doing a bit of code cleanup and refactoring lately, and as part of said refactoring, ended up replacing a lot of concatenated strings with String.Format(), I wasn’t sure where I picked up this String.Format() habit and why I do it, so naturally, I googled it and ended up at this enlightening SO article.

Other than improve readability, String.Format() has several advantages, few I did know and some impressive ones:

  • • 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 set padding easily: (">{0,3}<", "hi"); // ">hi <"
  • • allows you to trade a regular string to a dynamic string, consider: string greeting = "Hi {0}", name = "Lesego"; Console.WriteLine(greeting, name);
  • • allows you to specify formatting: ("The value will be {0:3N} (or {1:P}) on {2:MMMM yyyy gg}", x, y, theDate). Check out this impressive list of formatting options.

 

It’s not the most efficient and fastest way to put together several strings (according to this article), but it packs a whole lot of features and makes for readable and reusable code.

Write a Reply or Comment

Your email address will not be published.