Before we learn how to program in C#, we must first know about the sections of C# program. We must know every part of the program. This will help us know about code placement and it will be easier for us to write a program. So, let us look at a basic program in C# to understand different sections of C# program.
When the above program is complied, we get the following output:
Hello
A basic C# program consists of following sections.
using directive
using directive is located in first line of the program. It is used to allow the use of types in namespace. A C# program can and generally have multiple using statements.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;
Namespace declaration
Namespace declaration is situated below using directives which was designed for keeping one set of name separate from another.
It is a collection of classes. In above example, Hello is the class of HelloApplication namespace.
Class
A class is defined using keyword class and followed by class name. It is used to declare a class and the class body is enclosed by curly braces {…}. It contains data and methods that a program uses. For example:
Hello is the class and main is a method.
class Hello { static void Main(string[] args) { /* hello program in C# */ Console.WriteLine("Hello"); Console.ReadLine(); } }
Main method
The main() method is starting point for our program. It states what the class does when executed. For example:
static void Main(string[] args)
Contents of the Main method (Expressions & Statements)
In Main method, we write any statements or expressions and they get executed when the program runs. Expressions are set of codes which evaluates the values whereas statements are lines of code which are meant to be executed for a specific action. These expressions and statements must end with a semicolon “;“. For example:
/* hello program in C# */ Console.WriteLine("Hello"); Console.ReadLine();
Comments
Comments are used to leave a note within a program. They are ignored by the compiler when compiling the program. For example:
/* hello program in C# */
We can use “//” for single line comments.
//single line comment
Or, we can use “/*…..*/” for multiple line comments.
/* multiple line comment */