English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Here, you will learn to create a simple console application in C# and understand the basic building blocks of a console application.
C# can be used in window-based, web-based, or console applications. First, we will create a console application to use C#.
Open Visual Studio installed on your local computer (2017Or higher version). Click File from the top menu-> New Project ... as shown below.
Create a new project from the following:New ProjectIn the pop-up window, select Visual C# in the left panel, and then select Console App in the right panel.
In the Name field, provide any appropriate project name, the location to create all project files, and the name of the project solution.
Click "OK" to create the console project.Program.csA default C# file will be created in Visual Studio, where you can write C# code in the Program class, as shown below. (.cs is the file extension for C# files.)
Every console application starts from the Main() method of this class. The following example displays "Hello World !!" on the console.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSharpTutorials { class Program { static void Main(string[] args) { string message = "Hello World!!"; Console.WriteLine(message); } } }
Let's understand the structure of the above C# code.
Each .NET application references the .NET Framework namespace references that it plans to use with the using keyword (for example, using System.Text).
Use the namespace keyword to declare the name space of the current class, for example, namespace CSharpTutorials.FirstProgram
Then, we use the class keyword to declare a class: class Program
Main() is a method of the Program class, which is the entry point of the console application.
String is a data type.
message is a variable that stores values of specified data types.
"Hello World!!" is the value of the message variable.
Console.WriteLine() is a static method, used to display text on the console.
Every line or statement in C# must end with a semicolon (;).
To view the output of the above C# program, we must compile it by pressing Ctrl + F5Or click the 'Run (Run)' button or click the 'Debug (Debug)' menu and click 'Start Without Debugging' to run it. You will see the following output in the console:
Hello World !!
Therefore, these are the basic code items you might use in each C# code.