Apr 24, 2013

Named String Format in C#

It is nice on how NET Framework gave a bunch of “shortcut” code, including String.Format. But we have to keep track of the indices in the object array which is not really nice.

82653205

It would be good if we just write code, declare a named string collection and format it.

  1. string format = "my name is [[name]] for it called [[name]] to be noted. and address is [[address]].";
  2. Hashtable ht = new Hashtable() { { "name", "Minion No. 10594" }, { "address", "gru's place" } };
  3. txtResult.Text = format.Format(ht);

Now we can use my commonly-used library in rdz.codeplex.com, and use the Format method in StringUtility class. You can download it and use it.

Don’t forget to add reference to Rdz.dll and put using directive as below. You are good to go and the Format function will be available on every string object, like in the example above.

  1. using Rdz.Utility;

In case you didn’t notice, the hashtable is case-sensitive. So to make it case-insensitive, declare Hashtable as below.

  1. Hashtable ht = new Hashtable(StringComparer.CurrentCultureIgnoreCase) { { "name", "Minion No. 10594" }, { "address", "gru's place" } };

Cool! See you! Winking smile