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 go using System; similarily, types from other namespaces could use our Test class by going using FirstProgram.

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 a default entry point of execution.

Get C# Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.