Nestor Nestor - 1 month ago 9
C# Question

alternatives to string.Format(".... {0}....{1}....",v1,v2) in .net?

string.Format() with it's "bla {0} bla" syntax is great. But sometimes I don't want to enumerate the placeholders. Instead I just want to map the variables sequentially in the placeholders. Is there a library that can do that?

For instance, instead of

string.Format("string1={0}, string2={1}", v1, v2)


something like

string.Format("string1={*}, string2={*}", v1, v2)

Answer

You could accomplish this yourself by writing your own string extension coupled with the params keyword, assuming you're using .NET 3.5 or higher.

Edit: Got bored, the code is sloppy and error prone, but put this class in your project and using its namespace if necessary:

public static class StringExtensions
{
    public static string FormatEx(this string s, params string[] parameters)
    {
        Regex r = new Regex(Regex.Escape("{*}"));

        for (int i = 0; i < parameters.Length; i++)
        {
            s = r.Replace(s, parameters[i], 1);
        }

        return s;
    }
}

Usage:

Console.WriteLine("great new {*} function {*}".FormatEx("one", "two"));