Introduction to the Console

Overview

To allow you to display simple values on the monitor's screen, the .NET Framework provides a static class named Console.

Practical LearningPractical Learning: Introducing the Console

  1. Launch Microsoft Visual Studio. On the Visual Studio 2022 dialog box, click Create a New Project
  2. Make sure C# is selected. In the list of project templates, click Empty Project (.NET Framework)
  3. Click Next
  4. Change the project Name to GeorgetownDryCleaningServices4 and accept or change the project Location
  5. Click Create
  6. On the main menu, click Project -> Add New Item...
  7. In the left list of the Add New Item dialog box, click Code and, in the middle list, click Code File
  8. Change the file Name to CleaningOrderProcessing
  9. Click Add

Starting Console Code

The Console class is defined in the System namespace. Therefore, to use it in your application, in your code, you can type System followed by a period. If you are using the code Editor in Microsoft Visual Studio to create your application, its Intellisense would display the available classes of that namespace.

The System namespace is part of the mscorlib.dll library. When you create a C# application, the mscorlib.dll library is directly available; which means you don't have to import it. Since the Console class is static, you never have to declare a variable of it in order to use it. Therefore, to access the Console class in your code, after typing System and a period, type Console. To access a member of this class, type a period after its name.

Writing to the Console

To provide the ability to display one or more values to the screen, the Console class is equipped with a method named Write. To use the Write() method, inside its parentheses, type the value you want to display. Here is an example:

System.Console.Write("The Wonderful World of C# Programming");

To be able to handle any value of the data types we have used so far, the Write() method is overloaded with various versions. There is a version for each data type. The syntaxes are:

public static void Write(int value);
public static void Write(uint value);
public static void Write(string value);
public static void Write(long value);
public static void Write(ulong value);
public static void Write(float value);
public static void Write(double value);
public static void Write(decimal value);
public static void Write(object value);

Writing With a New Line

After displaying a value on the screen, the Write() method keeps the caret on the same line. To give you the ability to move the caret to the next line after displaying a value, the Console class is equipped with a method named WriteLine. Like Write(), the WriteLine() method has a version for each of the data types we have used so far:

public static void WriteLine(int value);
public static void WriteLine(uint value);
public static void WriteLine(string value);
public static void WriteLine(long value);
public static void WriteLine(ulong value);
public static void WriteLine(float value);
public static void WriteLine(double value);
public static void WriteLine(decimal value);
public static void WriteLine(object value);

Besides these versions, the Write() and the WriteLine() methods have each a version that takes an unlimited number of arguments. Their syntaxes are:

public static void WriteLine(. . .);
public static void WriteLine(. . .);

To get skeleton code for System.Console.WriteLine, right-click the line where you want to add it, position the mouse on Snippet, and click Insert Snippet... Double-click Visual C#. In the list, double-click cw:

cw

Practical LearningPractical Learning: Introducing Data Writing

  1. Change the document as follows:
    System.Console.WriteLine("-/- Georgetown Dry Cleaning Services -/-");
  2. To execute the application to see the result, on the main menu, click Debug -> Start Without Debugging:
    -/- Georgetown Dry Cleaning Services -/-
    Press any key to continue . . .
  3. In the console window, press Enter to close it and return to your programming environement

Accessing the Members of the Console Class

Remember that, to access any class, you can qualify it from its namespace. Here is an example of calling a method of the Console class that is defined in the System namespace:

System.Console.WriteLine("The Wonderful World of C# Programming");

Using a Namespace

As you may know by now, to use a namespace, in your code, usually in the top section, type using followed by the name of the namespace. After doing that, you can access a class of the namespace in your code.

Practical LearningPractical Learning: Using a Namespace

  1. Change the document as follows:
    using System;
    
    Console.WriteLine("-/- Georgetown Dry Cleaning Services -/-");
    Console.WriteLine("      Cursomer Order Processing");
    Console.WriteLine("========================================");
  2. To execute the application to see the result, on the main menu, click Debug -> Start Without Debugging:
    -/- Georgetown Dry Cleaning Services -/-
          Cursomer Order Processing
    Press any key to continue . . .
  3. In the console window, press Z to close it and return to your programming environement

Not Using the System

When you create a Console App in Microsoft Visual studio, the System namespace is automatically made available. As a result, as you don't have to "load" its library, you don't need the "using System;" line. If you omit that line, you can use the "Console.Write()" and the "Console.WriteLine()" expressions in your document.

Practical LearningPractical Learning: Omitting the System Namespace

Statically Using a Namespace

Remember that, to access a static method, you can include using static followed by the name of the class in the top section of the document. Then, where needed, call the static method directly.

using static System.Console;

WriteLine("The Wonderful World of C# Programming");

Reading a Value from the Console

Introduction

While the Console.Write() method is used to display something on the screen, the Console class provides a method named Read that is used to get a value from the user. To use it, the name of a variable can be assigned to it. The syntax used is:

variable-name = Console.Read();

This simply means that, when the user types something and presses Enter, what the user had typed would be given (the word is assigned) to the variable specified on the left side of the assignment operator.

The Read() method doesn't always have to assign its value to a variable. For example, it can be used on its own line, which simply means that the user is expected to type something but the value typed by the user would not be used for any significant purpose. For example some versions of a program display the DOS window briefly and disappear. You can use the Read() function to wait for the user to press any key in order to close the DOS window.

Reading a Key

As you may know already, each letter of the alphabet is represented on the keyboard by a key. Other symbols, readable (such as #, @, or $) or not (such as Shift, Ctrl, Space, or Enter) are also represented. To get the letter or the action that those keys represent, the Console class is equipped with a method named ReadKey that is overloaded with two versions. One of the versions uses the following syntax:

public static ConsoleKeyInfo ReadKey();

This method takes no argument but produces a value of a class named ConsoleKeyInfo. To get the value returned by this method, you can declare a ConsoleKeyInfo variable and assign it to the calling of this method.

If the user presses a key for a letter or a readable symbol (such as #, !, /, or %), to recognize the key that was pressed, the ConsoleKeyInfo class is equipped with a member named KeyChar. Here is an example of getting the letter:

ConsoleKeyInfo cki = new ConsoleKeyInfo();

Console.Write("Press a key: ");
cki = Console.ReadKey();
Console.WriteLine();

Console.Write("You pressed: ");
Console.WriteLine(cki.KeyChar);

Console.ReadKey();

If the key that the user pressed is not a readable symbol such as the Space Bar, a Ctrl key, or Enter, to recognize it, the ConsoleKeyInfo class is equipped with a member named Key. Here is an example of using it:

ConsoleKeyInfo cki = new ConsoleKeyInfo();

Console.Write("Press a key: ");
cki = Console.ReadKey();
Console.WriteLine();

Console.Write("You pressed: ");
Console.WriteLine(cki.Key);

Console.ReadKey();

When it finishes reading its key, the Console.ReadKey() method stops and lets you decide what to do. If you want it to display the result, the Console class provides another version of the ReadKey() method. Its syntax is:

public static ConsoleKeyInfo ReadKey(bool intercept);

The Boolean argument specifies whether you want the method to display the value.

Reading With a New Line

Besides Read(), the Console class also provides the ReadLine() method. Like the WriteLine() method, after performing its assignment, the ReadLine() method sends the caret to the next line. Otherwise, it plays the same role as the Read() function.

Characteristics and Behaviors of a Console

The Title of a Console Screen

A console window is primarily a normal window with classic behaviors. It is equipped with a title bar that displays a title. By default, the title bar displays the path of the Command Prompt. Here is an example:

Title

To allow you to change the title of its window, the Console class is equipped with a property named Console.Title. Here is an example of specifying the title of a console window:

Console.Title = "Department Store";

Title

Practical LearningPractical Learning: Naming a Console Window

  1. Change the code as follows:
    Console.Title = "Georgetown Dry Cleaning Services";
    
    Console.WriteLine("-/- Georgetown Dry Cleaning Services -/-");
    Console.WriteLine("      Cursomer Order Processing");
    Console.WriteLine("========================================");
  2. To execute the application to see the result, on the main menu, click Debug -> Start Without Debugging
  3. In the console window, press Enter to close it and return to your programming environement
  4. Change the code as follows:
    Console.Title = "Georgetown Dry Cleaning Services";
    
    Console.WriteLine("-/- Georgetown Dry Cleaning Services -/-");
    Console.WriteLine("      Cursomer Order Processing");
    
    string customerName = "", homePhone = "";
    
    // Display the receipt
    Console.WriteLine("====================================");
    Console.WriteLine("-/- Georgetown Dry Cleaning Services -/-");
    Console.WriteLine("====================================");
    Console.Write("Customer:   ");
    Console.WriteLine(customerName);
    Console.Write("Home Phone: ");
    Console.WriteLine(homePhone);
    
    Console.WriteLine("========================================");

Clearing the Console

If the console screen is filled with text you don't need anymore, you can empty it. To allow you to clear the screen, the Console class is equipped with a method named Clear. It syntax is:

public static void Clear();

Practical LearningPractical Learning: Clearing the Console

Data Reading

String Value Request

In most cases the user provides a value in your application, you will not know that value. For example, you may want the user to provide a string. To request a string, you can call the Console.Read() or the Console.ReadLine() method and assign it to the name of the variable whose value you want to retrieve. Here is an example:

string firstName;

Console.Write("Enter First Name: ");
firstName = Console.ReadLine()!;

Practical LearningPractical Learning: Reading String Values

  1. To request strings from the user, change the code as follows:
    Console.Title = "Georgetown Dry Cleaning Services";
    
    Console.WriteLine("-/- Georgetown Dry Cleaning Services -/-");
    Console.WriteLine("      Cursomer Order Processing");
    
    string customerName = "", homePhone = "";
    
    // Request customer information from the user
    Console.Write("Enter Customer Name:  ");
    customerName = Console.ReadLine()!;
    Console.Write("Enter Customer Phone: ");
    homePhone = Console.ReadLine()!;
    
    Console.Clear();
    
    // Display the receipt
    Console.WriteLine("====================================");
    Console.WriteLine("-/- Georgetown Dry Cleaning Services -/-");
    Console.WriteLine("====================================");
    Console.Write("Customer:   ");
    Console.WriteLine(customerName);
    Console.Write("Home Phone: ");
    Console.WriteLine(homePhone);
    
    Console.WriteLine("========================================");
  2. To execute the program, press Ctrl + F5
  3. When asked, type James Watson
  4. Press Enter
  5. When asked to provide a phone number, type (410) 493-2005
    -/- Georgetown Dry Cleaning Services -/-
          Cursomer Order Processing
    ========================================
    Enter Customer Name:  James Watson
    Enter Customer Phone: (410) 493-2005
  6. Press Enter:
    ========================================
    -/- Georgetown Dry Cleaning Services -/-
    ========================================
    Customer:   James Watson
    Home Phone: (410) 493-2005
    ========================================
    Press any key to continue . . .
  7. Press Enter to close the console window and return to your programming environment

Number Request

Practically everything the user types in your program is a string and the compiler would hardly analyze it without your explicit asking it to do so. Therefore, if you want to get a number from the user, first request a string. Here is an example:

using static System.Console;

int number;
string strNumber;

strnumber = ReadLine();

After getting the string, you must convert it to a number. To perform this conversion, as we saw in previous lessons, each data type is represented in the .NET Framework by a structure that is equipped with a method named Parse. To convert a number, pass its variable to the Parse() method. Here is an example:

int number;
string strNumber;

strnumber = Console.ReadLine()!;
number = int.Parse(strNumber);

As an alternative, call the Console.Read() or the Console.ReadLine() method directly in the parentheses of the Parse() method. Here is an example:

int number;

number = int.Parse(Console.ReadLine());

Practical LearningPractical Learning: Reading Numeric Values

  1. To retrieve various numbers from the user, change the file as follows:
    Console.Title = "Georgetown Dry Cleaning Services";
    
    Console.WriteLine("-/- Georgetown Dry Cleaning Services -/-");
    Console.WriteLine("      Cursomer Order Processing");
    Console.WriteLine("========================================");
    
    // Price of items
    const double PriceOneShirt = 1.35;
    const double PriceAPairOfPants = 2.95;
    const double PriceOneDress = 4.55;
    const double TaxRate = 0.0575;  // 5.75%
    
    // Request customer information from the user
    // Customer personal information
    Console.Write("Enter Customer Name:  ");
    string customerName = Console.ReadLine()!;
    Console.Write("Enter Customer Phone: ");
    string homePhone = Console.ReadLine()!;
    
    // Request the quantity of each category of items
    Console.Write("Number of Shirts:     ");
    string strShirts = Console.ReadLine()!;
    uint numberOfShirts = uint.Parse(strShirts);
    
    Console.Write("Number of Pants:      ");
    string strPants = Console.ReadLine()!;
    uint numberOfPants = uint.Parse(strPants);
    
    Console.Write("Number of Dresses:    ");
    string strDresses = Console.ReadLine()!;
    uint numberOfDresses = uint.Parse(strDresses);
    
    // Perform the necessary calculations
    double subTotalShirts = numberOfShirts * PriceOneShirt;
    double subTotalPants = numberOfPants * PriceAPairOfPants;
    double subTotalDresses = numberOfDresses * PriceOneDress;
    // Calculate the "temporary"total of the order
    double totalOrder = subTotalShirts + subTotalPants + subTotalDresses;
    
    // Calculate the tax amount using a constant rate
    double taxAmount = totalOrder * TaxRate;
    // Add the tax amount to the total order
    double salesTotal = totalOrder + taxAmount;
    
    // Communicate the total to the user...
    Console.Write("\nThe Total order is:   ");
    Console.WriteLine(salesTotal);
    // and request money for the order
    Console.Write("Amount Presented?        ");
    double amountPresented = double.Parse(Console.ReadLine()!);
    
    // Calculate the difference owed to the customer
    // or that the customer still owes to the store
    double moneyChange = amountPresented - salesTotal;
    
    Console.Clear();
    
    // Display the receipt
    Console.WriteLine("========================================");
    Console.WriteLine("-/- Georgetown Dry Cleaning Services -/-");
    Console.WriteLine("----------------------------------------");
    Console.WriteLine("       Customer Cleaning Order");
    Console.WriteLine("========================================");
    Console.Write("Customer:   ");
    Console.WriteLine(customerName);
    Console.Write("Home Phone: ");
    Console.WriteLine(homePhone);
    Console.WriteLine("----------------------------------------");
    Console.WriteLine("Item Type  Qty Unit/Price Sub-Total");
    Console.WriteLine("----------------------------------------");
    Console.Write("Shirts      ");
    Console.Write(numberOfShirts);
    Console.Write("     ");
    Console.Write(PriceOneShirt);
    Console.Write("     ");
    Console.WriteLine(subTotalShirts);
    Console.Write("Pants       ");
    Console.Write(numberOfPants);
    Console.Write("     ");
    Console.Write(PriceAPairOfPants);
    Console.Write("     ");
    Console.WriteLine(subTotalPants);
    Console.Write("Dresses     ");
    Console.Write(numberOfDresses);
    Console.Write("     ");
    Console.Write(PriceOneDress);
    Console.Write("     ");
    Console.WriteLine(subTotalDresses);
    Console.WriteLine("----------------------------------------");
    Console.Write("Total Order:      ");
    Console.WriteLine(totalOrder);
    Console.Write("Tax Rate:         ");
    Console.Write(TaxRate * 100);
    Console.WriteLine('%');
    Console.Write("Tax Amount:       ");
    Console.WriteLine(taxAmount);
    Console.Write("Net Price:        ");
    Console.WriteLine(salesTotal);
    Console.WriteLine("----------------------------------------");
    Console.Write("Amount Tended:    ");
    Console.WriteLine(amountPresented);
    Console.Write("Difference:       ");
    Console.WriteLine(moneyChange);
    Console.WriteLine("========================================");
  2. To execute the program and test it, press Ctrl + F5
  3. When requested, type the Customer Name as James Watson and press Enter
  4. Type the Customer Phone as (401)493-2005
  5. For the Number of Shorts, type 8 and press Enter
  6. For the Number of Pants, type 3 and press Enter
  7. For the Number of Dresses, type 5 and press Enter
  8. For the Amount Tended, type 50
    -/- Georgetown Dry Cleaning Services -/-
          Cursomer Order Processing
    ========================================
    Enter Customer Name:  James Watson
    Enter Customer Phone: (401) 493-2005
    Number of Shirts:     8
    Number of Pants:      3
    Number of Dresses:    5
    
    The Total order is:   44.838
    Amount Presented?        50
  9. Press Enter
    ========================================
    -/- Georgetown Dry Cleaning Services -/-
    ----------------------------------------
           Customer Cleaning Order
    ========================================
    Customer:   James Watson
    Home Phone: (401) 493-2005
    ----------------------------------------
    Item Type  Qty Unit/Price Sub-Total
    ----------------------------------------
    Shirts      8     1.35     10.8
    Pants       3     2.95     8.85
    Dresses     5     4.55     22.75
    ----------------------------------------
    Total Order:      42.4
    Tax Rate:         5.75%
    Tax Amount:       2.438
    Net Price:        44.838
    ----------------------------------------
    Amount Tended:    50
    Difference:       5.16199999999999
    ========================================
    Press any key to continue . . .
  10. Press Enter to close the console window and return to your programming environement

Formatting Data Display

Introduction

Instead of using two Write() methods or a combination of theWrite() and the WriteLine() methods to display data, you can convert a value to a string and display it directly. To do this, you can provide two sections to the Write() or the WriteLine() methods and separate them with a comma:

  1. The first part is the first argument to the Write() or the WriteLine() method. Normally, this argument is passed as a string that would display to the user. This string argument can itself be made of different sections:
    1. One section is a string in any way you want it to display
    2. Another section is a number included between an opening curly bracket "{" and a closing curly bracket "}". This combination of "{" and "}" is referred to as a placeholder
      You can put the placeholder anywhere inside the string. The first placeholder must have number 0. The second must have number 1, and so on. With this technique, you can create the string anyway you like and use the placeholders anywhere inside the string
  2. The second section of the arguments passed to the Write() or the WriteLine() method is one or more values you want to display. It can be one value if you used only one placeholder with 0 in the first string argument. If you used different placeholders, you can then provide a different value for each one of them in this second part, separating the values with a comma

Here are examples:

var fullName = "Anselme Bogos";
var age = 15;
var hSalary = 22.74;

Console.WriteLine("Full Name: {0}", fullName);
Console.WriteLine("Age: {0}", Age);
Console.WriteLine("Distance: {0}", hSalary);

This would produce:

Full Name: Anselme Bogos
Age: 15
Distance: 22.74

As mentioned already, the numeric value typed in the curly brackets of the first part is an ordered number. If you want to display more than one value, provide each incremental value in its curly brackets. The syntax used is:

Write("To Display {0} {1} {2} {n}", First, Second, Third, nth);

You can use the sections between a closing curly bracket and an opening curly bracket to create a meaningful sentence.

Practical LearningPractical Learning: Displaying Data With Placeholders

  1. To use curly brackets to display data, change the document as follows:
    Console.Title = "Georgetown Dry Cleaning Services";
    
    Console.WriteLine("-/- Georgetown Dry Cleaning Services -/-");
    Console.WriteLine("      Cursomer Order Processing");
    Console.WriteLine("========================================");
    
    // Price of items
    const double PriceOneShirt = 1.35;
    const double PriceAPairOfPants = 2.95;
    const double PriceOneDress = 4.55;
    const double TaxRate = 0.0575;  // 5.75%
    
    // Request customer information from the user
    // Customer personal infoirmation
    Console.Write("Enter Customer Name:  ");
    string customerName = Console.ReadLine()!;
    Console.Write("Enter Customer Phone: ");
    string homePhone = Console.ReadLine()!;
    
    // Request the quantity of each category of items
    Console.Write("Number of Shirts:     ");
    string strShirts = Console.ReadLine()!;
    uint numberOfShirts = uint.Parse(strShirts);
    
    Console.Write("Number of Pants:      ");
    string strPants = Console.ReadLine()!;
    uint numberOfPants = uint.Parse(strPants);
    
    Console.Write("Number of Dresses:    ");
    string strDresses = Console.ReadLine()!;
    uint numberOfDresses = uint.Parse(strDresses);
    
    // Perform the necessary calculations
    double subTotalShirts = numberOfShirts * PriceOneShirt;
    double subTotalPants = numberOfPants * PriceAPairOfPants;
    double subTotalDresses = numberOfDresses * PriceOneDress;
    // Calculate the "temporary"total of the order
    double totalOrder = subTotalShirts + subTotalPants + subTotalDresses;
    
    // Calculate the tax amount using a constant rate
    double taxAmount = totalOrder * TaxRate;
    // Add the tax amount to the total order
    double salesTotal = totalOrder + taxAmount;
    
    // Communicate the total to the user...
    Console.Write("\nThe Total order is:   ");
    Console.WriteLine(salesTotal);
    // and request money for the order
    Console.Write("Amount Presented?        ");
    double amountPresented = double.Parse(Console.ReadLine()!);
    
    // Calculate the difference owed to the customer
    // or that the customer still owes to the store
    double moneyChange = amountPresented - salesTotal;
    
    Console.Clear();
    
    // Display the receipt
    Console.WriteLine("-/- Georgetown Dry Cleaning Services -/-");
    Console.WriteLine("====================================");
            Console.WriteLine("Customer:   {0}", customerName);
    Console.WriteLine("Home Phone: {0}", homePhone);
    Console.WriteLine("------------------------------------");
    Console.WriteLine("Item Type  Qty Unit/Price Sub-Total");
    Console.WriteLine("------------------------------------");
    Console.WriteLine("Shirts      {0}     {1}     {2}",
                      numberOfShirts, PriceOneShirt, subTotalShirts);
    Console.WriteLine("Pants       {0}     {1}     {2}",
                      numberOfPants, PriceAPairOfPants, subTotalPants);
    Console.WriteLine("Dresses     {0}     {1}     {2}",
                      numberOfDresses, PriceOneDress, subTotalDresses);
    Console.WriteLine("------------------------------------");
    Console.WriteLine("Total Order:     {0}", totalOrder);
    Console.WriteLine("Tax Rate:        {0}%", TaxRate * 100);
    Console.WriteLine("Tax Amount:      {0}", taxAmount);
    Console.WriteLine("Net Price:       {0}", salesTotal);
    Console.WriteLine("------------------------------------");
    Console.WriteLine("Amount Tended:   {0}", amountPresented);
    Console.WriteLine("Difference:      {0}", moneyChange);
    Console.WriteLine("========================================");
  2. To execute the program and test it, press Ctrl + F5
  3. When requested, type the Customer Name as Jennifer Longhorn and press Enter
  4. Type the Customer Phone as (142) 570-9274
  5. For the Number of Shorts, type 5 and press Enter
  6. For the Number of Pants, type 2 and press Enter
  7. For the Number of Dresses, type 7 and press Enter
  8. For the Amount Tended, type 48
    -/- Georgetown Dry Cleaning Services -/-
          Cursomer Order Processing
    ========================================
    Enter Customer Name:  Jennifer Longhorn
    Enter Customer Phone: (142) 570-9274
    Number of Shirts:     5
    Number of Pants:      2
    Number of Dresses:    7
    
    The Total order is:   47.05875
    Amount Presented?        48
  9. Press Enter
    -/- Georgetown Dry Cleaning Services -/-
    ====================================
    Customer:   Jennifer Longhorn
    Home Phone: (142) 570-9274
    ------------------------------------
    Item Type  Qty Unit/Price Sub-Total
    ------------------------------------
    Shirts      5     1.35     6.75
    Pants       2     2.95     5.9
    Dresses     7     4.55     31.85
    ------------------------------------
    Total Order:     44.5
    Tax Rate:        5.75%
    Tax Amount:      2.55875
    Net Price:       47.05875
    ------------------------------------
    Amount Tended:   48
    Difference:      0.941249999999997
    ========================================
    Press any key to continue . . .
  10. To close the window, press R, and return to your programming environment

Conversion To String

We mentioned earlier that everything the user types using the keyboard is primarily a string and it's your job to convert it to the appropriate type. In reverse, if you have a value that is not a string, you can easily convert it to a string. To support this, the .NET Framework structure of each data type is equipped with a method named ToString. Normally, in C#, as we have done so far, this conversion is automatically or transparently done by the compiler. In some cases, you will need to perform the conversion yourself.

To convert a value of a primitive data type to a string, type the name of the variable, followed by a period, followed by ToString(). Here is an example:

string fullName = "Anselme Bogos";
int age = 15;
double hSalary = 22.74;

Console.WriteLine("Full Name: {0}", fullName);
Console.WriteLine("Age: {0}", age.ToString());
Console.WriteLine("Distance: {0}", hSalary.ToString());

In some cases, you will type something in the parentheses of ToString().

Number Formatting

To properly display data in a friendly and most familiar way, you can format it. Formatting tells the compiler what kind of data you are using and how you want the compiler to display it to the user.

The System namespace provides a specific letter you can use in the Write() or WriteLine()'s placeholder for each category of data to display. To format a value, in the placeholder of the variable or value, after the number, type a colon and one of the appropriate letters from the following table. If you are using ToString(), then, in the parentheses of ToString(), you can include a specific letter or combination inside of double-quotes. The letters and their meanings are:

Character Description
c C Currency values
d D Decimal numbers
e E Scientific numeric display such as 1.45e5
f F Fixed decimal numbers
d D General and most common type of numbers
n N Natural numbers
r R Roundtrip formatting
s S Hexadecimal formatting
p P Percentages

Here are examples:

var Distance = 248.38782;
var age = 15;
var NewColor = 3478;
var hSalary = 22.74;
var HoursWorked = 35.5018473;
var WeeklySalary = hSalary * HoursWorked;

Console.WriteLine("Distance: {0}", Distance.ToString("E"));
Console.WriteLine("Age: {0}", age.ToString());
Console.WriteLine("Color: {0}", NewColor.ToString("X"));
Console.WriteLine("Weekly Salary: {0} for {1} hours",
                          WeeklySalary.ToString("c"),
              		      HoursWorked.ToString("F"));

This would produce:

Distance: 2.483878E+002
Age: 15
Color: D96
Weekly Salary: $807.31 for 35.50 hours

As you may have noticed, if you leave the parentheses of ToString() empty, the compiler would use a default formatting to display the value.

As opposed to calling ToString(), you can use the above letters in the curly brackets of the first part of Write() or WriteLine(). In this case, after the number in the curly brackets, type the colon operator followed by the letter.

Practical LearningPractical Learning: Formatting Data Display

  1. To format data display, change the file as follows:
    Console.Title = "Georgetown Dry Cleaning Services";
    
    Console.WriteLine("-/- Georgetown Dry Cleaning Services -/-");
    Console.WriteLine("      Cursomer Order Processing");
    Console.WriteLine("========================================");
    
    // Price of items
    const double priceOneShirt = 1.35;
    const double priceAPairOfPants = 2.95;
    const double priceOneDress = 4.55;
    const double taxRate = 0.0575;  // 5.75%
    
    // Request customer information from the user
    // Customer personal infoirmation
    Console.Write("Enter Customer Name:  ");
    string customerName = Console.ReadLine()!;
    Console.Write("Enter Customer Phone: ");
    string homePhone = Console.ReadLine()!;
    
    // Request the quantity of each category of items
    Console.Write("Number of Shirts:     ");
    string strShirts = Console.ReadLine()!;
    uint numberOfShirts = uint.Parse(strShirts);
    
    Console.Write("Number of Pants:      ");
    string strPants = Console.ReadLine()!;
    uint numberOfPants = uint.Parse(strPants);
    
    Console.Write("Number of Dresses:    ");
    string strDresses = Console.ReadLine()!;
    uint numberOfDresses = uint.Parse(strDresses);
    
    // Perform the necessary calculations
    double subTotalShirts = numberOfShirts * priceOneShirt;
    double subTotalPants = numberOfPants * priceAPairOfPants;
    double subTotalDresses = numberOfDresses * priceOneDress;
    // Calculate the "temporary"total of the order
    double totalOrder = subTotalShirts + subTotalPants + subTotalDresses;
    
    // Calculate the tax amount using a constant rate
    double taxAmount = totalOrder * taxRate;
    // Add the tax amount to the total order
    double salesTotal = totalOrder + taxAmount;
    
    // Communicate the total to the user...
    Console.Write("\nThe Total order is:   ");
    Console.WriteLine(salesTotal.ToString("F"));
    // and request money for the order
    Console.Write("Amount Presented?        ");
    double amountPresented = double.Parse(Console.ReadLine()!);
    
    // Calculate the difference owed to the customer
    // or that the customer still owes to the store
    double moneyChange = amountPresented - salesTotal;
    
    Console.Clear();
    
    // Display the receipt
    Console.WriteLine("-/- Georgetown Dry Cleaning Services -/-");
    Console.WriteLine("====================================");
    Console.WriteLine("Customer:   {0}", customerName);
    Console.WriteLine("Home Phone: {0}", homePhone);
    Console.WriteLine("------------------------------------");
    Console.WriteLine("Item Type  Qty Unit/Price Sub-Total");
    Console.WriteLine("------------------------------------");
    Console.WriteLine("Shirts      {0}     {1:F}     {2:C}",
                          numberOfShirts, priceOneShirt, subTotalShirts);
    Console.WriteLine("Pants       {0}     {1:F}     {2:F}",
                      numberOfPants, priceAPairOfPants, subTotalPants);
    Console.WriteLine("Dresses     {0}     {1}     {2}",
                      numberOfDresses, priceOneDress.ToString("F"), subTotalDresses.ToString("C"));
    Console.WriteLine("------------------------------------");
    Console.WriteLine("Total Order:     {0:C}", totalOrder);
    Console.WriteLine("Tax Rate:        {0:P}", taxRate);
    Console.WriteLine("Tax Amount:      {0}", taxAmount.ToString("C"));
    Console.WriteLine("Net Price:       {0}", salesTotal.ToString("C"));
    Console.WriteLine("------------------------------------");
    Console.WriteLine("Amount Tended:   {0:C}", amountPresented);
    Console.WriteLine("Difference:      {0}", moneyChange.ToString("C"));
    Console.WriteLine("========================================");
  2. To execute the application and test it, on the main menu, click Debug -> Start Without Debugging
  3. When requested, type the Customer Name as James Watson and press Enter
  4. Type the Customer Phone as (401)493-2005
  5. For the Number of Shorts, type 8 and press Enter
  6. For the Number of Pants, type 3 and press Enter
  7. For the Number of Dresses, type 5 and press Enter
  8. For the Amount Tended, type 50
    -/- Georgetown Dry Cleaning Services -/-
          Cursomer Order Processing
    ========================================
    Enter Customer Name:  James Watson
    Enter Customer Phone: (401) 493-2005
    Number of Shirts:     8
    Number of Pants:      3
    Number of Dresses:    5
    
    The Total order is:   44.84
    Amount Presented?        50
  9. Press Enter
    -/- Georgetown Dry Cleaning Services -/-
    ====================================
    Customer:   James Watson
    Home Phone: (401) 493-2005
    ------------------------------------
    Item Type  Qty Unit/Price Sub-Total
    ------------------------------------
    Shirts      8     1.35     $10.80
    Pants       3     2.95     8.85
    Dresses     5     4.55     $22.75
    ------------------------------------
    Total Order:     $42.40
    Tax Rate:        5.75%
    Tax Amount:      $2.44
    Net Price:       $44.84
    ------------------------------------
    Amount Tended:   $50.00
    Difference:      $5.16
    ========================================
    Press any key to continue . . .
  10. Press Enter to close the console window and return to your programming environement

Line Formatting

In the above programs, to display a line of text, we easily used Write() or WriteLine(). To position text of different lengths one above the other, we had to "corrupt" a string by including extra-empty spaces. Such a technique is uncertain and less professional. Fortunately, you can format how a string or a line of text should display. The .NET Framework provides mechanisms to control the amount of space used to display a string of text and how to align that string on its line.

To specify the amount of space used to display a string, you can use its placeholder in Write() or WriteLine(). To do this, in the placeholder, type the number or the variable in the curly brackets. Then, type a comma followed by the number of characters equivalent to the desired width. Here are examples:

string fullName = "Anselme Bogos";
int age = 15;
double hSalary = 22.74;

Console.WriteLine("Full Name: {0,20}", fullName);
Console.WriteLine("Age:{0,14}", age.ToString());
Console.WriteLine("Distance: {0:C,8}", hSalary.ToString());

This would produce:

Full Name:        Anselme Bogos
Age:            15
Distance: 22.74

The sign you provide for the width is very important. If it is positive, the line of text is aligned to the right. This should be your preferred alignment for numeric values. If the number is negative, then the text is aligned to the left.

Practical LearningPractical Learning: Managing Console Display

  1. Start a new Console App that supports .NET 8.0 (Long-term support) and named StellarWaterPoint8
  2. To create a new folder, in the Solution Explorer, right-click StellarWaterPoint8 -> Add -> New Folder
  3. Type Models as the name of the folder
  4. To create a class, in the Solution Explorer, right-click Models -> Add -> Class...
  5. Type WaterBill as the name of the file and class
  6. Click Add
  7. Change the class as follows:
    namespace StellarWaterPoint8.Models
    {
        internal enum Classification { Residential, NonProfit, WaterIntensive, GeneralUse, Other }
    
        internal class WaterBill
        {
            private readonly string typeOfAccount;
    
            public WaterBill(string category) => typeOfAccount = category;
    
            public double CounterReadingStart { get; set; }
            public double CounterReadingEnd   { get; set; }
    
            public (Classification @class, string name) AccountType
            {
                get
                {
                    if (typeOfAccount == "1")
                        return (Classification.Residential, "Residential Household");
                    else if (typeOfAccount == "2")
                        return (Classification.NonProfit, "Social/Non-Profit Organization");
                    else if (typeOfAccount == "3")
                        return (Classification.WaterIntensive, "Water Intensive Business (Laudromat, Hair Salon, etc)");
                    else if (typeOfAccount == "4")
                        return (Classification.GeneralUse, "General Business, Government");
                    else
                        return (Classification.Other, "Other");
                }
            }
    
            public double Gallons => CounterReadingEnd - CounterReadingStart;
    
            public double HCFTotal => Gallons / 748;
    
            public (double FirstTier, double NextTier, double LastTier) Therms
            {
                get
                {
                    double first, next, above;
    
                    if (HCFTotal is > 40.00)
                    {
                        first = 25.00 * 1.5573;
                        next  = 15.00 * 1.2264;
                        above = (HCFTotal - 40.00) * 0.9624;
                    }
                    else if (HCFTotal > 25.00)
                    {
                        first = 25.00 * 1.5573;
                        next  = (HCFTotal - 25.00) * 1.2264;
                        above = 0.00;
                    }
                    else // if (HCFTotal > 40.00)
                    {
                        first = HCFTotal * 1.5573;
                        next  = 0.00;
                        above = 0.00;
                    }
    
                    return (first, next, above);
                }
            }
    
            public double WaterUsageCharges => Therms.FirstTier + Therms.NextTier + Therms.LastTier;
    
            public double SewerCharges
            {
                get
                {
                    double result = AccountType.@class switch
                    {
                        Classification.Residential     => WaterUsageCharges * 0.2528,
                        Classification.NonProfit       => WaterUsageCharges * 0.0915,
                        Classification.WaterIntensive  => WaterUsageCharges * 1.5865,
                        Classification.GeneralUse      => WaterUsageCharges * 0.6405,
                        _                              => WaterUsageCharges * 1.2125
                    };
    
                    return result;
                }
            }
    
            public double EnvironmentCharges
            {
                get
                {
                    double result = AccountType.@class switch
                    {
                        Classification.Residential    => WaterUsageCharges * 0.0025,
                        Classification.NonProfit      => WaterUsageCharges * 0.0015,
                        Classification.WaterIntensive => WaterUsageCharges * 0.0105,
                        Classification.GeneralUse     => WaterUsageCharges * 0.0045,
                        _                             => WaterUsageCharges * 0.0125
                    };
    
                    return result;
                }
            }
    
            public double ServiceCharges
            {
                get => AccountType.@class switch
                {
                    Classification.Residential        => WaterUsageCharges * 0.0328,
                    Classification.NonProfit          => WaterUsageCharges * 0.0115,
                    Classification.WaterIntensive     => WaterUsageCharges * 0.1015,
                    Classification.GeneralUse         => WaterUsageCharges * 0.0808,
                    _                                 => WaterUsageCharges * 0.1164
                };
            }
    
            public double TotalCharges => WaterUsageCharges + SewerCharges + EnvironmentCharges + ServiceCharges;
    
            public double LocalTaxes
            {
                get => AccountType.@class switch
                {
                    Classification.Residential        => TotalCharges * 0.115,
                    Classification.NonProfit          => TotalCharges * 0.085,
                    Classification.WaterIntensive     => TotalCharges * 0.825,
                    Classification.GeneralUse         => TotalCharges * 0.315,
                    _                                 => TotalCharges * 0.625
                };
            }
    
            public double StateTaxes => AccountType.@class switch
            {
                Classification.Residential            => TotalCharges * 0.035,
                Classification.NonProfit              => TotalCharges * 0.015,
                Classification.WaterIntensive         => TotalCharges * 0.105,
                Classification.GeneralUse             => TotalCharges * 0.065,
                _                                     => TotalCharges * 0.815
            }; 
    
            public double AmountDue => TotalCharges + LocalTaxes + StateTaxes;
        }
    }
  8. In the Solution Explorer, right-click Program.cs and click Rename
  9. Type BillProcessing (to get BillProcessing.cs) and press Enter
  10. Click the BillProcessing.cs tab and change the document as follows:
    using StellarWaterPoint8.Models;
    using static System.Console;
    
    WriteLine("Stellar Water Point");
    WriteLine("===========================================================");
    
    string ? answer = "";
    
    try
    {
        WriteLine("To prepare an invoice, enter the following information");
        WriteLine("Types of Accounts");
        WriteLine("1. Residential Household");
        WriteLine("2. Social/Non-Profit Organization");
        WriteLine("3. Water Intensive Business (Laudromat, etc)");
        WriteLine("4. General Business");
        WriteLine("0. Other");
        Write("Enter Type of Account:         ");
        answer = ReadLine()!;
        WriteLine("-----------------------------------------------------------");
    }
    catch(FormatException fe)
    {
        WriteLine("There was an error from the request for the account type was presented." + Environment.NewLine +
                  "The error produced was: " + fe.Message);
        WriteLine("-----------------------------------------------------------");
    }
    
    Clear();
    
    WaterBill bill = new WaterBill(answer);
    
    if (bill != null)
    {
        WriteLine("===========================================================");
        WriteLine("Stellar Water Point - Customer Invoice");
        WriteLine("Account Type: {0}", bill.AccountType.name);
        WriteLine("===========================================================");
    
        try
        {
            Write("Counter Reading Start:         ");
            bill.CounterReadingStart = int.Parse(ReadLine()!);
        }
        catch (FormatException fe)
        {
            WriteLine("There was an error from the request for the counter starting number was made." + Environment.NewLine +
                      "The error produced was: " + fe.Message);
            WriteLine("-----------------------------------------------------------");
        }
    
        try
        {
            Write("Counter Reading End:           ");
            bill.CounterReadingEnd = int.Parse(ReadLine()!);
        }
        catch (FormatException fe)
        {
            WriteLine("There was an error from the request for the counter ending number was made." + Environment.NewLine +
                      "The error produced was: " + fe.Message);
            WriteLine("-----------------------------------------------------------");
        }
    
        Clear();
    
        if ((answer != "") && (bill.CounterReadingStart != 0) && (bill.CounterReadingEnd != 0))
        {
            WriteLine("===========================================================");
            WriteLine("Stellar Water Point - Customer Invoice");
            WriteLine("Account Type: {0}", bill.AccountType.name);
            WriteLine("===========================================================");
            WriteLine("Meter Reading");
            WriteLine("-----------------------------------------------------------");
            WriteLine("Counter Reading Start:      {0,10}", bill.CounterReadingStart);
            WriteLine("Counter Reading End:        {0,10}", bill.CounterReadingEnd);
            WriteLine("Total Gallons Consumed:     {0,10}", bill.Gallons);
            WriteLine("===========================================================");
            WriteLine("Therms Evaluation");
            WriteLine("-----------------------------------------------------------");
            WriteLine("HCF Total:                  {0,10:n}", bill.HCFTotal);
            WriteLine("First 35 Therms (* 1.5573): {0,10:n}", bill.Therms.FirstTier);
            WriteLine("First 20 Therms (* 1.2264): {0,10:n}", bill.Therms.NextTier);
            WriteLine("Above 40 Therms (* 0.9624): {0,10:n}", bill.Therms.LastTier);
            WriteLine("-----------------------------------------------------------");
            WriteLine("Water Usage Charges:        {0,10:n}", bill.WaterUsageCharges);
            WriteLine("Sewer Charges:              {0,10:n}", bill.SewerCharges);
            WriteLine("===========================================================");
            WriteLine("Bill Values");
            WriteLine("-----------------------------------------------------------");
            WriteLine("Environment Charges:        {0,10:n}", bill.EnvironmentCharges);
            WriteLine("Service Charges:            {0,10:n}", bill.ServiceCharges);
            WriteLine("Total Charges:              {0,10:n}", bill.TotalCharges);
            WriteLine("Local Taxes:                {0,10:n}", bill.LocalTaxes);
            WriteLine("State Taxes:                {0,10:n}", bill.StateTaxes);
            WriteLine("-----------------------------------------------------------");
            WriteLine("Amount Due:                 {0,10:n}", bill.AmountDue);
        }
        else
        {
            WriteLine("===========================================================");
            WriteLine("The water bill was not prepared appropriately.");
        }
    }
    
    Write("===========================================================");
  11. To execute, on the main menu, click Debug -> Start Without Debugging
  12. When requested, for the type of account, type 1 and simply press Enter:
    ===========================================================
    Stellar Water Point - Customer Invoice
    Account Type: Residential Household
    ===========================================================
    Counter Reading Start:
  13. For the Counter Reading Start, type 137926 and press Enter
  14. For the Counter Reading End, type 188420
    ===========================================================
    Stellar Water Point - Customer Invoice
    Account Type: Residential Household
    ===========================================================
    Counter Reading Start:         137926
    Counter Reading End:           188420
  15. Press Enter
    ===========================================================
    Stellar Water Point - Customer Invoice
    Account Type: Residential Household
    ===========================================================
    Meter Reading
    -----------------------------------------------------------
    Counter Reading Start:          137926
    Counter Reading End:            188420
    Total Gallons Consumed:          50494
    ===========================================================
    Therms Evaluation
    -----------------------------------------------------------
    HCF Total:                       67.51
    First 35 Therms (* 1.5573):      38.93
    First 20 Therms (* 1.2264):      18.40
    Above 40 Therms (* 0.9624):      26.47
    -----------------------------------------------------------
    Water Usage Charges:             83.80
    Sewer Charges:                   21.18
    ===========================================================
    Bill Values
    -----------------------------------------------------------
    Environment Charges:              0.21
    Service Charges:                  2.75
    Total Charges:                  107.94
    Local Taxes:                     12.41
    State Taxes:                      3.78
    -----------------------------------------------------------
    Amount Due:                     124.13
    ===========================================================
    Press any key to close this window . . .
  16. Close the window and return to your programming environment
  17. Close your programming environment

Previous Copyright © 2001-2024, FunctionX Saturday 04 June 2022 Next