Now we will look at how to create a basic program in C#. For the sake of explanation, we will work on the Console Application project:
- To create a new project, click on File | New Project and select Console App (.NET Framework) as the project type:
After giving the solution an appropriate name and path, click on OK. Check that the solution has been created. At this point, you should see the Solution Explorer. By default, a .cs file, Program.cs, should be added to the solution. By default, a method by the name of Main will also be added to the class. This method is the first entry point when this application is executed.
- Let's open Program.cs at this stage. By default, the project will have the following using expressions for the following namespaces:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
A using statement basically signifies that the program can use the classes and methods defined in those namespaces for any execution. In further chapters, we will go over namespaces in detail and learn how to use them.
- Now, have a look at the program structure. By default, each class needs to be associated with a namespace. The namespace expression present in the Program.cs class indicates the namespace this class is part of:
Each method in C# consists of two parts:
- Input parameters: This is a list of variables that will be passed to the function when it's executed.
- Return type: This is the value that will be returned by the function to the caller when the function finishes its processing.
In the case of the Program function declared previously, the input variable is a collection of arguments. The output variable is void; in other words, it does not return anything. In the forthcoming chapters, we will go over functions in more detail.
Now, let's write a program syntax to execute the famous Hello World output. In a console application, we can do this using Console.Writeline:
- The code implementation for this program is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World");
}
}
}
- At this stage, we have finished the program and are ready to execute it. Click on Build | Build Solution. Check that there are no compile time errors:
- At this stage, internally, Visual Studio should have created an .exe application for the project:
- Open Command Prompt and navigate directly to where the .exe file has been created. Execute the .exe file and check that the desired output of Hello World appears in Command Prompt.