Program Structure Of C#

 Introduction

Let us learn the C# program structure with a simple “HelloWorld” program.

Every C# program entails the following things.
  1. Namespace declaration
  2. A Class
  3. Class methods
  4. Class attributes
  5. The Main method
  6. Statements and Expressions
  7. Comments
Now, let's see a simple "Hello World" program.
  1. using System;  
  2. namespace HelloCSharp {  
  3.     class prog1HelloWorld {  
  4.         static void Main(string[] args) {  
  5.             /* prog1 Hello World*/  
  6.             Console.WriteLine("Hello World");  
  7.             Console.WriteLine(“Press a key…”);  
  8.             Console.ReadLine();  
  9.         }  
  10.     }  
  11. }  
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.
Next Recommended Reading C# LINQ Joins With Query Structure