net-core
  1. net-core-console-class-basics

Console Class Basics - (.NET Core Console Applications)

In this page, we will discuss the basics of the Console class in .NET Core console applications. The Console class is a static class in the System namespace that provides a way to read input and write output to the console.

Syntax

The syntax for using the Console class is straightforward. Here is the syntax for writing output to the console:

Console.WriteLine("Your output text here");

Here is the syntax for reading input from the console:

string userInput = Console.ReadLine();

Example

Here is an example that uses the Console class to write output to the console and read input from the user:

using System;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter your name:");
            string name = Console.ReadLine();
            Console.WriteLine("Hello, " + name + "!");
        }
    }
}

Output

The output of the above example will be:

Please enter your name:
John
Hello, John!

Explanation

In the example above, the program prompts the user to enter their name using the Console.WriteLine() method. The program then reads the user's input with the Console.ReadLine() method and stores it in the name variable. Finally, the program writes a personalized greeting to the console using the Console.WriteLine() method.

Use

The Console class is commonly used in .NET Core console applications to provide a way to read user input and write program output to the console. It is useful for creating simple command-line tools and utilities.

Important Points

  • The Console class is a static class in the System namespace.
  • The Console.WriteLine() method is used to write output to the console.
  • The Console.ReadLine() method is used to read input from the console.

Summary

In this page, we discussed the basics of using the Console class in .NET Core console applications. We covered the syntax, example, output, explanation, use, and important points of the Console class. By using the Console class, you can build simple command-line tools and utilities that interact with the user via the console.

Published on: