C# Hello World!
Posted by Samath
Last Updated: March 14, 2012

C# Hello World!

// A "Hello World!" program in C#

class Hello

{

   static void Main()

   {

      System.Console.WriteLine("Hello World!");

   }

}

 

Comments

The first line contains a comment:

// A "Hello World!" program in C#

The characters // convert the rest of the line to a comment. You can also comment a block of text by placing it between the characters /* and */, for example:

/* A "Hello World!" program in C#.
This program displays the string "Hello World!" on the screen. */

The Main Method

The C# program must contain a Main method, in which control starts and ends. The Main method is where you create objects and execute other methods.

The Main method is a static method that resides inside a class or a struct. In the "Hello World!" example, it resides inside the Hello class. Declare the Main method in one of the following ways:

  • It can return void:
·         static void Main() 
·         {
·         ...
·         }
  • It can also return an int:
·         static int Main() 
·         {
·            ...
·            return 0;
·         }
  • With both of the return types, it can take arguments:
·         static int Main(string[] args) 
·         {
·            ...
·            return 0;
·         }

-or-

static void Main(string[] args) 
{
   ...
}

The parameter of the Main method is a string array that represents the command-line arguments used to invoke the program. Notice that, unlike C++, this array does not include the name of the executable (exe) file.

Input and Output

C# programs generally use the input/output services provided by run-time library of the .NET Framework. The statement: System.Console.WriteLine("Hello World!"); uses the WriteLine method, one of the output methods of the Console class in the run-time library. It displays its string parameter on the standard output stream followed by a new line. Other Console methods are used for different input and output operations. If you include the using System; statement at the beginning of the program, you can directly use the System classes and methods without fully qualifying them. For example:

Console.WriteLine("Hello World!");

 

 

Related Content