Introduction
I think I'm not the only one who has always had trouble when it comes to using String.Format()
. I never had a clear understanding about the meaning of its interpunction: """, "", ",", ":", "#", "-", ";" - but finally, I got it. :-)
The Topic: String.Format()
String.Format()
accepts a formatstring
and a list (of arbitrary length) with arguments, to which the format is to apply. Within the formatstring
, there can be arbitrary text, and there are embedded placeholders, marked up with {}
, where the formatted arguments get inserted. For example:
Dim s = String.Format("Now it's {0,-20:hh:mm} - hurry up!", Date.Now)
This tips topic is the formatting-instructions within those Placeholders - only in general.
For detailed information, especially the particular type-depending instruction-syntax, refer to the MSDN-documentation - see links below.
The Three Instruction-sections Within a formatstring-placeholder
Within a formatstring-Placeholder, there are 3 sections. The first section is required, the others are optional. The second section is separated by ",
", and the third is separated by ":
".
Meanings of the Three Sections
- The zero-based Index of the aimed argument in the further argument-list: required
- "
,
" (if present) separates a section to define width and alignment of the inserted formatted value-string.
In the sample above a width of 20 chars is defined, and the "-
" defines left alignment (Default-alignment is right).
- "
:
" (if present) separates a section to define a particular type-depending Formatting-syntax, which is well-documented on MSDN.
In the sample above DateTime
-depending syntax defines an output of hours and minutes, separated by ":
"
The confusion is that the latter two sections are optional, and moreover the inner syntax of the third section changes from type to type, and moreover it may as well use ",
" or ":
", so that especially these two ControlChars
can have different meanings within the same formatstring.
But once understood that their first occurrence within the placeholder is as Separator, the confusion hopefully vanishes. :-)
Some Links to MSDN-Documentation
Points of Interest