Updated on Kisan Patel
In this tutorial series, we will teach you the basics of programming and the basics of the C# programming language.
If you are an absolute beginner this tutorial is suited for you.
To follow this tutorial you need to have Visual Studio C# Express Edition 2010 or later version installed on your computer. These applications are free to download and install.
The best way to learn this is by practicing. Make sure you write all the examples yourself and test them.
To start with Visual Studio Express, Open Visual Studio ⇒ File ⇒ New ⇒ Project… ⇒ Select the Visual C# Console Application
template from the window that appears and name it to FirstConsoleApp
⇒ click OK.
Once you created your project, you will show you the initial default code for your FirstCOnsoleApp
application.
using System; namespace FirstConsoleApp { class Program { static void Main(string[] args) { } } }
First, change the class name Program
to HelloWorld
as shown in below code and also write all changes we have make in below code.
using System; namespace FirstConsoleApp { class HelloWorld { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } }
At this point, your application won’t do anything. To start you application, press F5. You will see a black windows appearing and closing immediately.
It closes immediately because it does exactly what you told it to do: nothing. Let’s “tell” it to open and wait for a keystroke to close. Write the Console.ReadKey();
line between the braces of static void Main(string[] args)
.
static void Main(string[] args) { Console.WriteLine("Hello World!"); Console.ReadKey(); }
Now, press F5 to run your application. You will end up with a black window awaiting you to press any key so it closes.
Namespaces in c#
So, in our program HelloWorld
class are part of FirstConsoleApp
namespace.
namespace FirstConsoleApp { .... }
Main()
method resides in one of these classes.namespace FirstConsoleApp { class HelloWorld { // here add methods and fields etc.. } }
using
keyword allows us to use the classes defined in the System
namespace.using System;
line, we can now access all the classes defined in the System
namespace.Console
class in our Main
method.static void Main(string[] args) { ... }
In C#, every application must have a static Main()
or int Main()
entry point. The C# program starts its execution from the first line of Main method and terminates of Main method.
The Main
method is designed as static as it will be called by the Common Language Runtime (CLR) without making any object of our HelloWorld
class.
The method is also declared void
as it does not return anything.
Main is the name of this method, while string[] args
is the list of parameters that can be passed to Main method.
In our program, we called WriteLine()
, a static
method of the Console
class defined in System namespace.
WriteLine()
method takes a string as its parameter and prints it on the Console window.