Turning string.Format into an Extension Method
string.Format is the Bread and Butter function of every .Net developer, but somehow it feels a bit verbose. Here is a little extension method that allows you to do this:
string myTestString = "Hello {0}, Welcome to {1}, have a nice {2}!"; // Imagine this comes from a database or localized resource string uname = "Dave"; string facility = "Initrode"; string timeOfDay = "afternoon"; // "old" way lblWelcome.Text = string.Format(myTestString, uname, facility, timeOfDay); // "new" way lblWelcome.Text = myTestString.FormatString(uname, facility, timeOfDay); // It gracefully handles nulls as long as it's a string, it will return string.Empty on a null string string myNullString = null; lblWelcome.Text = myNullString.FormatString(uname, facility, timeOfDay); // Buzzword of 2009: Fluent Interface! lblWelcome.Text = myTestString.Replace("Hello","Howdy").FormatString(uname,facility,timeOfDay).Trim().Reverse();
Not really life changing, but it's one of those small things that just "feel" nicer/more fluent. Thanks to Kevin Dente for reminding me of string.Format again. I am using it every day and I always had it in the back of my head that I find it a bit "clunky". So here is the extension method:
public static class StringExtensionMethods { public static string FormatString(this String input, params object[] args) { if (input == null) return string.Empty; return string.Format(input, args); } }
Not Rocket Science, I know, but as said, even small things count if you just encounter them often enough 🙂
Thanks, I feel the same way about string.Format. Most of the time I find that I want to format a string and then I have to go back and add parens around it and so on. Feels like too much work. This seems so much simpler.