Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass parameters to String.Format without specifying numbers?

Is there a way to String.Format a message without having to specify {1}, {2}, etc? Is it possible to have some form of auto-increment? (Similar to plain old printf)

like image 626
Hosam Aly Avatar asked Feb 18 '09 13:02

Hosam Aly


4 Answers

You can use a named string formatting solution, which may solve your problems.

like image 101
cbp Avatar answered Sep 30 '22 03:09

cbp


Afraid not -- where would it put the objects into the string? Using printf, you still need to put specifiers in somewhere.

like image 41
mqp Avatar answered Sep 30 '22 03:09

mqp


I think the best way would be passing the property names instead of Numbers. use this Method:

using System.Text.RegularExpressions;
using System.ComponentModel;

public static string StringWithParameter(string format, object args)
    {
        Regex r = new Regex(@"\{([A-Za-z0-9_]+)\}");

        MatchCollection m = r.Matches(format);

        var properties = TypeDescriptor.GetProperties(args);

        foreach (Match item in m)
        {
            try
            {
                string propertyName = item.Groups[1].Value;
                format = format.Replace(item.Value, properties[propertyName].GetValue(args).ToString());
            }
            catch
            {
                throw new FormatException("The string format is not valid");
            }
        }

        return format;
    }

Imagine you have a Student Class with properties like: Name, LastName, BirthDateYear and use it like:

 Student S = new Student("Peter", "Griffin", 1960);
 string str =  StringWithParameter("{Name} {LastName} Born in {BithDate} Passed 4th grade", S);

and you'll get: Peter Griffin born in 1960 passed 4th grade.

like image 42
Ashkan Ghodrat Avatar answered Sep 30 '22 02:09

Ashkan Ghodrat


There is a C# implementation of printf available here

like image 41
Rune Grimstad Avatar answered Sep 30 '22 02:09

Rune Grimstad