Search code examples
c#stringstring-formatting

Can maximum number of characters be defined in C# format strings like in C printf?


Didn't find how to do that. What I found was more or less on the lines of this (http://blog.stevex.net/string-formatting-in-csharp/):

There really isn’t any formatting within a string, beyond it’s alignment. Alignment works for any argument being printed in a String.Format call. Sample Generates

String.Format(“->{1,10}<-”, “Hello”);  // gives "->     Hello<-" (left padded to 10)
String.Format(“->{1,-10}<-”, “Hello”); // gives "->Hello     <-" (right padded to 10)

Solution

  • What you want is not "natively" supported by C# string formatting, as the String.ToString methods of the string object just return the string itself.

    When you call

    string.Format("{0:xxx}",someobject);
    

    if someobject implements the IFormattable interface, the overload ToString(string format,IFormatProvider formatProvider) method gets called, with "xxx" as format parameter.

    So, at most, this is not a flaw in the design of .NET string formatting, but just a lack of functionality in the string class.

    If you really need this, you can use any of the suggested workarounds, or create your own class implementing IFormattable interface.