Share via


Hello World in Visual C#

Here is how Hello World looks in Visual C#:

Listing 1. Hello World in Visual C# (HelloCS.cs)

// Allow easy reference to the System namespace classes.
using System;

// This class exists only to house the entry point.
class MainApp {
   // The static method, Main, is the application's entry point.
   public static void Main() {
      // Write text to the console.
      Console.WriteLine("Hello World using C#!");
   }
}

This code is a little longer than the equivalent for Managed Extensions for C++. The syntax for accessing the core library is new; it specifies the namespace rather than the name of the file in which it is found:

using System;

The most striking difference is the class specification:

class MainApp {

In Visual C#, all code must be contained in methods of a class. So, to house the entry-point code, you must first create a class. (The name of the class does not matter here). Next, you specify the entry point itself:

public static void Main () {

The compiler requires this to be called Main. The entry point must also be marked with both public and static. In addition, as with the Managed Extensions for C++ example, the entry point takes no arguments and does not return anything (although different signatures for more sophisticated programs are certainly possible).

The next line is:

Console.WriteLine("Hello World using C#!");      

Again, this line writes a string using the runtime Console type. In Visual C#, however, you are able to use a period (.) to indicate the scope. Also, you do not have to place an L before the string because, in C#, all strings are Unicode.

The Build.bat file contains the single line that is necessary to build this program:

csc.exe /debug+ /out:.\HelloCS.exe helloCS.cs

In this admittedly simple case, you do not have to specify anything other than the file to compile. In particular, C# does not use the additional step of linking that is required by C++:

C:\...\HelloWorld\cs>build
C:\...\HelloWorld\cs>csc.exe /debug+ /out:.\HelloCS.exe hellocs.cs
Microsoft (R) Visual C# Compiler Version ...[CLR version...]
Copyright (C) Microsoft Corp 2000-2001. All rights reserved.

The default output of the C# compiler is an executable file of the same name, and running this program generates the following output:

C:\...\HelloWorld\cs>hellocs
Hello World using Visual C#!

See Also

Hello World in Visual Basic | Writing Simple .NET Components | Clients for the Simple Components | Summary of Development Tutorial | Appendix A: Tools for Exploring Namespaces