A First Simple Program


It is now time to look at an actual C# program. We will begin by compiling and running the short program shown here:

 /*    This is a simple C# program.    Call this program Example.cs. */ using System; class Example {   // A C# program begins with a call to Main().   public static void Main() {     Console.WriteLine("A simple C# program.");   } } 

The primary development environment for C# is Microsoft’s Visual Studio. To compile all of the programs in this book, including those that use the new C# 2.0 features, you will need to use Visual Studio 2005, or later. Using Visual Studio 2005, there are two ways to edit, compile, and run a C# program. First, you can use the command-line compiler, csc.exe. Second, you can use the Visual Studio Integrated Development Environment (IDE). Both methods are described here.

Using csc.exe, the C# Command-Line Compiler

Although the Visual Studio IDE is what you will probably be using for your commercial projects, the C# command-line compiler is the easiest way to compile and run most of the sample programs shown in this book. To create and run programs using the C# commandline compiler, you will follow these three steps:

  1. Enter the program using a text editor.

  2. Compile the program.

  3. Run the program.

Entering the Program

The programs shown in this book are available from Osborne’s web site: www.osborne.com. However, if you want to enter the programs by hand, you are free to do so. In this case, you must enter the program into your computer using a text editor, such as Notepad. Remember, you must create text-only files, not formatted word-processing files, because the format information in a word processor file will confuse the C# compiler. When entering the program, call the file Example.cs.

Compiling the Program

To compile the program, execute the C# compiler, csc.exe, specifying the name of the source file on the command line, as shown here:

 C:\>csc Example.cs

The csc compiler creates a file called Example.exe that contains the MSIL version of the program. Although MSIL is not executable code, it is still contained in an exe file. The Common Language Runtime automatically invokes the JIT compiler when you attempt to execute Example.exe. Be aware, however, that if you try to execute Example.exe (or any other exe file that contains MSIL) on a computer for which the .NET Framework is not installed, the program will not execute because the CLR will be missing.

Note 

Prior to running csc.exe, you may need to run the batch file vcvars32.bat, which is typically found in the \Program Files\Microsoft Visual Studio 8\VC\Bin directory. Alternatively, you can activate a command-prompt session that is already initialized for C# by selecting a Visual Studio 2005 Command Prompt from the list of tools shown under the Microsoft Visual Studio 2005 entry in the Start | Programs menu of the task bar. Alternatively, you can select SDK Command Prompt shown under the Microsoft .NET Framework SDK 2.0 entry in the Start | Programs menu of the task bar.

Running the Program

To actually run the program, just type its name on the command line, as shown here:

 C:\>Example

When the program is run, the following output is displayed:

 A simple C# program.

Using the Visual Studio IDE

To edit, compile, and run a C# program using Visual Studio 2005, follow these steps.

  1. Create a new, empty C# project by selecting File | New | Project. Next, select Visual C#, and then Console Application, as shown here:

    image from book

    Then, change the name to Project1 and press OK.

    Note 

    The precise screens that you see may vary based on which version of Visual Studio 2005 you have installed and your specific configuration.

  2. Once the project is created, the Visual Studio IDE will look like this:

    image from book

  3. Notice that a new window called Program.cs was created. This contains an empty template for a C# console program. This file is created automatically by Visual Studio 2005 and contains the skeleton to a C# program. However, this skeleton is more complicated than it needs to be for our purposes, so delete all of the lines in this window. After doing so, the Program.cs window will be blank, and look like this:

    image from book

  4. Next, enter the example program into the Program.cs window, and then save the file using the name Example.cs. (Remember, you can download the programs in this book from www.osborne.com.) When done, your screen will look like this:

    image from book

  5. Compile the program by selecting Build Solution from the Build menu.

  6. Run the program by selecting Start Without Debugging from the Debug menu. When you run the program, you will see the window shown here.

    image from book

As the preceding instructions show, compiling short sample programs using the IDE involves more steps than it does when using the csc command-line compiler. Therefore, for the programs shown in the first part of this book, using the command-line compiler is the recommended approach. Of course, the choice is yours.

Note 

When using the IDE to compile and run the sample programs in this book, you don’t need to create a new project for each one. Instead, you can use the same C# project. Just delete the current file and add the new file. Then, recompile and run.

The First Sample Program, Line by Line

Although Example.cs is quite short, it includes several key features that are common to all C# programs. Let’s closely examine each part of the program, beginning with its name.

The name of a C# program is arbitrary. Unlike some computer languages (most notably, Java) in which the name of a program file is very important, this is not the case for C#. You were told to call the sample program Example.cs so that the instructions for compiling and running the program would apply, but as far as C# is concerned, you could have called the file by another name. For example, the preceding sample program could have been called Sample.cs, Test.cs, or even X.cs.

By convention, C# programs use the .cs file extension, and this is a convention that you should follow. Also, many programmers call a file by the name of the principal class defined within the file. This is why the filename Example.cs was chosen. Since the names of C# programs are arbitrary, names won’t be specified for most of the sample programs in this book. Just use names of your own choosing.

The program begins with the following lines:

 /*    This is a simple C# program.        Call this program Example.cs. */

This is a comment. Like most other programming languages, C# lets you enter a remark into a program’s source file. The contents of a comment are ignored by the compiler. Instead, a comment describes or explains the operation of the program to anyone who is reading its source code. In this case, the comment describes the program and reminds you to call the source file Example.cs. Of course, in real applications, comments generally explain how some part of the program works or what a specific feature does.

C# supports three styles of comments. The one shown at the top of the program is called a multiline comment. This type of comment must begin with /* and end with */. Anything between these two comment symbols is ignored by the compiler. As the name suggests, a multiline comment can be several lines long.

The next line in the program is

 using System;

This line indicates that the program is using the System namespace. In C#, a namespace defines a declarative region. Although we will examine namespaces in detail later in this book, a brief description is useful now. Through the use of namespaces, it is possible to keep one set of names separate from another. In essence, names declared in one namespace will not conflict with names declared in a different namespace. The namespace used by the program is System, which is the namespace reserved for items associated with the .NET Framework class library, which is the library used by C#. The using keyword simply states that the program is using the names in the given namespace.

The next line of code in the program is shown here:

 class Example {

This line uses the keyword class to declare that a new class is being defined. As mentioned, the class is C#’s basic unit of encapsulation. Example is the name of the class. The class definition begins with the opening curly brace ({) and ends with the closing curly brace (}). The elements between the two braces are members of the class. For the moment, don’t worry too much about the details of a class except to note that in C#, all program activity occurs within one. This is one reason why all C# programs are (at least a little bit) object oriented.

The next line in the program is the single-line comment, shown here:

 // A C# program begins with a call to Main().

This is the second type of comment supported by C#. A single-line comment begins with a // and ends at the end of the line. As a general rule, programmers use multiline comments for longer remarks and single-line comments for brief, line-by-line descriptions.

The next line of code is shown here:

 public static void Main() {

This line begins the Main( ) method. As mentioned earlier, in C#, a subroutine is called a method. As the comment preceding it suggests, this is the line at which the program will begin executing. All C# applications begin execution by calling Main( ). (This is similar to the way C/C++ programs begin execution at main( ).) The complete meaning of each part of this line cannot be given now, since it involves a detailed understanding of several other C# features. However, since many of the examples in this book will use this line of code, we will take a brief look at it here.

The public keyword is an access specifier. An access specifier determines how other parts of a program can access a member of a class. When a class member is preceded by public, then that member can be accessed by code outside the class in which it is declared. (The opposite of public is private, which prevents a member from being used by code defined outside of its class.) In this case, Main( ) is declared as public because it will be called by code outside of its class (in this case, the operating system) when the program is started.

Note 

C# does not actually require Main( ) to be declared as public. However, this is the way that many of the examples supplied by Visual Studio 2005 declare it. It is also the way that many C# programmers prefer because it explicitly states that Main( ) can be called from outside its class. Essentially, declaring Main( ) as public is simply a good programming practice to follow. For these reasons, this book will also declare Main( ) as public. Don’t be surprised, though, if you see it declared without the public specifier.

The keyword static allows Main( ) to be called before an object of its class has been created. This is necessary because Main( ) is called at program startup. The keyword void simply tells the compiler that Main( ) does not return a value. As you will see, methods can also return values. The empty parentheses that follow Main indicate that no information is passed to Main( ). As you will see, it is also possible to pass information into Main( ) or into any other method. The last character on the line is the { (curly brace). This signals the start of Main( )’s body. All of the code that comprises a method will occur between the method’s opening curly brace and its closing curly brace.

The next line of code is shown here. Notice that it occurs inside Main( ).

 Console.WriteLine("A simple C# program.");

This line outputs the string “A simple C# program.” followed by a new line on the screen. Output is actually accomplished by the built-in method WriteLine( ). In this case, WriteLine( ) displays the string that is passed to it. Information that is passed to a method is called an argument. In addition to strings, WriteLine( ) can be used to display other types of information. The line begins with Console, which is the name of a predefined class that supports console I/O. By connecting Console with WriteLine( ), you are telling the compiler that WriteLine( ) is a member of the Console class. The fact that C# uses an object to define console output is further evidence of its object-oriented nature.

Notice that the WriteLine( ) statement ends with a semicolon, as does the using System statement earlier in the program. In general, statements in C# end with a semicolon. The exception to this rule are blocks, which begin with a { and end with a }. This is why those lines in the program don’t end with a semicolon. Blocks provide a mechanism for grouping statements and are discussed later in this chapter.

The first } in the program ends Main( ), and the last } ends the Example class definition.

One last point: C# is case-sensitive. Forgetting this can cause serious problems. For example, if you accidentally type main instead of Main, or writeline instead of WriteLine, the preceding program will be incorrect. Furthermore, although the C# compiler will compile classes that do not contain a Main( ) method, it has no way to execute them. So, if you had mistyped Main, the compiler would still compile your program. However, you would also see an error message that states that Example.exe does not have an entry point defined.




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net