Reputation: 99418
I heard that there is no need to use string.Format with a single placeholder.
For example, how can I change the following code accordingly, considering CultureInfo.InvariantCulture
,
string myString = string.Format(CultureInfo.InvariantCulture, "{0}", myMethod());
myMethod()
returns a string
object.
Btw, I modified some existing code like the following to have one place holder only
string myString = string.Format(CultureInfo.InvariantCulture, "{0}{1}", myMethod1(), myMethod2());
Thanks.
Upvotes: 0
Views: 2198
Reputation: 101473
To expand a bit on my comment. For each argument, String.Format
checks if object implements IFormattable
interface, which looks like this:
public interface IFormattable
{
string ToString(string format, IFormatProvider formatProvider);
}
If argument implements it - String.Format
will call that ToString
and pass your formatter there. Otherwise, it will call regular ToString
without providing formatter.
A lot of types (both .NET Framework and third party) implement this interface, such as all numeric types, date time and so on. If your myMethod()
returns type that implements IFormattable
- just call ToString
yourself (most such types for convenience also implement ToString
with one parameter, which is not part of IFormattable
interface):
myMethod().ToString(CultureInfo.InvariantCulture)
If type does not implement such interface - String.Format
will also do nothing useful for it (will not use formatter you passed) - so nothing is lost.
UPDATE: since your argument is string - there is no need to pass formatter to String.Format
and in your specific case use String.Format
at all. Formatter is used to convert object to string using specific rules, and string is well already a string.
In your old code there was multiple arguments, some of them might not be strings and then passing culture makes sense. Also someone might be on a safe side and decide to pass culture even if all arguments are strings, because who knows what will happen later - someone might add more arguments, or current arguments might change types, and of course when this happens no one will change String.Format
to accept invariant culture. So in general such approach does make sense.
However, when only one argument left and that is string - there is no sense any more for such complications - just remove String.Format
statement completely and replace with myMethod()
.
Upvotes: 3