Our First C Program

 
Chapter 2 - C# Basics
bySimon Robinsonet al.
Wrox Press 2002
  

Our First C# Program

Let's start in the traditional way by compiling and running the simplest possible C# program - a simple class consisting of a console application that writes a message to the screen. Type the following into a text editor (such as Notepad), and save it with a .cs extension (for example, First.cs ):

   using System;     namespace Wrox.ProCSharp.Basics     {     class MyFirstCSharpClass     {     static void Main()     {     Console.WriteLine("This isn't at all like Java!");     Console.ReadLine();     return;     }     }     }   

Through the next chapters we will present a number of code samples. The most common technique for writing C# programs is to use Visual Studio .NET to generate a basic project and add your own code to this. However, since the aim of these early chapters is to teach the C# language, we are going to keep things simple and avoid relying on Visual Studio .NET until Chapter 6. Instead, we will present the code as simple files that you can type in using any text editor and compile from the command line.

You can compile this program simply running the C# command-line compiler ( csc.exe ) against the source file, like this:

  csc First.cs  

If you wish to compile code from the command line using the csc command, you should be aware that the .NET command-line tools, including csc , are only available if certain environment variables have been set up. Depending on how you installed .NET (and Visual Studio .NET), this may or may not be the case on your machine.

If you do not have them set up then there are two ways round this. The first is to run the batch file %Microsoft Visual Studio   .NET%\Vc7\bin\vcvars32.bat from the command prompt before running csc , where %Microsoft Visual Studio .NET is the folder to which Visual Studio .NET has been installed. The second (easier) way is to use the Visual Studio .NET command prompt instead of the usual command-prompt window. You will find the Visual Studio .NET command prompt in the Start Menu, under the Programs then Microsoft Visual Studio.NET submenus. It is simply a command-prompt window that automatically runs vcvars32.bat when it opens.

Compiling the code will produce an executable file named First.exe , which we can run from the command line or from Windows Explorer like any other executable. Give it a try:

  csc First.cs  Microsoft (R) Visual C# .NET Compiler version 7.00.9466 for Microsoft (R) .NET Framework version 1.0.3705 Copyright (C) Microsoft Corporation 2001. All rights reserved. First This isn't at all like Java! 

Well, maybe that message isn't quite true! There are some fairly fundamental similarities to Java in this program, although there are one or two points (such as the capitalized Main() function) to catch out the unwary Java or C++ developer. Let's look a little more closely at what's going on in the code.

A Closer Look

First, a few general comments about C# syntax. In C#, as in other C-style languages, every statement must end in a semi- colon , ; , and can continue over multiple lines without needing a continuation character (such as the underscore in VB). Statements can be joined into blocks using curly braces, {} . Single-line comments begin with two forward slash characters , // , and multi-line comments begin with a slash and an asterisk, /* , and end with the same combination reversed , */ . In these aspects, C# is identical to C++ and Java, but different from VB. It is the semi-colons and curly braces that give C# code such a different visual appearance to VB code. If your background is predominantly VB, then take extra care to remember the semi-colon at the end of every statement. Omitting this is usually the biggest single cause of compilation errors among developers new to C-style languages.

The first couple of lines are to do with using namespace statement in C++.

 using System; namespace Wrox.ProCSharp.Basics { 

The reason for the presence of the using statement in the First.cs file is that we are going to use a library class, System.Console . The using System statement allows us to refer to this class simply as Console (and similarly for any other classes in the System namespace). The standard System namespace is where the most commonly used .NET types reside. It is important to realize straight away that pretty well everything we do in C# depends on the .NET base classes; in this case, we are using the Console class within the System namespace in order to write to the console window.

Since almost every C# program uses classes in the System namespace, we will assume that a using System; statement is present in the file for all of the other code snippets in this chapter.

C# has no built-in keywords of its own for input or output - it is completely reliant on the .NET classes.

Next, we declare a class ostensibly called MyFirstClass . However, because it has been placed in a namespace called Wrox.ProCSharp.Basics the fully qualified name of this class is Wrox.ProCSharp.Basics.MyFirstCSharpClass .

 class MyFirstCSharpClass    { 

As in Java, all C# code must be contained within a class. Classes in C# are similar to classes in Java and C++, and very roughly comparable to class modules in VB 6. The class declaration consists of the class keyword, followed by the class name and a pair of curly braces. All code associated with the class should be placed between these braces.

Next we declare a method called Main() . Every C# executable (such as console applications, Windows applications, and Windows services) must have an entry point - the Main() method (note the capital M ):

 static void Main()       { 

The method is called when the program is started, like the main() function in C++ or Java, or Sub   Main() in a VB 6 module. This method must return either nothing ( void ) or an integer ( int ). A C# method corresponds to a method in C++ and Java (sometimes referred to in C++ as a member function). It also corresponds to either a VB Function or a VB Sub , depending on whether the method returns anything (unlike VB, C# makes no conceptual distinction between functions and subroutines).

Note how method definitions in C# take the form:

 [  modifiers  ]  return   _   type MethodName  ([  parameters  ]) {    // Method body } 

Here, the first square brackets represent certain optional keywords. Modifiers are used to specify certain features of the method we are defining, such as where the method can be called from. In our case, we have two modifiers: public and static . The public modifier means that the method can be accessed from anywhere , so it can be called from outside our class. This is the same meaning as public in C++ and Java, and Public in VB. The static modifier indicates that the method does not operate on a specific instance of our class, and therefore is called without first instantiating the class. This is important since we are creating an executable rather than a class library. Once again, this has the same meaning as the static keyword in C++ and Java, though in this case there is no VB equivalent (the Static keyword in VB has a different meaning). We set the return_type to void , and in our example, we don't include any parameters.

Finally we come the code statements themselves :

 Console.WriteLine("This isn't at all like Java!");          Console.ReadLine();          return; 

In this case, we simply call the WriteLine() method of the System.Console class to write a line of text to the console window. WriteLine() is a static method, so we don't need to instantiate a Console object before calling it.

Console.ReadLine() reads user input. Adding this line forces the application to wait for the carriage return key to be hit before the application exits, and, in the case of Visual Studio .NET, the console window disappears.

We then call return to exit from the method (and, since this is the Main() method, the program). We specified void in our method header, so we don't return any parameters. The return statement is equivalent to return in C++ and Java, and Exit Sub or Exit Function in VB.

Now that we have given you a taste of basic C# syntax, we are ready to go into more detail with the various aspects of C#. Since it is virtually impossible to write any non-trivial program without variables , we will start by looking variables in C#.

  


Professional C#. 2nd Edition
Performance Consulting: A Practical Guide for HR and Learning Professionals
ISBN: 1576754359
EAN: 2147483647
Year: 2002
Pages: 244

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