Let’s see the first simple program in C# which prints Hello word on the console.
1 2 3 4 5 6 7 8 9 |
class FirstExample { static void Main (string[] args) { System.Console.WriteLine("Hello World "); } } |
Output
1 2 3 |
Hello World |
Description of the first Program:
- class: it’s a keyword which is used to define class. in C#, we have to define class first before main method .
- static: It is a keyword which is used to declare the class variable. We don’t need to create object to access static variable .
- void: void is a return type of the main method .
- Main: In C#, we have to write Main instead of main .
- string[] args: It is string array which is used to store the command line arguments. Writing this is optional.
- Console.WriteLine(“Hello World”): System is the name space. We are writing fully qualified name here. We could have used System name space before. WriteLine is the method used for writing on the console .
C# Example: using System namespace
In the first example, if we could have used System namespace then we didn’t need to write fully qualified name to access its method .
1 2 3 4 5 6 7 8 9 10 |
using System; class FirstExample { static void Main (string[] args) { Console.WriteLine("Hello World "); } } |
Output
1 2 3 |
Hello World |
C# Example : using public modifier
1 2 3 4 5 6 7 8 9 10 |
using System; public class FirstExample { public static void Main (string[] args) { Console.WriteLine("Hello World "); } } |
Output
1 2 3 |
Hello World |
C# Example: using Namespace
We can organize our classes and code in a namespace. It is a better way to organize your classes.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; using namespace FirstProgram { public class FirstExample { public static void Main (string[] args) { Console.WriteLine("Hello World "); } } } |
Output
1 2 3 |
Hello World |