A Simple C Sharp Console Application

From Techotopia
Revision as of 21:19, 9 January 2008 by Neil (Talk | contribs) (Creating a Sample C# Program)

Jump to: navigation, search

In the early 1970's the creators of the C Programming Language wrote a book of the same name intended to teach the skills necessary to program in C. One of the first chapters of this book contained a very simple C program which simply displayed the words "Hello World" in a console. Ever since that day most programming books has followed this tradition. Given that C# can trace its ancestry to the C programming language C# Essentials will be no exception to this rule.

Even if you are an experienced programmer this simple C# example is still recommended if only to verify that the C# development environment is correctly installed.

Even an example this simple requires that certain aspects of the C# and runtime environment be set up. Before we plunge into the example, therefore, we first need to spend a little time talking about setting up the environment.

Options for Installing a C# Environment

There are a number of options for installing an environment suitable for compiling and executing a C# program. If you are running on Windows you can either install Visual Studio (either the professional edition or the free express edition). If you prefer a lighter weight solution you can simply download and install latest .NET Framework which includes the C# compiler and the runtime environment. This can be downloaded from the Microsoft website.

Once installed the compiler will need to be run from a command prompt window. The compiler executable is called CSC.EXE and by default it is not in the command path. Find where CSC.EXE is installed on your system (in .NET Framework 3.5 on Windows XP it is installed in the \WINDOWS\Microsoft.NET\Framework\v3.5) by performing a Search of your disk drives. Once the location has been ascertained, add the location to the path environment variable:

Set PATH=%PATH%;%Windir%\Microsoft.NET\Framework\v3.5

If you are running on a non-Windows system such as Linux you will need to use either Mono or DotGNU. The Mono compiler command is mcs.

Creating a Sample C# Program

Once the appropriate environment is installed and configured the next step is to write our Hello World example. Convention dictates that C# sources files be named with the .cs file name extension. We shall, therefore, name our example file HelloCsharp.cs. Using your favorite code editor create the following C# source code:

class HelloCsharp
{
       static void Main()
       {
            System.Console.WriteLine ("Hello from C#.");
       }
}