Let’s write and run a simple program in C#. This program will print “Hello, World!” to the console—our first C# program!
It’s a very basic example, but it helps us verify that everything is installed correctly, and… we have to start somewhere 😊.
Creating the Program in Visual Studio
We can use Visual Studio to create our first application. In this simple case, we are going to use a console application. To do this,
- Open Visual Studio and select Create a new project.
- Select Console Application.
- Give your project a name (for example,
HelloWorld
) and select the folder where it will be saved. Click on Create.
This process will create a basic template of a C# program in your new project.
Writing Our First Program
With our project already created, we open the file Program.cs
, selecting it in the Solution Explorer.
In this file, we write the following code,
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
}
Let’s Break It Down
using: The line
using System;
indicates that the program will use theSystem
namespace, which contains fundamental classes of the .NET Framework such asConsole
.Namespace:
namespace HelloWorld
defines a namespace that organizes the code and avoids name conflicts between different parts of the program.Class:
class Program
declares a class calledProgram
. In C#, all code must be contained within a class.Main Method:
static void Main(string[] args)
is the entry point of the program. Every C# program must have aMain
method, which is where execution begins.Statement:
Console.WriteLine("Hello, World!");
is a statement that prints text to the console. Statements in C# end with a semicolon (;
).
Don’t worry about each detail for now. We will go through them gradually in the rest of the course.
Running the Project
To run the project in Visual Studio, select the Start button or press Ctrl + F5
. This will compile and run the program, displaying the phrase in the console:
Hello, World!
If everything is installed correctly, you should see “Hello, World!” in the console. Congratulations! 👏🥳.
Creating the Program from .NET CLI
We can also create and run the project using .NET CLI. To do this, open a terminal, navigate to your project folder, and type:
dotnet new console -o HelloWorld
To run the project, we can use,
dotnet run
Finally, to build the project, we can do,
dotnet build
These commands are useful for creating projects, compiling code, and running it directly from the terminal without the need to open the IDE.
The .NET Command-Line Interface (CLI) is a useful tool for creating and managing projects in C#.
Although Visual Studio and Visual Studio Code automatically handle many aspects of project management, the CLI is very helpful in some advanced contexts.