Monday 26 November 2012

c# for dummies

String.Format and composite format strings




The static Format method provides a convenient way  to build strings  that embed
variables.  The  embedded  variables  can  be  of  any  type;  the  Format  simply  calls
ToString on them.
The master string that includes the embedded variables is called a composite format
string. When calling String.Format, you provide a composite format string followed
by each of the embedded variables. For example:
string composite = "It's {0} degrees in {1} on this {2} morning";
string s = string.Format (composite, 35, "Perth", DateTime.Now.DayOfWeek);
// s == "It's 35 degrees in Perth on this Friday morning"
(And that’s Celsius!)
Each number in curly braces is called a format item. The number corresponds to the
argument position and is optionally followed by:


• A comma and a minimum width to apply
• A colon and a format string
The minimum width is useful for aligning columns. If the value is negative, th
is left-aligned; otherwise, it’s right-aligned. For example:
string composite = "Name={0,-20} Credit Limit={1,15:C}";
Console.WriteLine (string.Format (composite, "Mary", 500));
Console.WriteLine (string.Format (composite, "Elizabeth", 20000));
Here’s the result:
Name=Mary                 Credit Limit=        $500.00
Name=Elizabeth            Credit Limit=     $20,000.00
The equivalent without using string.Format is this:
string s = "Name=" + "Mary".PadRight (20) +
           " Credit Limit=" + 500.ToString ("C").PadLeft (15);

No comments:

Post a Comment