Introduction
Let us learn the C# program structure with a simple “HelloWorld” program.
Every C# program entails the following things.
- Namespace declaration
- A Class
- Class methods
- Class attributes
- The Main method
- Statements and Expressions
- Comments
Now, let's see a simple "Hello World" program.
- using System;
- namespace HelloCSharp {
- class prog1HelloWorld {
- static void Main(string[] args) {
-
- Console.WriteLine("Hello World");
- Console.WriteLine(“Press a key…”);
- Console.ReadLine();
- }
- }
- }
After compilation and execution of this code, it produces the following result.
Hello World
Now, let’s explore the parts of the program.
- using System
This "using" keyword is used to contain the System namespace in the program. Every program has multiple using statements.
- namespace declaration
It’s a collection of classes. The HelloCSharp namespace contains the class prog1HelloWorld.
- class declaration
The class prog1HelloWorld contains the data and method definitions that your program uses and Classes always contain multiple methods. Methods define the behavior of the class. Though, the HelloWorld class has only one method Main.
- defines the Main method
This is the entry point for all C# programs. The main method states what the class does when executed.
/*...*/
This is ignored by the compiler and put to add comments in the program. The main method specifies its behavior with the statement Console.WriteLine("Hello World");
- WriteLine
It’s a method of the Console class distinct in the System namespace. This statement causes the message "Hello, World!" to be displayed on the screen.
- Console.ReadLine()
This is for the VS.NET Users. This makes the program wait for a key press.
Main things in C#
- C# is case sensitive.
- C# program execution starts at the Main method.
- All C# expression and statements must end with a semicolon (;).
- File name is different from the class name. This is unlike Java.
Compiling and Executing the Program
Following these steps: (using Visual Studio)
- Open the Visual Studio.
- On the menu bar, choose File -> New -> Project.
- Choose Visual C# from templates, and then choose Windows.
- And then choose Console Application.
- Give a name for this project.
- Click OK button.
- This creates a new project in Solution Explorer.
- Now, go to write code in the Code Editor.
- After writing the code, press F5 key to execute the project. A Command Prompt window appears that contains the line Hello World.
Summary
I hope you understood about C# program structure.