In this tutorial, we’ll walk through the steps to create a simple “Hello, World!” console application in C# using .NET Core CLI (dotnet).

Prerequisites

Before you begin, make sure you have the following installed:

Step 1: Open a Terminal (Command Prompt)

  • Windows: Open Command Prompt (cmd) or PowerShell.
  • Linux/macOS: Open your terminal application.

Step 2: Create a New Console Application

  1. Navigate to the directory where you want to create your project.
  cd path/to/your/directory
  
  1. Use the dotnet new command to create a new console application:
  dotnet new console -n HelloWorld
  
  • dotnet new console: Creates a new console application.
  • -n HelloWorld: Specifies the name of the project as HelloWorld. This command creates a folder named HelloWorld with the basic structure and files for a console application.

Step 3: Navigate to the Project Directory

On Windows

  1. Change directory to HelloWorld:
  cd HelloWorld
  
  1. List the files in the directory to confirm the project files are created:
  dir    # Use `dir` command
  

On Linux/macOS

  1. Change directory to HelloWorld:
  cd HelloWorld
  
  1. List the files in the directory to confirm the project files are created:
  ls    # On macOS and Linux use `ls` command
  

Step 4: Open and Modify Program.cs

  1. Open Program.cs in your preferred text editor or integrated development environment (IDE).
  code Program.cs    # Opens in Visual Studio Code, replace with your editor command
  
  1. Replace the content of Program.cs with the following C# code:
  
using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
        }
    }
}
  

Explanation of the code:

  • using System;: Imports the System namespace, which contains fundamental types and classes.
  • namespace HelloWorld { ... }: Defines a namespace named HelloWorld to organize your code.
  • class Program { ... }: Defines a class named Program.
  • static void Main(string[] args) { ... }: The entry point of the program. Main is a static method where program execution begins. It accepts an array of strings (args) as parameters.
  • Console.WriteLine("Hello, World!");: Prints “Hello, World!” to the console.

Step 5: Run the Application

  1. Back in the terminal, build and run the application:
  dotnet run
  

You should see the output:

  Hello, World!