#1 – C# Hello World with .NET CLI

In this short tutorial, you will learn how to create and run C# Hello Word with .NET CLI.

Install .NET SDK

The latest version of .NET is .NET 5.0 and .NET 6 preview 3 is also available.

Go to official download site, choose the OS and download the latest version .NET SDK. After installing the SDK you can run following commands to check the installation.

$ dotnet --version
$ dotnet --list-sdks

Create Hello World Program

Create Hello World program with following command:

$ dotnet new console -o HelloWorld

It will create a project file HelloWorld.csproj and a Program.cs file

Project File

HelloWorld.csproj

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net5.0</TargetFramework>
  </PropertyGroup>

</Project>

Key Points:

  • The Sdk attribute specifies the SDK that is used by the project. Microsoft ships two main SDKs: Microsoft.NET.Sdk for console applications, and Microsoft.NET.Sdk.Web for ASP.NET Core web applications.
  • You don’t need to add source files to the project. Files with the .cs extension in the same directory and subdirectories are automatically added for compilation. Resource files with the .resx extension are automatically added for embedding the resource. You can change the default behavior and exclude/include files explicitly.
  • You also don’t need to add the .NET packages. By specifying the target framework net5.0, the metapackage Microsoft.NetCore.App that references many other packages is automatically included.

Main Method File

The Main method is the entry point for a .NET application. The CLR invokes a static Main method on startup. The Main method needs to be put into a class. Here, the class is named Program, but you could call it by any name.

Program.cs

using System;

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

Build and Run

You can directly run the program by following commands:

$ cd HelloWorld/
$ dotnet run

You also can build the project first and then run the binary by:

$ dotnet build
$ dotnet ./bin/Debug/net5.0/HelloWorld.dll 

One Reply to “#1 – C# Hello World with .NET CLI”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.