1. Home
  2. Computing & Technology
  3. C / C++ / C#

C# Programming Tutorial - About Strings and Chars

By , About.com Guide

10 of 10

Formatted Strings in C#

The parameter placeholder {0}, {1} etc in Console.Write is handled by the string formatting. The placeholder has to have the index of the parameter but can also include formatting information.

This is used in Console.WriteLine and also string.format hence its inclusion here.

Layout of the PlaceHolder

The three parts are
index, alignment : format
So {0:X} (x means Hexadecimal) or {0,10} meaning output in a width of 10. The alignment value specifies teh width and left or right alignment by using - (left aligned) or + (right aligned) numbers. 10 Means right aligned in a width of 10, -6 means left aligned in a width of 6. Alignment is ignored if the output exceeds the width.

Download Example Ex6

This provides a large number of formatting examples.

List of Numeric Formats

  • C or C - For Currency. Uses the cultures currency symbol.
  • D or D - Integer types. Add a number for 0 padding eg D5.
  • E or e - Scientific notation.
  • F or f - Fixed Point.
  • G or g - Compact fixed-point/scientific notation.
  • N or n - Number. This can be enhanced by a NumberFormatInfo object.
  • P or p - Percentage.
  • R or r - Round-trip. Keeps exact digits when converted to string and back.
  • X or x - Hexadecimal. x - uses abcdef, X use ABCDEF.
Dates can also be specified either using Standard Format strings
  • O or o - YYYY-MM-dd:mm:ss:ffffffffzz
  • R or r - RFC1123 eg ddd, dd MMM yyyy HH:ss GMT
  • s - sortable . yyyy-MM-ddTHH:mm:ss
  • u - Universal Sort Date - yyyy-MM-dd HH:mm:ssZ
or Format specifiers. There are too many of those to list here - see example 6 for examples using them. I've commented the examples.

This concludes this tutorial. The next C# programming tutorial will be on Windows forms.

Explore C / C++ / C#
By Category
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C# / C Sharp
  5. Learn C Sharp
  6. Formatted Strings in C#

©2009 About.com, a part of The New York Times Company.

All rights reserved.