Pergunta

I often use String.Format() because it makes the building of strings more readable and manageable.

Is there anyway to reduce its syntactical verbosity, e.g. with an extension method, etc.?

Logger.LogEntry(String.Format("text '{0}' registered", pair.IdCode));

public static void LogEntry(string message)
{
    ...
}

e.g. I would like to use all my and other methods that receive a string the way I use Console.Write(), e.g.:

Logger.LogEntry("text '{0}' registered", pair.IdCode);
Foi útil?

Solução

How about:

static void LogEntry(string format, params object[] args) {
    Console.WriteLine(format, args); // For example.
}

Now you can call it like this:

Logger.LogEntry("text '{0}' registered", pair.IdCode);

Outras dicas

If you control the Logger.LogEntry method, you can simply add an overload that encompasses the string.format. Just declare the second parameter as a paramarray and you are good to go!

Yes, you can make an extension method named FormatWith, which lets you say things like:

Logger.LogEntry("I hate my {0}".FormatWith(itemName));

It should be easy enough to roll your own, but here's an example: http://james.newtonking.com/archive/2008/03/27/formatwith-string-format-extension-method.aspx

If Logger.LogEntry is a static method outside of your control, then no; you can only add extension methods to instances. If it is your type, you could add:

public static void LogEntry(string format, params object[] args) {
    ... string.Format(format,args) ...
}

You could use the params keyword to combine all of the arguments after the first argument into an array and pass that array to String.Format.

static void FormatString(string myString, params string[] format)
{
     Console.WriteLine(String.Format(myString, format));
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top