String.Format Extension Method

I have:

public static string Format(this string text, params object[] args) { return string.Format(text, args); } 

So, I can do:

 "blablabla {0}".Format(variable1); 

Is it good / bad? Could it get any shorter? I want the lines to be built smoothly, for example, writing text, without worrying before or after the parameters, etc.:

 // bad return "date: " + DateTime.Now.ToString("dd.MM.yyyy") + "\ntime: " + DateTime.Now.ToString("mm:HH:ss") + "\nuser: " + _user + " (" + _status + ")"; // better, but you have to deal with order of {0}...{n} and order of parameters return string.Format("date: {0}\ntime: {1}\user: {2} ({3})", ...); // ideal return "date: {DateTime.Now{dd:MM:yyyy}}\ntime: {...}\nuser: {_user} ({_status})"; 
+6
source share
4 answers

Well, one of the troubles is that only by having a single params object[] method do you forcibly add an extra array distribution per call.

You may notice that string.Format has a range of overloads for accepting a small number of arguments (they are very often used) - I would suggest duplicating them.

Your β€œideal” script can be executed by re-writing the string.Format method, but you will need to pass the values, i.e.

 return "date: {date}\ntime: {...}\nuser: {_user} ({_status})" .Format(new { date = DateTime.Now, _user, _status }); 

(and using your own native Format method or one like this one ), but note that this forces a new instance of the object per call.

Actually, at some point, the monocompiler had an experimental flag to enable this directly. I do not know if it is supported.

+3
source

This doesn't exactly match your ideal, but something like this might work for you:

 public static class Extensions { public static string Format(this object data, string format) { var values = new List<object>(); var type = data.GetType(); format = Regex.Replace(format, @"(^|[^{])\{([^{}]+)\}([^}]|$)", x => { var keyValues = Regex.Split(x.Groups[2].Value, "^([^:]+):?(.*)$") .Where(y => !string.IsNullOrEmpty(y)); var key = keyValues.ElementAt(0); var valueFormat = keyValues.Count() > 1 ? ":" + keyValues.ElementAt(1) : string.Empty; var value = GetValue(key, data, type); values.Add(value); return string.Format("{0}{{{1}{2}}}{3}", x.Groups[1].Value, values.Count - 1, valueFormat, x.Groups[3].Value); }); return string.Format(format, values.ToArray()); } private static object GetValue(string name, object data, Type type) { var info = type.GetProperty(name); return info.GetValue(data, new object[0]); } } 

This should allow you to do this formatting on any object:

 new {Person = "Me", Location = "On holiday"} .Format("{Person} is currently {Location}"); 

It will also allow you to add formatting:

 new {Person = "Me", Until = new DateTime(2013,8,1)} .Format("{Person} is away until {Until:yyyy-MM-dd}); 

How is that for you? I'm sure the code can be improved in terms of efficiency, but it works!

+3
source

I also use a similar extension method, and I like it, I also indicate the culture information in the extension method, which is fixed for the system in my case.

 public static string Format(this string formatTemplate, params object[] args) { return string.Format(SysSettings.CultureInfo, formatTemplate, args); } 

Customs:

 return "date: {0:dd.MM.yyyy}\ntime: {1:mm:HH:ss}\nuser: {2} ({3})".Format(DateTime.Now, DateTime.Now, _user, _status); 
+2
source

It depends on whether you code yourself or have a command. In a team, this is a pretty bad idea, as everyone will have to learn this method.

Another problem is the format with arguments in strings that randomly contain curly braces with the wrong index, for example {1} rather than {2}. Thus, only a bad line will cause the entire application to crash. I used something similar for my logging and had to use try-catch for FormatExceptions.

+1
source

Source: https://habr.com/ru/post/949302/


All Articles