HTML
CSS
C#
SQL

Introduction to C#

Console applications are programs that run in a text-based interface, such as a command prompt or a terminal. They are useful for testing, debugging, and performing simple tasks that do not require a graphical user interface. To create and interact with console applications in C#, we can use the Console class, which is part of the System namespace. The Console class provides various methods and properties that allow us to read input from the keyboard, write output to the screen, and manipulate the appearance and behavior of the console window.

Writing Output to the Console

One of the most common tasks in console applications is to display some information or messages on the screen. To do this, we can use the Write and WriteLine methods of the Console class. Both methods take a string argument and write it to the standard output stream, which is usually the console window. The difference between them is that the WriteLine method also appends a new line character at the end of the string, which moves the cursor to the next line. The Write method does not add a new line character, so the cursor stays at the same line.

We can also use the Write and WriteLine methods to write the value of a variable to the console. For example, if we have an integer variable called x, we can write its value using Console.Write(x) or Console.WriteLine(x). The methods will automatically convert the value to a string before writing it to the output stream. We can also use placeholders and format specifiers to write multiple values or format the output in a specific way. For example, Console.WriteLine(“The value of x is {0}”, x) will write “The value of x is 10” if x is 10.

Reading Input from the Console

Another common task in console applications is to get some input from the user through the keyboard. To do this, we can use the Read, ReadLine, and ReadKey methods of the Console class. Each method has a different way of reading and returning the input.

– The Read method reads a single character from the keyboard and returns its ASCII value as an integer. For example, if the user presses the A key, the Read method will return 65, which is the ASCII code of A. If the user presses the Enter key, the Read method will return -1, which indicates the end of input. The Read method blocks the execution of the program until the user presses a key.

– The ReadLine method reads a line of text from the keyboard and returns it as a string. For example, if the user types “Hello” and presses the Enter key, the ReadLine method will return “Hello”. The ReadLine method also blocks the execution of the program until the user presses the Enter key.

– The ReadKey method reads a single key press from the keyboard and returns a ConsoleKeyInfo object, which contains information about the key, such as the key code, the key character, and the modifier keys (such as Shift, Ctrl, or Alt). For example, if the user presses the A key, the ReadKey method will return a ConsoleKeyInfo object with the Key property set to ConsoleKey.A, the KeyChar property set to ‘A’, and the Modifiers property set to 0. The ReadKey method does not block the execution of the program until the user presses the Enter key, but it does echo the key press to the console.

Changing the Appearance and Behavior of the Console

The Console class also provides some properties and methods that allow us to change the appearance and behavior of the console window, such as the background color, the foreground color, the cursor size, the title, and the sound. Some of these properties and methods are:

– The BackgroundColor property gets or sets the background color of the console, which is the color that appears behind each character. The default value is black. The property takes a ConsoleColor enumeration value as an argument, which represents one of the 16 possible colors that the console can display.

– The ForegroundColor property gets or sets the foreground color of the console, which is the color of each character that is displayed. The default value is gray. The property takes a ConsoleColor enumeration value as an argument, which represents one of the 16 possible colors that the console can display.

– The CursorSize property gets or sets the height of the cursor within a character cell, expressed as a percentage of the cell height. The property value ranges from 1 to 100. The default value is 25. A larger value makes the cursor more visible, while a smaller value makes the cursor less visible.

– The Title property gets or sets the title to display in the console title bar. The property takes a string argument, which can be up to 24500 characters long. The default value is the name of the executable file that started the program.

– The Beep method plays the sound of a beep through the console speaker. The method takes two integer arguments, which specify the frequency and the duration of the beep in hertz and milliseconds, respectively. The frequency value ranges from 37 to 32767, and the duration value ranges from 0 to int.MaxValue. The default values are 800 and 200, respectively.

Examples of Console Class in C#

The following examples demonstrate how to use some of the methods and properties of the Console class in C#. The examples are self-explanatory, so please read the comments in the code for more details.

Example 1: Writing Output to the Console

using System;

 

namespace ConsoleDemo

{

    class Program

    {

        static void Main(string[] args)

        {

            // Declare and initialize some variables

            int x = 10;

            double y = 3.14;

            string name = “Alice”;

 

            // Write a string to the console using the Write method

            Console.Write(“Hello, “);

 

            // Write the value of a variable to the console using the Write method

            Console.Write(name);

 

            // Write a new line character to the console using the Write method

            Console.Write(“\n”);

 

            // Write a string to the console using the WriteLine method

            Console.WriteLine(“Welcome to C#”);

 

            // Write the value of a variable to the console using the WriteLine method

            Console.WriteLine(x);

 

            // Write multiple values to the console using placeholders and the WriteLine method

            Console.WriteLine(“The value of x is {0} and the value of y is {1}”, x, y);

 

            // Write a formatted string to the console using format specifiers and the WriteLine method

            Console.WriteLine(“The value of y with two decimal places is {0:F2}”, y);

        }

    }

}

The output of the program is:

Hello, Alice

Welcome to C#

10

The value of x is 10 and the value of y is 3.14

The value of y with two decimal places is 3.14

Example 2: Reading Input from the Console

using System;

 

namespace ConsoleDemo

{

    class Program

    {

        static void Main(string[] args)

        {

            // Declare some variables

            int a, b, sum;

            string input;

 

            // Prompt the user to enter two numbers

            Console.WriteLine(“Enter two numbers:”);

 

            // Read the first number as a string using the ReadLine method

            input = Console.ReadLine();

 

            // Convert the string to an integer using the Convert.ToInt32 method

            a = Convert.ToInt32(input);

 

            // Read the second number as a string using the ReadLine method

            input = Console.ReadLine();

 

            // Convert the string to an integer using the Convert.ToInt32 method

            b = Convert.ToInt32(input);

 

            // Calculate the sum of the two numbers

            sum = a + b;

 

            // Write the sum to the console using the WriteLine method

            Console.WriteLine(“The sum is {0}”, sum);

 

            // Prompt the user to press any key

            Console.WriteLine(“Press any key to continue…”);

 

            // Read a single key press from the keyboard using the ReadKey method

            ConsoleKeyInfo key = Console.ReadKey();

 

            // Write the key information to the console using the WriteLine method

            Console.WriteLine(“\nYou pressed {0} (character

The output of the program is:

Enter two numbers:

5

6

The sum is 11

Press any key to continue…

a

You pressed A (character ‘a’)

Example 3: Changing the Appearance and Behavior of the Console

using System;

 

namespace ConsoleDemo

{

    class Program

    {

        static void Main(string[] args)

        {

            // Set the title of the console window using the Title property

            Console.Title = “Console Demo”;

 

            // Set the background color of the console to blue using the BackgroundColor property

            Console.BackgroundColor = ConsoleColor.Blue;

 

            // Set the foreground color of the console to white using the ForegroundColor property

            Console.ForegroundColor = ConsoleColor.White;

 

            // Clear the console screen using the Clear method

            Console.Clear();

 

            // Write a message to the console using the WriteLine method

            Console.WriteLine(“Hello, World!”);

 

            // Set the cursor size to 50% using the CursorSize property

            Console.CursorSize = 50;

 

            // Move the cursor to the next line using the WriteLine method

            Console.WriteLine();

 

            // Play a beep sound using the Beep method

            Console.Beep();

 

            // Reset the console colors to their defaults using the ResetColor method

            Console.ResetColor();

 

            // Write a message to the console using the WriteLine method

            Console.WriteLine(“Goodbye, World!”);

        }

    }

The output of the program is:

Hello, World!

Goodbye, World!

Course Video