In this tutorial, we will learn how to write a simple "Hello World!" program in C#.
C# is a modern, high-level, general-purpose, object-oriented programming language. It is the principal language of the .NET framework. It supports functional, procedural, generic, object-oriented, and component-oriented programming disciplines.
In order to work with .NET, we need to download and install .NET SDK. The .NET 5 supports C# 9.0.
After installing .NET SDK, we can build our first C# program.
C# Hello World Program
Here is our C# Hello World program. It will print a "Hello World!" message to the console. We will explain it line by line.
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
When you run the program, the output will be:
Hello World!
Let's understand the above simple C# program line by line.
The using keyword imports a specific namespace to our program. Namespaces are created to group and/or distinguish named entities from other ones. This prevents name conflicts. This line is a C# statement. Each statement is ended with a semicolon.
using System;
We declare a namespace. Namespaces are used to organize code and to prevent name clashes:
namespace Simple
{
}
Each C# program is structured. It consists of classes and its members. A class is a basic building block of a C# program. The above code is a class definition. The definition has a body, which starts with a left curly brace ({) and ends with a right curly brace (}):
class Program
{
...
}
The Main is a method. A method is a piece of code created to do a specific job. Instead of putting all code into one place, we divide it into pieces, called methods. This brings modularity to our application. Each method has a body, in which we place statements. The body of a method is enclosed by curly brackets:
static void Main(string[] args)
{
...
}
In this code line, we print the "Hello World!" string to the console. To print a message to the console, we use the WriteLine method of the Console class:
Console.WriteLine("Hello World!");
Comments
Post a Comment