C# is a simple, modern, general-purpose, object-oriented programming language developed by Microsoft within its .NET initiative led by Anders Hejlsberg.
In this tutorial, we will learn how to write a simple “Hello World!” program in C#. This will get you familiar with the basic syntax and requirements of a C# program.
The “Hello World!” program is often the first program we see when we dive into a new language. It simply prints Hello World! on the output screen.
The purpose of this program is to get us familiar with the basic syntax and requirements of a programming language.
// Hello World! program
namespace HelloWorld
{
class Hello {
static void Main(string[] args)
{
System.Console.WriteLine("Hello World!");
}
}
}
When you run the program, the output will be:
Hello World!
Let’s break down the program line by line.
//
indicates the beginning of a comment in C#. Comments are not executed by the C# compiler.They are intended for the developers to better understand a piece of code.
The namespace keyword is used to define our own namespace. Here we are creating a namespace called HelloWorld.
Just think of namespace as a container which consists of classes, methods and other namespaces.
The above statement creates a class named - Hello in C#. Since, C# is an object-oriented programming language, creating a class is mandatory for the program’s execution.
Main() is a method of class Hello. The execution of every C# program starts from the Main() method. So it is mandatory for a C# program to have a Main() method.
The signature/syntax of the Main() method is:
static void Main(string[] args){
...
}
Here WriteLine() is a method of the Console class defined in the System namespace.
Here’s an alternative way to write the “Hello World!” program.
// Hello World! program
using System;
namespace HelloWorld
{
class Hello {
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
Notice in this case, we’ve written using System; at the start of the program. By using this, we can now replace
System.Console.WriteLine("Hello World!");
with
Console.WriteLine("Hello World!");
This is a convenience we’ll be using in our later problems as well.
Now that we have learned the basics of our code. Let’s solve a example in the editor below.
Write a code to print “Hello, InterviewBit!” (without quotes) in the editor below.