only for RuBoard - do not distribute or recompile Previous Section Next Section

1.4 A First C# Program

Here is a simple C# program:

namespace FirstProgram {
  using System;
  class Test {
    static void Main (  ) {
      Console.WriteLine ("Welcome to C#!");
    }
  }
}

A C# program is composed of types (typically classes) that we organize into namespaces. Each type contains function members (typically methods), as well as data members (typically fields). In our program, we define a class named Test that contains a method, named Main, that writes Welcome to C#! to the Console window. The Console class encapsulates standard input/output functionality, providing methods such as WriteLine. To use types from another namespace, we use the using directive. Since the Console class resides in the System namespace, we write using System; similarly, types from other namespaces could use our Test class by including the following statement: using FirstProgram;.

To compile this program into an executable, paste it into a text file, save it as Test.cs, then type csc Text.cs in the command prompt. This compiles the program into an executable called Test.exe. Add the /debug option to the csc command line to include debugging symbols in the output. This will let you run your program under a debugger and get meaningful stack traces that include line numbers.

.NET executables contain a small CLR host created by the C# compiler. The host starts the CLR and loads your application, starting at the Main entry point. Note that Main must be specified as static.

In C#, there are no standalone functions; functions are always associated with a type, or as we will see, instances of that type. Our program is simple and makes use of only static members, which means the member is associated with its type, rather than instances of its type. In addition, we make use of only void methods, which means these methods do not return a value. Of final note is that C# recognizes a method named Main as the default entry point of execution.

only for RuBoard - do not distribute or recompile Previous Section Next Section