On this page
Hello, World! Console Application in C#
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:
- .NET SDK for your operating system
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
- Navigate to the directory where you want to create your project.
cd path/to/your/directory
- 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
- Change directory to
HelloWorld
:
cd HelloWorld
- List the files in the directory to confirm the project files are created:
dir # Use `dir` command
On Linux/macOS
- Change directory to
HelloWorld
:
cd HelloWorld
- 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
- 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
- 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
- Back in the terminal, build and run the application:
dotnet run
You should see the output:
Hello, World!