First C# Code with explanation


Create first Console Application

  • Open Visual studio and click on "File" > "New" > "Project" or you can click on "Console App" below New Project in search screen, as displayed in the image below.

  • From the pop up select "Console App", add any name to your project, select the location where you want to save your project, if you want add customized name for solution and select the .NET framework you want to work in. Then click "Ok" as shown below:

  • So you created your first console application.

Write your first program in C#.

Let's write simple C# code. Every console application in C# start from Main() method. The following code displays "Hello World!" in the console.

using System;
namespace DemoApp
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

Let's understand this program:

Let's understand the above program line by line:
  1. .NET have its built-in library which helps use do many tasks very easily. So, we use the necessary .NET namespaces which we want to apply in our program. With the help of "using" keyword we use the namespace.
  2. Namespace are used to organize too many classes so that we can handle classes easily. So, we declared the namespace "DemoApp" of the current class "Program" using "namespace" keyword.
  3. We declare our class "Program" using "class" keyword. We have added access modifier "internal" in front of the class which defines scope(it defines accessibility of the element in the application) of the class.
  4. We declare our method "Main()" of our "Program" class. This is the entry point to our application. It also has access modifier "private" with a modifier "static" with the return type "void". The method is also has parameter as "args" where we can pass array of strings. You don't have to remember all this, as you will get detailed information later.
  5. Here we print the "Hello World!" message to console using .NET library. So, "Console" is a .NET framework class, it has a method "WriteLine()" which displays messages to console.
So, your first program is done, if you don't understand these terms i used in the program then don't worry. I have added this because you can relate them later.

Comments

Popular posts from this blog

C# Tutorial