C# – How to provide custom string placeholder for string format

.netc++stringstring-formatting

I have a string

string str ="Enter {0} patient name";

I am using string.format to format it.

String.Format(str, "Hello");

Now if i want patient also to be retrieved from some config then I need to change str to something like
"Enter {0} {1} name". So it will replace the {1} with second value. The problem is that I want instead of {1} some other format something like {pat}. But when I try to use, it throws an error. The reason I want a different format is that there are lot of files I need to change like this(which may contain {0},{1} etc). So I need a custom placeholder which can be replaced at run-time.

Best Solution

You might want to check out FormatWith 2.0 by James Newton-King. It allows you to use property names as formatting tokens such as this:

var user = new User()
{
    Name = "Olle Wobbla",
    Age = 25
};

Console.WriteLine("Your name is {Name} and your age is {Age}".FormatWith(user));

You can also use it with anonymous types.

UPDATE: There is also a similar solution by Scott Hanselman but it is implemented as a set of extension methods on Object instead of String.

UPDATE 2012: You can get Calrius Consulting's NETFx String.FormatWith Extension Method NuGet package on NuGet.org

UPDATE 2014: There is also StringFormat.NET and littlebit's StringFormat