Programming Example 1: C# Program Structure


In this example program you will see the basic elements and overall structure of a C# program. Every program that you write this semester will contain these basic elements and structure. Over the course of the semester, we will discuss additional elements that will appear in your programs, but these are the basics.

Basic Program Elements

As you read through this example, look for the following program elements:

  1. The file prologue: Every source code file must have a file prologue. The file prologue provides a description of what is in the file and identifies you as the owner of the file. One of the most important elements of the file prologue is the notice that you did not copy code from anyone else while developing this program.
  2. using: The most common using statement that you will use in this course is the using System statement. The using System statement tells the compiler that you are going to be using names that come from the System namespace.The other common using statement is using System.Console. This lets you use some shortcuts when typing programs that use the Console to do input and output.
  3. namespace: Identifiers(names) used in C# programs can belong to different namespaces. A namespace is simply a collection of names that you can use in your program. Because different namespaces may contain identical names, you either have to tell the compiler which namespace you will be using, or prefix each name with the name of the namespace. Every program you write will have a unique namespace.
  4. class: Every C# program mst contain at least one class. A class can have any name that you want, but in your assignments you should name this class "Program". You can think of this class as the package that contains the Main( ) method and any global, class level data. The body of the class is enclosed in curly braces "{" and "}".
  5. The Main( ) method: Every program must have a Method named Main. When the computer executes your program it will search for a static method named Main and start it's execution there. The body of every method, including Main is enclosed in curly braces "{" and "}".
  6. Comments:Comments are used to add notes and documentation to your program. The compiler ignores all comments. There are three types of comments in a C# program. This program uses single line comments that begin with a double slash "//"
  7. Statements:The body of a C# program is made up of statements, much like a paragraph is made up of sentences. Each statement in a C# program ends with a semi-colon.
  8. ReadKey(true) This statement is used at the end of your program, and tells the program to stop and wait for the user of the program to press the Enter key.

This example program is located here.  An executable of this program can be found here.