Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Microsoft CSharp Programming For The Absolute Beginner (2002) [eng]-1.pdf
Скачиваний:
46
Добавлен:
16.08.2013
Размер:
15.71 Mб
Скачать

program. After reading this chapter, you will be able to write something like it.

Note that the user interface is Spartan—no flashy graphics or eye−catching buttons and menus. For now, you are concentrating on the underlying concepts. Those other elements will come soon enough, but they add complications to your life (which you don’t need just yet).

Reviewing Basic C# Concepts

The C# language was designed to profit from the experiences of other programming languages. The basic concepts behind C# programming are apparent in even the simplest programs. Essentially, a C# program can be thought of as an onion with a bunch of layers (see Figure 1.3).

Figure 1.3: In C# programming, you have code inside methods, which are inside classes, which are inside namespaces

In the .NET environment (of which C# is a primary language) are layers of code that go from general to specific. The outer, most general, layer is the namespace. Inside a namespace, you find a series of classes, which contain methods, which contain statements.

Trap Actually, this is a simplified view. As you progress through this book (and beyond), you will see that the .NET model contains other elements. However, this reduced version of the model will suffice for now.

6

Namespaces

The various layers of programming help you organize your programs. Even as a beginner, you need to understand a little bit about the various layers because even the most rudimentary programs use them. Think of the layers as something like an address on an envelope. When you address an envelope, you write specific information, such as the house number. You also put the street name, which is more general, and the state, which is broad. The post office can deliver your letter by getting it to the correct state, then the correct city, then the right part of the city, and finally the specific house. Namespaces in the C# language work very much like this.

The largest landscape in the C# universe is a namespace. You can think of a namespace as a state in the postal analogy. A namespace is an element that enables you to group together a series of other things. Each project you create is usually a namespace. In addition, all the various things you can use in your programs—including the computer system itself, and Windows elements, such as text boxes and buttons—are separated into namespaces. Frequently, you specify which namespaces you want to work with, for example, to define whether a program should use Windows forms or a special library of math functions. If all this seems unclear to you, don’t worry about it. Soon you will see examples that make it clear.

Classes

A namespace is usually made up of one or more classes. A class is a definition for a specific kind of object. Throughout the entire book, you will be learning about classes and objects, but essentially, they are used to describe some type of entity.

Anything a computer can describe (a database, a file, an image, a cow, whatever) can be encoded as an object. The things an object can do are called its methods, and the characteristics of an object are called its properties. Don’t worry, there isn’t a quiz on all this theory. You do need an introduction to these concepts, though, because all of C# is based on the idea of objects.

Methods

Classes always have methods. A method is a structure that contains instructions. All the commands in a program are housed in various methods of objects. Most programs have a special method named Main() (method names always end in parentheses), which is meant to execute as soon as the program begins running. If you are familiar with other languages, such as C or Visual Basic, you will see that methods are a lot like functions or subprograms in those languages.

Statements

Inside a method, you write the instructions you want the computer to execute. A statement is an instruction. Many statements (sometimes also called commands) involve using methods of built−in objects. Of course, a computer scientist wouldn’t usually say using a method, because everyone would understand that. Often C# folks will refer to the process as invoking a method. Maybe at dinner tonight rather than asking somebody to pass the salt, you could say “Could you please invoke the salt shaker object’s pass method?” It should liven up the conversation. Other commands are built in to the structure of the language.

Trick Don’t worry if all this talk about methods and namespaces is making you dizzy. You don’t have to memorize all this now, but you will be using it later. Even the simplest program uses all these levels of instruction, so you need to have some idea of these terms. However, you probably won’t fully understand them until you build a few custom namespaces, classes,

7

and methods down the road. Everybody spends time in confusion until the larger picture becomes clear.

The Console Object

To see how all this works, take a look at one specific object, the console. In the bad old days of computing before visual interfaces like Windows, all interaction with a computer was done through a plain text screen. The combination of the text screen and the keyboards is usually referred to as the console. Although programming on the console might seem kind of old−fashioned, it’s a good place to start because programs which feature the console are easier to write than the fancier programs using Windows forms. In C#, everything is an object, so you’ll work with the console by working with a special object, also called the Console. Note that the names of classes are capitalized, so when I’m referring to the actual Console, class, I use a capital C. Most of your early programs will be built using the Console object, so taking a look at how C# sees this object is a good idea. If you remember working in DOS or command−line UNIX, you probably have some fond memories of the console. Most console applications use only text and appear only in black and white. Modern programs for end users don’t usually work with the console because it makes things much more difficult for users who prefer menus, buttons, and toolbars. However, knowing how to program on the console is still useful because some applications don’t require a graphic user interface, such as server−side programs in Web development, code libraries, and simple applications. The main reason I’m starting you out on the console, though, is that it’s a much easier place to program. Although all those graphic elements make the user’s life easier, they can cause headaches for beginning programmers.

Trick In the earlier days of computing, all computing happened on a simple black−and−white text screen. It was an easy way to learn programming because you had fewer things to learn (and fewer things could go wrong). Programming on the console is still a very important skill, and because it’s still a relatively easy place to work, you start there in your programming journey. You will be able to write programs that look more familiar to a Windows user or a Web surfer as you progress through this book, but all the main ideas can be demonstrated using the generally simpler console.

The console itself can be thought of as a DOS window. If you’ve been around computing for a while, you probably remember the days when you had to type all your commands into a text−only window. The Console object is the way C# views that window, which is still available in modern computing, and is surprisingly useful. To do anything useful with the console, you need to know how to use the Console class within C#, which ships with documentation describing all the various parts of the language. Looking through this documentation will also give you a sense of how the language is organized.

.NET Documentation

To understand the general layout of the language, take a look at Microsoft’s official documentation for the .NET framework. This should be installed on your machine as part of the Visual Studio environment, but it may appear as a separate element in the Start menu. (On my machine, it is Programs, Microsoft .NET framework SDK, Documentation.) Figure 1.4 shows this screen in action.

8

Figure 1.4: Here’s the .NET documentation. I’ve expanded the tree on the left to show the various namespaces available in the .NET environment.

Trick If the .NET documentation is not available on your machine, you should install it before going much further. It is a road map to all of C#, and your way will be much easier if you have access to this map.

A huge amount of information is in the .NET documentation, but you don’t need to concern yourself with all of it. For now, I just want you to see what’s there. The right panel shows a long (intimidating) list of namespaces available to you as a programmer. When the documentation first comes up, you won’t see much in the right−hand panel, so, click the System link under Namespaces to see the contents of the System namespace.

In the Real World

You might be confused about the relationship between C# and .NET. This confusion is understandable because the two technologies are very closely intertwined. .NET is Microsoft’s term for its new programming architecture. The basic idea of .NET is to have several languages use the same underlying architecture, which should have a natural relationship with the various forms of the Windows operating system. Most of Microsoft’s next generation of programming languages, including the latest editions of C++ and Visual Basic, use the .NET environment. However, C# is the first major language designed from the beginning with .NET in mind. Because of this, many pundits speculate that C# will be the most commonly used language in the .NET universe. All programmers in the Microsoft world (there are other kinds of programming) will probably have to learn some form of the .NET model, so C# is a natural choice because of its close relationship with the model. Throughout this book, when you learn about specific syntax issues (such as where to put semicolons and how the assignment operator works), you’re actually learning the C# language. When you learn about certain objects, such as the Console object or command buttons, you’re learning about the .NET universe. If you don’t see the distinction yet, that’s okay. Just note that if you ever want to learn another .NET language (such as Visual Basic, or VB), you will find it an easy jump because both C# and VB use the.NET framework. The .NET framework also provides some interesting possibilities for Internet programming, but these techniques do not work on every web server.

9

The System Namespace

As you can see in Figure 1.5, the System namespace consists of many (again, intimidating) classes. Each of these classes represents an object you can use to write your programs. For now, you can safely ignore most of them, but there is a class to represent the console. Click the appropriate link to examine the Console class. The page of text you see is almost useless, but at the bottom of that page is a link named Console Members. Click this link to learn about the characteristics of the Console class and the things it can do.

Figure 1.5: Some classes in the System namespace. The Console has features for communicating with the user that will be helpful.

The Console Class

The Console is a simple (but important) class. Like most classes, it has properties (which you will ignore for now) and methods (shown in Figure 1.6). Methods are the tasks that the Console object knows how to do. You want to do one thing in this program—write a message to the user.

Fortunately, the Console class contains several methods designed to do exactly that. Take a careful look at Write().

10

Figure 1.6: The members of the Console class.

The Write() Method

The Write() method enables you to write a message to the text screen. Anything you want to write to the screen should be enclosed in quotes inside the parentheses. If you want to write Hi, Mom!, use this command:

System.Console.Write("Hi, Mom!");

This command demonstrates the entire hierarchy of structures in C#. System is a namespace, which contains the Console class, which contains the Write() method. This is cumbersome enough to warrant a loophole. If you use the command

using System;

at the beginning of your program, you no longer have to specify System, and you can simply write

Console.Write("Hi, Mom!");

The WriteLine() Method

The Write() method has an even smarter cousin, named WriteLine(). The easiest way to explain the difference between them is with a demonstration.

This code fragment

Console.Write("Hi, ");

Console.Write("Mom!");

appears on the console as Hi, Mom!.

11

Trap Console.Write does not add anything to the text. Note that I include a space after the comma in "Hi, ". Without the space, the output would be Hi,Mom!.

Each invocation of Console.Write() causes the new text to be written at the next spot on the screen, usually on the same line. Often, you are generating one line of text at a time. The Console.WriteLine() method is used to write text as a complete line, adding a new line (like pressing the Enter key in a word processor) to the end of the line. Here’s an example:

Console.WriteLine("Hi");

Console.WriteLine("Mom");

Output:

Hi

Mom

Although knowing about the Write() and WriteLine() methods is helpful, understanding how to get around in the documentation is even more important. Whenever you want to accomplish a task in C#, usually you can find a method attached to an object in a particular namespace that will fulfill your needs.

Saying “Hello, World!”

The programming world has a surprising number of well−established traditions. One of them is the Hello World program, which is the first program you write in any new environment. It simply pops up on the screen and says, Hello, World!. This is a fun tradition but also has a practical side. It is usually the simplest kind of activity you can make a computer do in a given language. By starting with such a simple program, you can focus your efforts on becoming comfortable with the programming environment. With a debugging and programming package as complex as Visual Studio, starting with a simple program so that you can get your feet wet in the environment makes a lot of sense.

The Hello World program featured in Figure 1.7 doesn’t do much, but it illustrates several important ideas in programming. When you understand the code behind this very simple program, you will have a framework that can be reused for every C# program you write.

Figure 1.7: As advertised, the program says “Hello, World!”

12

Соседние файлы в предмете Программирование на C++