Your First C Program


Your 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.

The Code

Type the following into a text editor (such as Notepad), and save it with a .cs extension (for example, First.cs). The Main() method is shown here:

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

Tip 

The following chapters present a number of code samples. The most common technique for writing C# programs is to use Visual Studio 2005 to generate a basic project and add your own code to it. However, because 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 2005 until Chapter 14, “Visual Studio 2005.” Instead, we will present the code as simple files that you can type in using any text editor and compile from the command line.

Compiling and Running the Program

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

 csc First.cs

If you want 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 2005), this may or may not be the case on your machine.

Tip 

If you do not have the environment variables set up, you have the following two options. The first is to run the batch file %Microsoft Visual Studio 2005%\Common7\Tools\vcvars32.bat from the command prompt before running csc, where %Microsoft Visual Studio 2005 is the folder to which Visual Studio 2005 has been installed. The second (easier) way is to use the Visual Studio 2005 command prompt instead of the usual command prompt window. You will find the Visual Studio .NET command prompt in the Start Menu, under Programs, Microsoft Visual Studio2005, Microsoft Visual Studio Tools. It is simply a command prompt window that automatically runs vcvars32.bat when it opens.

Compiling the code produces an executable file named First.exe, which you 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# 2005 Compiler version 8.00.50727.42 for Microsoft (R) Windows (R) 2005 Framework version 2.0.50727 Copyright (C) Microsoft Corporation 2001-2005. All rights reserved.

First.exe

 This isn't at all like Java!

Well, maybe that message isn’t quite true! This program has some fairly fundamental similarities to Java, 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, most statements end in a semicolon (;) and can continue over multiple lines without needing a continuation character (such as the underscore in Visual Basic). Statements can be joined into blocks using curly braces ({}). Single-line comments begin with two forward slash characters (//), and multiline 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 Visual Basic. It is the semicolons and curly braces that give C# code such a different visual appearance from Visual Basic code. If your background is predominantly Visual Basic, take extra care to remember the semicolon at the end of every statement. Omitting this is usually the biggest single cause of compilation errors among developers new to C-style languages.

Another thing to remember is that C# is case sensitive. That means that variables named myVar and MyVar are two different variables.

The first couple of lines in the previous code example have to do with namespaces (mentioned later in this chapter), which are a way to group together associated classes. This concept will be familiar to Java and C++ developers but may be new to Visual Basic 6 developers. C# namespaces are basically the same as C++ namespaces or, equivalently, Java packages, but there is no comparable concept in Visual Basic 6. The namespace keyword declares the namespace your class should be associated with. All code within the following braces is regarded as being within that namespace. The using statement specifies a namespace that the compiler should look at to find any classes that are referenced in your code but that aren’t defined in the current namespace. This serves the same purpose as the import statement in Java and the 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 you are going to use a library class, System.Console. The using System statement allows you 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 that everything you do in C# depends on the .NET base classes. In this case, you are using the Console class within the System namespace in order to write to the console window.

Tip 

Because 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 code snippets in this chapter.

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

Next, you declare a class 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 Visual Basic 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, you 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 Visual Basic 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 Visual Basic Function or a Visual Basic Sub, depending on whether the method returns anything (unlike Visual Basic, C# makes no conceptual distinction between functions and subroutines).

Note the format of method definitions in C#:

  [modifiers] return_type MethodName([parameters]) {    // Method body. NB. This code block is pseudo-code. }

Here, the first square brackets represent certain optional keywords. Modifiers are used to specify certain features of the method you are defining, such as where the method can be called from. In this case, you 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 your class. This is the same meaning as public in C++ and Java, and Public in Visual Basic. The static modifier indicates that the method does not operate on a specific instance of your class and therefore is called without first instantiating the class. This is important because you 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 Visual Basic equivalent (the Static keyword in Visual Basic has a different meaning). You set the return type to void, and in the example, you don’t include any parameters.

Finally, we come to the code statements themselves:

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

In this case, you 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 you 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 pressed before the application exits, and, in the case of Visual Studio 2005, the console window disappears.

You then call return to exit from the method (also because this is the Main() method, the program). You specified void in your method header, so you don’t return any parameters. The return statement is equivalent to return in C++ and Java, and Exit Sub or Exit Function in Visual Basic.

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




Professional C# 2005 with .NET 3.0
Professional C# 2005 with .NET 3.0
ISBN: 470124725
EAN: N/A
Year: 2007
Pages: 427

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