The following console program is the C# version of the traditional "Hello World!" program, which displays the string Hello World!
.
// A "Hello World!" program in C# class Hello { public static void Main() { System.Console.WriteLine("Hello World!"); } }
The following are important points of this program.
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 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 public static method that resides inside a class or a struct. In the "Hello World!" example, it resides inside the Hello
class. There are three ways to declare the Main
method:
public static void Main() { ... }
public static int Main() { ... return 0; }
public static int Main(string[] args) { ... return 0; }
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.
For more information on using command-line arguments, see the example in Main and Creating and Using DLLs.
C# programs generally use the input/output services provided by run-time library of the NGWS 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 following using statement at the beginning of the program:
using System;
you can directly use the System classes and methods without fully qualifying them. For example:
Console.WriteLine("Hello World!");
For more information on input/output methods, see the Reference section of the NGWS SDK.
You can compile the "Hello World!" program either by Creating a C# Client EXE Project in the Visual Studio IDE, or by using the command line.
To compile the program from the command line:
Hello.cs
. C# source code files use the extension .cs
.csc Hello.cs
If your program does not contain any compilation errors, a Hello.exe
file will be created.
Hello
For more information on compilation options, see C# Compiler Options.