Free mag vol1 | Page 151

CHAPTER 3  CORE C# PROGRAMMING CONSTRUCTS, PART I } // Notice that upper- or lowercasing for hex // determines if letters are upper- or lowercase. Console.WriteLine("E format: {0:E}", 99999); Console.WriteLine("e format: {0:e}", 99999); Console.WriteLine("X format: {0:X}", 99999); Console.WriteLine("x format: {0:x}", 99999); The following output shows the result of calling the FormatNumericalData() method. The value 99999 in various formats: c format: $99,999.00 d9 format: 000099999 f3 format: 99999.000 n format: 99,999.00 E format: 9.999900E+004 e format: 9.999900e+004 X format: 1869F x format: 1869f You’ll see additional formatting examples where required throughout this text; however, if you are interested in digging into .NET string formatting further, look up the topic “Formatting types” within the .NET Framework 4.5 SDK documentation.  Source Code The BasicConsoleIO project is located under the Chapter 3 subdirectory. Formatting Numerical Data Beyond Console Applications On a final note, be aware that the use of the .NET string formatting characters is not limited to console programs. This same formatting syntax can be used when calling the static string.Format() method. This can be helpful when you need to compose textual data at runtime for use in any application type (e.g., desktop GUI app, ASP.NET web app, and so forth). The string.Format() method returns a new string object, which is formatted according to the provided flags. After this point, you are free to use the textual data as you see fit. For example, assume you are building a graphical WPF desktop application and need to format a string for display in a message box. The following code illustrates how to do so, but be aware that this code will not compile until you reference the PresentationFramework.dll assembly for use by your project (see Chapter 2 for information on referencing libraries using Visual Studio). static void DisplayMessage() { // Using string.Format() to format a string literal. string userMessage = string.Format("100000 in hex is {0:x}", 100000); 85