In the previous tutorial, we’ve learnt about the basics of C#. If you’re new to c# & haven’t learnt about the basics of C#, then please check out reference to C# before you dive in programming. Now, lets dive into the programming with C#. In this tutorial, we’ll be doing “Hello World” program in C#. As we know, “Hello World” is often the 1st program when we start any programming language. Actually, it is a simple program that just prints out “Hello World” as output of the program.
“Hello World” in C#
// Hello World program namespace HelloWorld { class Hello { static void Main(string[] args) { System.Console.WriteLine("Hello World"); } } }
Output:
HelloWorld
Explaination:
Lets go through the program line by line.
1. // Hello World! Program
// means the beginning of a comment in C#. C# compiler doesn’t execute the comments. They’re just line of message/comment/reminder that developers use to understand the piece of code.
2. namespace HelloWorld{…}
The keyword, namespace is used to define our namespace.It consists of classes, methods and other namespaces. Here, in above program, we’ve created a namespace called HelloWorld.
3. class Hello{…}
In OOP, it is compulsory to have a main() class. Since, C# is OOOP, we’ve created a class named – Hello in above program.
4. static void Main(string[] args){…}
The main() is the methode of class Hello. It is compulsory to have main() to inorder to execute C# program.
5. System.Console.WriteLine("Hello World!");
It is just the piece of code that prints out the result. Here, in above program, it prints “Hello World”.
Alternative method
Have a look at the 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!"); } } }
In this program, did you notice that we’ve written using System; at the start of the program. Using this, now we can replace
System.Console.WriteLine("Hello World!");
with
Console.WriteLine("Hello World!");
This is a convenience & we’ll be using in our later tutorials as well.
IDE for CS - Visual Studio