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
)
You can use a named string formatting solution, which may solve your problems.
Afraid not -- where would it put the objects into the string? Using printf, you still need to put specifiers in somewhere.
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.
There is a C# implementation of printf available here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With