Our First C# Program

Before we continue with an in depth description of the C# language and the .NET platform, let’s take a look at a simple example, illustrating how a program written in C# looks like:

The only thing this program does is to print the message "Hello, C#!" on the default output. It is still early to execute it, which is why we will only take a look at its structure. Later we will describe in full how to compile and run a given program from the command prompt as well as from a development environment.

How Does Our First C# Program Work?

Our first program consists of three logical parts:

·         Definition of a class HelloCSharp;

·         Definition of a method Main();

·         Contents of the method Main().

Defining a Class

On the first line of our program we define a class called HelloCSharp. The simplest definition of a class consists of the keyword class, followed by its name. In our case the name of the class is HelloCSharp. The content of the class is located in a block of program lines, surrounded by curly brackets: {}.

Defining the Main() Method

On the third line we define a method with the name Main(), which is the starting point for our program. Every program written in C# starts from a Main() method with the following title (signature):

 

Contents of the Main()

Method The content of every method is found after its signature, surrounded by opening and closing curly brackets. On the next line of our sample program we use the system object System.Console and its method WriteLine() to print a message on the default output (the console), in this case "Hello, C#!".

In the Main() method we can write a random sequence of expressions and they will be executed in the order we assigned to them.

More information about expressions can be found in chapter "Operators and Expressions", working with the console is described in chapter "Console Input and Output", classes and methods can be found in chapter "Defining Classes".