CHAPTER 3 CORE C# PROGRAMMING CONSTRUCTS, PART I
static void GetUserData()
{
// Get name and age.
Console.Write("Please enter your name: ");
string userName = Console.ReadLine();
Console.Write("Please enter your age: ");
string userAge = Console.ReadLine();
// Change echo color, just for fun.
ConsoleColor prevColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Yellow;
// Echo to the console.
Console.WriteLine("Hello {0}!
userName, userAge);
}
You are {1} years old.",
// Restore previous color.
Console.ForegroundColor = prevColor;
Not surprisingly, when you run this application, the input data is printed to the console (using a
custom color to boot!).
Formatting Console Output
During these first few chapters, you might have noticed numerous occurrences of tokens such as {0} and
{1} embedded within various string literals. The .NET platform supports a style of string formatting
slightly akin to the printf() statement of C. Simply put, when you are defining a string literal that
contains segments of data whose value is not known until runtime, you are able to specify a placeholder
within the literal using this curly-bracket syntax. At runtime, the value(s) passed into
Console.WriteLine() are substituted for each placeholder.
The first parameter to WriteLine() represents a string literal that contains optional placeholders
designated by {0}, {1}, {2}, and so forth. Be very aware that the first ordinal number of a curly-bracket
placeholder always begins with 0. The remaining parameters to WriteLine() are simply the values to be
inserted into the respective placeholders.
Note If you have more uniquely numbered curly-bracket placeholders than fill arguments, you will receive a
format exception at runtime. However, if you have more fill arguments than placeholders, the unused fill
arguments are ignored.
It is permissible for a given placeholder to repeat within a given string. For example, if you are a
Beatles fan and want to build the string "9, Number 9, Number 9", you would write:
// John says...
Console.WriteLine("{0}, Number {0}, Number {0}", 9);
83