Understanding our first program
Detailed explanation of the first program previously written in C#
Now is the time to understand the code. Let us begin with these three statements at the top of the code:
using System;
using System.Collections.Generic;
using System.Text;
These are namespaces that we are using in our code. A namespace is a logical collection of code, mainly classes. These classes itself contain different types of codes: properties, methods and events. These codes are predefined in the .NET Framework and we can use them just by including the related namespace. When we use a namespace in our program, we have access to all the classes in that namespace. This saves a lot of development time and makes the coding easier as much of the task is already done for us.
For example, the System.Text namespace contains the classes (and the codes) needed for working with characters. The `using' keyword indicates that we want to use this namespace in our code.
The .NET framework has many such namespaces for different purposes. The System.Data namespace, for example, contains the classes for data handling. All we need to do is to include the required namespace in our program to access the classes in that namespace.
Note: namespaces can contain other elements like interfaces, enumerators and structures apart from classes.
To use a namespace in program, use the following syntax:
using namespace;
For example:
using System.Data;
To include more than one namespace, write multiple statements, each on a separate line.
The next statement is:
namespace MyFirstApp
This is our own namespace. The name of the namespace is the name of the project that we provided during the new project creation. This namespace contains a class and inside the class, the actual program resides. The class inside the namespace is called a `Program'. We will learn about classes in a later chapter.
class Program
Inside the class, the statement is -
static void Main(string[] args)
This is known as the `Main' method or `Main' function. The `Main' method is the entry point of our program. The code that we want to execute should be inside the curly braces of the `Main' method (atleast for now, we will use this pattern. Windows progrmming has a different structure).
Right now, our `Main' method contains just one statement in it -
Console.WriteLine("Hello. Looks like my first application");
`Console.WriteLine' is used to output (display) messages on the screen. The message to be displayed is inside the parenthesis, in double quotes.
In its simplest form, the execution of a C# program begins with the `Main' method. The statements inside the `Main' method are executed one by one. When the `Main' method ends (denoted by a closing `}'), the program execution also ends.