Search the Catalog
Learning C#

Learning C#

By Jesse Liberty
September 2002
0-596-00376-5, Order Number: 3765
368 pages, $34.95 US $54.95 CA

Chapter 2
Getting Started with C#

You can use C# to create three different types of programs:

The .NET platform is web-centric. The C# language was developed to allow .NET programmers to create very large, powerful, high-quality web applications quickly and easily. The .NET technology for creating web applications is called ASP.NET.

ASP.NET, the next generation from ASP (Active Server Pages), is composed of two Microsoft development technologies: Web Forms and Web Services. While the development of fully realized web applications using these technologies is beyond the scope of this book, learning the basics of the C# language will certainly get you started in the right direction. C# is generally acknowledged to be the language of choice for ASP.NET development.

Typically, you'll create an ASP.NET application when you want your program to be available to end users on any platform (e.g., Windows, Mac, Unix). By serving your application over the Web, end users can access your program with any browser.

When you want the richness and power of a native application running directly on the Windows platform, alternatively you might create a desktop-bound Windows application. The .NET tools for building Windows applications are called Windows Forms; a detailed analysis of this technology is also beyond the scope of this book.

However, if you don't need a Graphical User Interface (GUI) and just want to write a simple application that talks to a console window (i.e., what we used to call a DOS box), you might consider creating a console application. This book makes extensive use of console applications to illustrate the basics of the C# language.

Web, Windows, and console applications are described and illustrated in the following pages.

Console applications
A console application runs in a console window, as shown in Figure 2-1. A console window (or DOS box) provides simple text-based output.

Figure 2-1. A console application

 

Console applications are very helpful when learning a language because they strip away the distraction of the Graphical User Interface. Rather than spending your time creating complex windowing applications, you can focus on the details of the language constructs, such as how you create classes and methods, how you branch based on runtime conditions, and how you loop. All these topics will be covered in detail in coming chapters.

Windows applications
A Windows application runs on a PC's desktop. You are already familiar with Windows applications such as Microsoft Word or Excel. Windows applications are much more complex than console applications and can take advantage of the full suite of menus, controls, and other widgets you've come to expect in a modern desktop application. Figure 2-2 shows the output of a simple windows application.

Figure 2-2. A Windows application

 

ASP.NET applications
An ASP.NET application runs on a web server and delivers its functionality through a browser, typically over the Web. ASP.NET technology facilitates developing web applications quickly and easily. Figure 2-3 shows a message from a simple ASP.NET application.

Figure 2-3. An ASP.NET application

 

Although most commercial applications will be either Windows or ASP.NET programs, console applications have a tremendous advantage in a C# primer. Windows and ASP.NET applications bring a lot more overhead; there is great complexity in managing the window and all the events associated with the window. (Events are covered in Chapter 19.) Console applications keep things simple--allowing you to focus on the features of the language.

TIP: This book does not go into all the myriad details of building robust Windows and ASP.NET applications. For complete coverage of these topics, please see Programming ASP.NET and Programming .NET Windows Applications, both by Jesse Liberty and Dan Hurwitz (O'Reilly).

What's in a Program?

A program consists of English-language instructions called source code. The syntax for these instructions is strictly defined by the language. Source code consists of a series of statements. A statement is an instruction to the complier. Each instruction must be formed correctly, and one task you'll face when learning C# will be to learn the correct syntax of the language. For example, in C# every statement ends with a semi-colon.

Each instruction has a semantic meaning that expresses what you are trying to accomplish. Although you must follow the syntax, the semantics of the language are far more important in developing effective object-oriented programs. This book will provide insight into both the syntax and the semantics of good C# programs.

Save the source code you write in a text file. You can write this source code file using any simple text editor (such as Notepad), or you can use the Visual Studio .NET Integrated Development Environment (IDE). Visual Studio .NET is described in Chapter 4.

Once you write your program, you compile it using the C# compiler. The end result of compiling the program is an application.

Your First Program: Hello World

In this chapter, you will create a very simple application that does nothing more than display the words "Hello World" to your monitor. This console application is the traditional first program for learning any new language; it demonstrates some of the basic elements of a C# program.

Once you write your "Hello World" program and compile it, this chapter will provide a line-by-line analysis of the source code. This analysis gives something of a preview of the language; Chapter 5 describes the fundamentals much more fully.

As explained earlier, you can create C# programs with any text editor. You can, for example, create each of the three programs shown previously (in Figure 2-1, Figure 2-2, and Figure 2-3) with Notepad. To demonstrate that this is possible, you'll write your very first C# program using Notepad.

Begin by opening Notepad and typing in the program exactly as shown in Example 2-1.

Example 2-1: Hello World in Notepad

namespace NotePad
{
   class HelloWorld
   {
      // every console app starts with Main
      static void Main()
      {
         System.Console.WriteLine("Hello world!");
      }
   }
 }

That is the entire program. Save it to your disk as a file called helloworld.cs.

We'll examine this program in some detail in just a moment. First, however, it must be compiled.

The Compiler

Once you save your program to disk, you must compile the code to create your application. Compiling your source code means running a compiler and passing in the source code file. You run the compiler by opening a command prompt (DOS box) and entering the program name csc. Then you pass in your source code file by entering the filename on the command line, as in the following:

csc HelloWorld.cs

The job of the compiler is to turn your source code into a working program. It turns out to be just slightly more complicated than that because .NET uses an intermediate language called Microsoft Intermediate Language (MSIL, sometimes abbreviated to IL). The compiler reads your source code and produces IL. The .NET Just In Time (JIT) compiler then reads your IL code and produces an executable application in memory.

Microsoft provides a command window with the correct environment variables set. Open the command window by selecting the following menu items in this order:

Start -> Programs -> Microsoft Visual Studio .NET 
-> Visual Studio.NET Tools -> Visual Studio .NET Command Prompt

Then navigate to the directory in which you created your code file and enter the following command:

csc helloworld.cs

The Microsoft C# compiler compiles your code; when you display the directory you'll find the compiler has produced an executable file called helloworld.exe. Type helloworld at the command prompt, and your program executes, as shown in Figure 2-4.

Figure 2-4. Compiling and running Hello World

 

Presto! You are a C# programmer. That's it, close the book, you've done it. Okay, don't close the book--there are details to examine, but take a moment to congratulate yourself. Have a cookie.

Granted, the program you created is one of the simplest C# programs imaginable, but it is a complete C# program, and it can be used to examine many of the elements common to C# programs.

Examining Your First Program

The single greatest challenge when learning to program is that you must learn everything before you can learn anything. Even this simple "Hello World" program uses many features of the language that will be discussed in coming chapters, including classes, namespaces, statements, static methods, objects, strings, inheritance, blocks, libraries, and even something called polymorphism!

It is as if you were learning to drive a car. You must learn to steer, accelerate, brake, and understand the flow of traffic. Right now we're going to get you out on the highway and just let you steer for a while. Over time you'll learn how to speed up and slow down. Along the way you'll learn to set the radio and adjust the heat so that you'll be more comfortable. In no time you'll be driving, and then won't your parents begin to worry.

Line-by-Line Analysis

Hang on tight, we're going to zip through this quickly and come back to the details in subsequent chapters.

The first line in the program defines a namespace:

namespace NotePad

You will create many names when programming in C#. Every object and every type of object must be named. It is possible for the names you assign to conflict with the names assigned by Microsoft or other vendors. A namespace is a way to say "these names are mine."

In this program, you've created a namespace called NotePad. Each namespace must be enclosed in braces ({}). Thus, the second line of the Hello World program is an open brace to mark the beginning of the NotePad namespace. The open brace is matched by a closing brace at the end of the program.

Within the braces of the namespace, you write other programming constructs. For instance, you might define what is called an object. Every object named within these braces is implicitly prefixed with the name NotePad. The dot operator (.) separates the namespace from the name of the object within the namespace. Thus, if you were to create an object MyObject within the namespace NotePad, the real name of that object would be NotePad.MyObject. You can read this as either "NotePad dot MyObject" or "NotePad MyObject". Actually, you use the dot operator quite a lot; you'll see various other uses as we proceed.

Classes define a category, or type, of object. In C# there are thousands of classes. A class is a new, user-defined type. Classes are used to define Windows controls (buttons, list boxes, etc.), as well as types of things (employees, students, telephones, etc.) in the program you are writing. Some classes you create yourself, and some you obtain from the .NET Framework. Each class must be named.

Classes are the core of C# and object-oriented programming. You'll learn about classes in detail in Chapter 3, as well as in Chapter 5.

The third line in our Hello World program creates a class named, aptly, HelloWorld. Like a namespace, a class is defined within braces. The following code represents the opening of the HelloWorld class definition:

class HelloWorld
{

A method is a small block of code that performs an action. The Main() method is the "entry point" for every C# console application; it is where your program begins. The next few lines in Hello World mark the beginning of the Main() method:

static void Main()
{

Methods are covered in detail in Chapter 9 but are mentioned in virtually every chapter in this book.

A comment (here in bold) appears just before the start of the Main() method:

// every console app starts with Main
static void Main()
{

A comment is just a note to yourself. You insert comments to make the code more readable to programmers. You can place comments anywhere in your program that you think the explanation will be helpful; they have no effect on the running program.

C# recognizes three styles of comments. The comment in Hello World begins with two slashes (//). The slashes indicate that everything to the right on the same line is a comment.

The second style is to begin your comment with a forward slash followed by an asterisk (/*) and to end your comment with the opposite pattern (*/). These pairs of characters are called the opening C-style comment and the closing C-style comment, respectively.

TIP: These comment symbols were inherited from the C language--thus the names used to identify them. They are also used in C++ and Java.

Everything between these comment symbols is a comment. C-style comments can span more than one line, as in the following:

/* This begins a comment
This line is still within the comment
Here comes the end of the comment */

The third and final style of comments uses three forward slashes ///. This is an XML-style comment and is used for advanced documentation techniques. XML comments are beyond the scope of this book.

Notice that the Main() method is defined with the keywords static and void.

static void Main()

The static keyword indicates that you can access this method without having an object of your class available. While a class defines a type, each instance of that type is an object (much as Car defines a type of vehicle and your aging rust-bucket is an individual instance of Car). Thus, while Button defines a type of control for a Windows program, any individual program will have many Button objects, each with its own label (e.g., OK, Cancel, Retry).

Normally, methods can be called only if you have an object, but static methods are special and can be called without an object. (The use of static methods, other than Main(), is fairly advanced and won't be covered until Chapter 8.)

The second keyword in the statement defining the Main() method is void:

static void Main()

Typically, one method calls another. The called method will do work, and it can return a value to the calling method. (You'll see how methods call one another and return values in Chapter 9.) If a method does not return a value, it is declared void. The keyword void is a signal to the compiler that your method will not return a value to the calling method.

The operating system calls Main() (when the program is invoked). It is possible for Main() to return a value (typically an error code) that might be used in a batch file. In this case, you've declared that Main() will not return a value since you will not be calling this program from a batch file. Every method name is followed by parentheses

static void Main()

It is possible to pass values into a method so that the method can manipulate or use those values. These values are called parameters or arguments. (Method parameters are covered in Chapter 9.) In this case, Main() has no parameters. All methods are enclosed within braces. Within the braces for Main() is a single line of code:

System.Console.WriteLine("Hello world!");

The Console is an object that represents your screen. The Console class is defined within the System namespace, and so its full identification is System.Console.

The Console class has a static method, WriteLine(), which you access not with an instance of Console, but through the Console class itself. Since you access the method with the dot operator, you write System.Console.WriteLine.

The WriteLine() method declares a single parameter: the string you want to display. When you pass a string in to the method, the string is an argument. The argument ("Hello world") corresponds to the parameter the method expects, and the string is displayed. The complete call to the method is:

System.Console.WriteLine("Hello world!");

If you will use many objects from the System namespace, you can save typing by telling the compiler that many of the objects you'll refer to are in that namespace. You do so by adding a using declaration to the beginning of your program:

using System;

Once you add this line, you can use the Console class name without explicitly identifying that it is in the System namespace. If you add the using declaration, you can rewrite the contents of Main() as follows:

Console.WriteLine("Hello world!");

The final series of lines close the various nested opening braces. The first closes the brace for Main(), the second closes the brace for the class, and the third closes the brace for the namespace. Each open brace must be matched by a closing brace.

The class is defined within the namespace declaration, and thus you do not close the namespace until you've closed the class. Similarly, the method Main() is declared within the class, so you do not close the class until you've closed the method.

Whew! That was a lot to take in all at once! Don't panic, all of the concepts introduced here are explained in detail in coming chapters.

Back to: Learning C#


oreilly.com Home | O'Reilly Bookstores | How to Order | O'Reilly Contacts
International | About O'Reilly | Affiliated Companies | Privacy Policy

© 2001, O'Reilly & Associates, Inc.
webmaster@oreilly.com