Export (0) Print
Expand All

Hello World Tutorial

Visual Studio .NET 2003

This tutorial shows several versions of a Hello World program in C#.

Sample Files

See Hello World Sample to download and build the sample files discussed in this tutorial.

Further Reading

Main

1.1 Getting started

3.3 Declarations

Tutorial

The following examples show different ways of writing the C# Hello World program.

Example 1

// Hello1.cs
public class Hello1
{
   public static void Main()
   {
      System.Console.WriteLine("Hello, World!");
   }
}

Output

Hello, World!

Code Discussion

  • Every Main method must be contained inside a class (Hello1 in this case).
  • The System.Console class contains a WriteLine method that can be used to display a string to the console.

Example 2

To avoid fully qualifying classes throughout a program, you can use the using directive as shown below:

// Hello2.cs
using System;

public class Hello2
{
   public static void Main()
   {
      Console.WriteLine("Hello, World!");
   }
}

Output

Hello, World!

Example 3

If you need access to the command line parameters passed in to your application, simply change the signature of the Main method to include them as shown below. This example counts and displays the command line arguments.

// Hello3.cs
// arguments: A B C D
using System;

public class Hello3
{
   public static void Main(string[] args)
   {
      Console.WriteLine("Hello, World!");
      Console.WriteLine("You entered the following {0} command line arguments:",
         args.Length );
      for (int i=0; i < args.Length; i++)
      {
         Console.WriteLine("{0}", args[i]); 
      }
   }
}

Output

Hello, World!
You entered the following 4 command line arguments:
A
B
C
D

Example 4

To return a return code, change the signature of the Main method as shown below:

// Hello4.cs
using System;

public class Hello4
{
   public static int Main(string[] args)
   {
      Console.WriteLine("Hello, World!");
      return 0;
   }
}

Output

Hello, World!

See Also

C# Tutorials

Show:
© 2014 Microsoft