Home

Data Reading and Writing on the Console

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. The Console class is defined in the System 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.

Practical LearningPractical Learning: Introducing the Console

  1. Launch Microsoft Visual Studio. On the Visual Studio 2019 dialog box, click Create a New Project
  2. In the list of projects templates, click Console App (.NET Framework)
  3. Click Next
  4. Change the Name to GeorgetownDryCleaningServices6
  5. Click Create

Writing to the Console

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

public class Exercise
{
    static void Main()
    {
    	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:
    namespace GeorgetownDryCleaningServices6
    {
        public class Program
        {
            public static int Main()
            {
                System.Console.WriteLine("-/- Georgetown Dry Cleaning Services -/-");
    
                return 0;
            }
        }
    }
  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

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 namspace:

public class Exercise
{
    public static int Main()
    {
    	System.Console.WriteLine("The Wonderful World of C# Programming");

        return 10;
    }
}

As you may know by now, you can also include the namespace in a using section. Here is an example:

using System;

public class Exercise
{
    public static int Main()
    {
    	Console.WriteLine("The Wonderful World of C# Programming");

        return 1001;
    }
}

Finally, 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. Here is an example:

using static System.Console;

public class Exercise
{
    public static int Main()
    {
        WriteLine("The Wonderful World of C# Programming");

        return 10101;
    }
}

Practical LearningPractical Learning: Accessing the Static Members

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:

using System;

public class Exercise
{
    static int Main()
    {
        ConsoleKeyInfo cki = new ConsoleKeyInfo();

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

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

        Console.ReadKey();
        return 0;
    }
}

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:

using System;
using static System.Console;

public class Exercise
{
    static int Main()
    {
        ConsoleKeyInfo cki = new ConsoleKeyInfo();

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

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

        ReadKey();
        return 20;
    }
}

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:

using System;

public class Exercise
{
    public static int Main()
    {
        Console.Title = "Department Store";

        return 2002;
    }
}

Title

Practical LearningPractical Learning: Naming a Console Window

  1. Change the code as follows:
    using static System.Console;
    
    namespace GeorgetownDryCleaningServices6
    {
        public class Program
        {
            public static int Main()
            {
                Title = "Georgetown Dry Cleaning Services";
                WriteLine("-/- Georgetown Dry Cleaning Services -/-");
    
                return 0;
            }
        }
    }
  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:
    using static System.Console;
    
    namespace GeorgetownDryCleaningServices6
    {
        public class Program
        {
            public static int Main()
            {
                string customerName, homePhone;
    
                Title = "Georgetown Dry Cleaning Services";
                WriteLine("-/- Georgetown Dry Cleaning Services -/-");
    
                // Request customer information from the user
    
                // Display the receipt
                WriteLine("====================================");
                WriteLine("-/- Georgetown Dry Cleaning Services -/-");
                WriteLine("====================================");
                Write("Customer:   ");
                WriteLine(customerName);
                Write("Home Phone: ");
                WriteLine(homePhone);
                WriteLine("====================================\n");
    
                return 0;
            }
        }
    }

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 (or any of the variables we will see in this lesson), 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:

using System;

public class Exercise
{
    public static void Main()
    {
        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:
    using static System.Console;
    
    namespace GeorgetownDryCleaningServices6
    {
        public class Program
        {
            public static int Main()
            {
                string customerName, homePhone;
    
                Title = "Georgetown Dry Cleaning Services";
                WriteLine("-/- Georgetown Dry Cleaning Services -/-");
    
                // Request customer information from the user
                Write("Enter Customer Name:  ");
                customerName = ReadLine();
                Write("Enter Customer Phone: ");
                homePhone = ReadLine();
    
                Clear();
    
                // Display the receipt
                WriteLine("====================================");
                WriteLine("-/- Georgetown Dry Cleaning Services -/-");
                WriteLine("====================================");
                Write("Customer:   ");
                WriteLine(customerName);
                Write("Home Phone: ");
                WriteLine(homePhone);
                WriteLine("====================================\n");
    
                return 0;
            }
        }
    }
  2. Execute the program. When asked to provide a customer name, type a name, such as James Watson:
  3. Press Enter
  4. When asked to provide a phone number, type something, such as (410) 493-2005

    Title

  5. Press Enter:

    Title

  6. 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;

public class Exercise
{
    public static int Main()
    {
        int number;
        string strNumber;

        strnumber = ReadLine();
        
        return 2020;
    }
}

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:

using System;

public class Exercise
{
    public static void Main()
    {
        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:

using System;

public class Exercise
{
    public static int Main()
    {
        int number;

        number = int.Parse(Console.ReadLine());
        
        return 0;
    }
}

Practical LearningPractical Learning: Reading Numeric Values

  1. To retrieve various numbers from the user, change the file as follows:
    using static System.Console;
    
    namespace GeorgetownDryCleaningServices6
    {
        public class Program
        {
            public static int Main()
            {
                // 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%
    
                // Customer personal infoirmation
                string customerName, homePhone;
                // Unsigned numbers to represent cleaning items
                uint numberOfShirts, numberOfPants, numberOfDresses;
                // Each of these sub totals will be used for cleaning items
                double subTotalShirts, subTotalPants, subTotalDresses;
                // Values used to process an order
                double totalOrder, taxAmount, salesTotal;
                double amountTended, moneyChange;
    
                Title = "Georgetown Dry Cleaning Services";
                WriteLine("-/- Georgetown Dry Cleaning Services -/-");
    
                // Request customer information from the user
                Write("Enter Customer Name:  ");
                customerName = ReadLine();
                Write("Enter Customer Phone: ");
                homePhone = ReadLine();
    
                // Request the quantity of each category of items
                Write("Number of Shirts:  ");
                string strShirts = ReadLine();
                numberOfShirts = uint.Parse(strShirts);
    
                Write("Number of Pants:   ");
                string strPants = ReadLine();
                numberOfPants = uint.Parse(strPants);
    
                Write("Number of Dresses: ");
                string strDresses = ReadLine();
                numberOfDresses = uint.Parse(strDresses);
    
                // Perform the necessary calculations
                subTotalShirts = numberOfShirts * PriceOneShirt;
                subTotalPants = numberOfPants * PriceAPairOfPants;
                subTotalDresses = numberOfDresses * PriceOneDress;
                // Calculate the "temporary" total of the order
                totalOrder = subTotalShirts + subTotalPants + subTotalDresses;
    
                // Calculate the tax amount using a constant rate
                taxAmount = totalOrder * TaxRate;
                // Add the tax amount to the total order
                salesTotal = totalOrder + taxAmount;
    
                // Communicate the total to the user...
                Write("\nThe Total order is: ");
                WriteLine(salesTotal);
                // and request money for the order
                Write("Amount Tended? ");
                amountTended = double.Parse(ReadLine());
    
                // Calculate the difference owed to the customer
                // or that the customer still owes to the store
                moneyChange = amountTended - salesTotal;
    
                Clear();
    
                // Display the receipt
                WriteLine("====================================");
                WriteLine("-/- Georgetown Dry Cleaning Services -/-");
                WriteLine("====================================");
                Write("Customer:   ");
                WriteLine(customerName);
                Write("Home Phone: ");
                WriteLine(homePhone);
                WriteLine("------------------------------------");
                WriteLine("Item Type  Qty Unit/Price Sub-Total");
                WriteLine("------------------------------------");
                Write("Shirts      ");
                Write(numberOfShirts);
                Write("     ");
                Write(PriceOneShirt);
                Write("     ");
                WriteLine(subTotalShirts);
                Write("Pants       ");
                Write(numberOfPants);
                Write("     ");
                Write(PriceAPairOfPants);
                Write("     ");
                WriteLine(subTotalPants);
                Write("Dresses     ");
                Write(numberOfDresses);
                Write("     ");
                Write(PriceOneDress);
                Write("     ");
                WriteLine(subTotalDresses);
                WriteLine("------------------------------------");
                Write("Total Order:     ");
                WriteLine(totalOrder);
                Write("Tax Rate:        ");
                Write(TaxRate * 100);
                WriteLine('%');
                Write("Tax Amount:      ");
                WriteLine(taxAmount);
                Write("Net Price:       ");
                WriteLine(salesTotal);
                WriteLine("------------------------------------");
                Write("Amount Tended:   ");
                WriteLine(amountTended);
                Write("Difference:      ");
                WriteLine(moneyChange);
                WriteLine("====================================\n");
    
                return 0;
            }
        }
    }
        {
            // 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%
    
            // Customer personal infoirmation
            string customerName, homePhone;
            // Unsigned numbers to represent cleaning items
            uint numberOfShirts, numberOfPants, numberOfDresses;
            // Each of these sub totals will be used for cleaning items
            double subTotalShirts, subTotalPants, subTotalDresses;
            // Values used to process an order
            double totalOrder, taxAmount, salesTotal;
            double amountTended, moneyChange;
    
            Title = "Georgetown Dry Cleaning Services";
            WriteLine("-/- Georgetown Dry Cleaning Services -/-");
    
            // Request customer information from the user
            Write("Enter Customer Name:  ");
            customerName = ReadLine();
            Write("Enter Customer Phone: ");
            homePhone = ReadLine();
    
            // Request the quantity of each category of items
            Write("Number of Shirts:  ");
            string strShirts = ReadLine();
            numberOfShirts = uint.Parse(strShirts);
    
            Write("Number of Pants:   ");
            string strPants = ReadLine();
            numberOfPants = uint.Parse(strPants);
    
            Write("Number of Dresses: ");
            string strDresses = ReadLine();
            numberOfDresses = uint.Parse(strDresses);
    
            // Perform the necessary calculations
            subTotalShirts = numberOfShirts * PriceOneShirt;
            subTotalPants = numberOfPants * PriceAPairOfPants;
            subTotalDresses = numberOfDresses * PriceOneDress;
            // Calculate the "temporary" total of the order
            totalOrder = subTotalShirts +
                      subTotalPants +
                      subTotalDresses;
    
            // Calculate the tax amount using a constant rate
            taxAmount = totalOrder * TaxRate;
            // Add the tax amount to the total order
            salesTotal = totalOrder + taxAmount;
    
            // Communicate the total to the user...
            Write("\nThe Total order is: ");
            WriteLine(salesTotal);
            // and request money for the order
            Write("Amount Tended? ");
            amountTended = double.Parse(ReadLine());
    
            // Calculate the difference owed to the customer
            // or that the customer still owes to the store
            moneyChange = amountTended - salesTotal;
    
            Clear();
    
            // Display the receipt
            WriteLine("====================================");
            WriteLine("-/- Georgetown Dry Cleaning Services -/-");
            WriteLine("====================================");
            Write("Customer:   ");
            WriteLine(customerName);
            Write("Home Phone: ");
            WriteLine(homePhone);
            WriteLine("------------------------------------");
            WriteLine("Item Type  Qty Unit/Price Sub-Total");
            WriteLine("------------------------------------");
            Write("Shirts      ");
            Write(numberOfShirts);
            Write("     ");
            Write(PriceOneShirt);
            Write("     ");
            WriteLine(subTotalShirts);
            Write("Pants       ");
            Write(numberOfPants);
            Write("     ");
            Write(PriceAPairOfPants);
            Write("     ");
            WriteLine(subTotalPants);
            Write("Dresses     ");
            Write(numberOfDresses);
            Write("     ");
            Write(PriceOneDress);
            Write("     ");
            WriteLine(subTotalDresses);
            WriteLine("------------------------------------");
            Write("Total Order:     ");
            WriteLine(totalOrder);
            Write("Tax Rate:        ");
            Write(TaxRate * 100);
            WriteLine('%');
            Write("Tax Amount:      ");
            WriteLine(taxAmount);
            Write("Net Price:       ");
            WriteLine(salesTotal);
            WriteLine("------------------------------------");
            Write("Amount Tended:   ");
            WriteLine(amountTended);
            Write("Difference:      ");
            WriteLine(moneyChange);
            WriteLine("====================================\n");
    
            ReadKey();
            return 0;
        }
    }
  2. Execute the program and test it. Here is an example:

    Title

    Title

    Title

    Title

    Title

  3. 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 the Write() 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 strings to the Write() or the WriteLine() methods and separate them with a comma:

  1. The first part of the string provided to Write() or WriteLine() is the complete string that would display to the user. This first string itself can 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 part of the string provided to the Write() or the WriteLine() method is the value you want to display. It can be one value if you used only one placeholder with 0 in the first string. 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:

using System;

public class Exercise
{
    public static void Main()
    {
        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:
    using static System.Console;
    
    namespace GeorgetownDryCleaningServices6
    {
        public class Program
        {
            public static int Main()
            {
                // 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%
    
                // Customer personal infoirmation
                string customerName, homePhone;
                // Unsigned numbers to represent cleaning items
                uint numberOfShirts, numberOfPants, numberOfDresses;
                // Each of these sub totals will be used for cleaning items
                double subTotalShirts, subTotalPants, subTotalDresses;
                // Values used to process an order
                double totalOrder, taxAmount, salesTotal;
                double amountTended, moneyChange;
    
                Title = "Georgetown Dry Cleaning Services";
                WriteLine("-/- Georgetown Dry Cleaning Services -/-");
    
                // Request customer information from the user
                Write("Enter Customer Name:  ");
                customerName = ReadLine();
                Write("Enter Customer Phone: ");
                homePhone = ReadLine();
    
                // Request the quantity of each category of items
                Write("Number of Shirts:  ");
                string strShirts = ReadLine();
                numberOfShirts = uint.Parse(strShirts);
    
                Write("Number of Pants:   ");
                string strPants = ReadLine();
                numberOfPants = uint.Parse(strPants);
    
                Write("Number of Dresses: ");
                string strDresses = ReadLine();
                numberOfDresses = uint.Parse(strDresses);
    
                // Perform the necessary calculations
                subTotalShirts = numberOfShirts * PriceOneShirt;
                subTotalPants = numberOfPants * PriceAPairOfPants;
                subTotalDresses = numberOfDresses * PriceOneDress;
                // Calculate the "temporary" total of the order
                totalOrder = subTotalShirts + subTotalPants + subTotalDresses;
    
                // Calculate the tax amount using a constant rate
                taxAmount = totalOrder * TaxRate;
                // Add the tax amount to the total order
                salesTotal = totalOrder + taxAmount;
    
                // Communicate the total to the user...
                Write("\nThe Total order is: ");
                WriteLine(salesTotal);
                // and request money for the order
                Write("Amount Tended? ");
                amountTended = double.Parse(ReadLine());
    
                // Calculate the difference owed to the customer
                // or that the customer still owes to the store
                moneyChange = amountTended - salesTotal;
    
                Clear();
    
                // Display the receipt
                WriteLine("====================================");
                WriteLine("-/- Georgetown Dry Cleaning Services -/-");
                WriteLine("====================================");
                WriteLine("Customer:   {0}", customerName);
                WriteLine("Home Phone: {0}", homePhone);
                WriteLine("------------------------------------");
                WriteLine("Item Type  Qty Unit/Price Sub-Total");
                WriteLine("------------------------------------");
                WriteLine("Shirts      {0}     {1}     {2}",
                          numberOfShirts, PriceOneShirt, subTotalShirts);
                WriteLine("Pants       {0}     {1}     {2}",
                          numberOfPants, PriceAPairOfPants, subTotalPants);
                WriteLine("Dresses     {0}     {1}     {2}",
                          numberOfDresses, PriceOneDress, subTotalDresses);
                WriteLine("------------------------------------");
                WriteLine("Total Order:     {0}", totalOrder);
                WriteLine("Tax Rate:        {0}%", TaxRate * 100);
                WriteLine("Tax Amount:      {0}", taxAmount);
                WriteLine("Net Price:       {0}", salesTotal);
                WriteLine("------------------------------------");
                WriteLine("Amount Tended:   {0}", amountTended);
                WriteLine("Difference:      {0}", moneyChange);
                WriteLine("====================================\n");
    
                return 0;
            }
        }
    }
  2. To execute the program and test it, press Ctrl + F5
  3. Close the console window 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:

using System;

public class Exercise
{
    public static void Main()
    {
        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());

        Console.WriteLine();
    }
}

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:

using System;

public class Exercise
{
    public static void Main()
    {
        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"));

        Console.WriteLine();
    }
}

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:
    using static System.Console;
    
    namespace GeorgetownDryCleaningServices6
    {
        public class Program
        {
            public static int Main()
            {
                // 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%
    
                // Customer personal infoirmation
                string customerName, homePhone;
                // Unsigned numbers to represent cleaning items
                uint numberOfShirts, numberOfPants, numberOfDresses;
                // Each of these sub totals will be used for cleaning items
                double subTotalShirts, subTotalPants, subTotalDresses;
                // Values used to process an order
                double totalOrder, taxAmount, salesTotal;
                double amountTended, moneyChange;
    
                Title = "Georgetown Dry Cleaning Services";
                WriteLine("-/- Georgetown Dry Cleaning Services -/-");
    
                // Request customer information from the user
                Write("Enter Customer Name:  ");
                customerName = ReadLine();
                Write("Enter Customer Phone: ");
                homePhone = ReadLine();
    
                // Request the quantity of each category of items
                Write("Number of Shirts:  ");
                string strShirts = ReadLine();
                numberOfShirts = uint.Parse(strShirts);
    
                Write("Number of Pants:   ");
                string strPants = ReadLine();
                numberOfPants = uint.Parse(strPants);
    
                Write("Number of Dresses: ");
                string strDresses = ReadLine();
                numberOfDresses = uint.Parse(strDresses);
    
                // Perform the necessary calculations
                subTotalShirts = numberOfShirts * PriceOneShirt;
                subTotalPants = numberOfPants * PriceAPairOfPants;
                subTotalDresses = numberOfDresses * PriceOneDress;
                // Calculate the "temporary" total of the order
                totalOrder = subTotalShirts + subTotalPants + subTotalDresses;
    
                // Calculate the tax amount using a constant rate
                taxAmount = totalOrder * taxRate;
                // Add the tax amount to the total order
                salesTotal = totalOrder + taxAmount;
    
                // Communicate the total to the user...
                Write("\nThe Total order is: ");
                WriteLine(salesTotal.ToString("F"));
                // and request money for the order
                Write("Amount Tended? ");
                amountTended = double.Parse(ReadLine());
    
                // Calculate the difference owed to the customer
                // or that the customer still owes to the store
                moneyChange = amountTended - salesTotal;
    
                Clear();
    
                // Display the receipt
                WriteLine("====================================");
                WriteLine("-/- Georgetown Dry Cleaning Services -/-");
                WriteLine("====================================");
                WriteLine("Customer:   {0}", customerName);
                WriteLine("Home Phone: {0}", homePhone);
                WriteLine("------------------------------------");
                WriteLine("Item Type  Qty Unit/Price Sub-Total");
                WriteLine("------------------------------------");
                WriteLine("Shirts      {0}     {1:F}     {2:C}",
                          numberOfShirts, PriceOneShirt, subTotalShirts);
                WriteLine("Pants       {0}     {1:F}     {2:F}",
                          numberOfPants, PriceAPairOfPants, subTotalPants);
                WriteLine("Dresses     {0}     {1}     {2}",
                          numberOfDresses, PriceOneDress.ToString("F"), subTotalDresses.ToString("C"));
                WriteLine("------------------------------------");
                WriteLine("Total Order:     {0:C}", totalOrder);
                WriteLine("Tax Rate:        {0:P}", taxRate);
                WriteLine("Tax Amount:      {0}", taxAmount.ToString("C"));
                WriteLine("Net Price:       {0}", salesTotal.ToString("C"));
                WriteLine("------------------------------------");
                WriteLine("Amount Tended:   {0:C}", amountTended);
                WriteLine("Difference:      {0}", moneyChange.ToString("C"));
                WriteLine("====================================\n");
    
                return 0;
            }
        }
    }
  2. To execute the application and test it, on the main menu, click Debug -> Start Without Debugging
  3. Enter some values as follows:
    Customer Name:     Shannon Hoft
    Customer Phone:    (202) 148-0726
    njumber of Shirts: 6
    Number of Pants:   6
    Number of Dresses: 4
    Amount Tended:     60

    Title

  4. Press Enter:

    Title

  5. 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:

using System;

public class Exercise
{
    public static void Main()
    {
        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: Ending the Lesson


Previous Copyright © 2001-2021, FunctionX Next