Скачиваний:
64
Добавлен:
15.03.2015
Размер:
4.31 Mб
Скачать

Chapter 4 • A GUIDED TOUR THROUGH C#: PART II 109

The Math class found in the System namespace of the .NET Framework class library contains many helpful methods to perform various mathematical calculations.

Instead of using just one method to solve a complex computational problem, break the problem into several simpler methods. Every method should accomplish just one clear task. Such a method is described as being cohesive.

Review Questions

1.What are namespaces used for in C# and .NET?

2.What is the advantage of including the keyword using followed by the name of a namespace in the beginning of a program?

3.Which namespace contains classes related to mathematical calculations and console input/output.

4.How should comments be applied in the source code?

5.Describe a variable of type int.

6.Why are x and y often regarded as unacceptable variable identifiers? Why are they acceptable in Listing 4.1?

7.What are the fundamental parts of a method?

8.Why is MoveLeft a bad name for a class? For which C# construct would it be better suited?

9.How do you specify that a method does not return a value?

10.How do you specify that a method returns a value of type int?

11.What are arguments (in method calls)?

12.What are formal parameters?

13.How do arguments and formal parameters relate?

14.Does the + operator only perform arithmetic additions?

15.How can you break down the inner complexities of a class?

16.What is a cohesive method?

110 C# PRIMER PLUS

Programming Exercises

Make the following changes to the program in Listing 4.1:

1.Change the multi-line comments in lines 3–6 to two single line comments.

2.Apart from addition and multiplication, allow the user to perform a subtraction. Among other changes, you need to add a Subtract method. (The symbol – is used to perform subtractions in C#).

3.Instead of calculating the sum and the product of two numbers, make the program perform the calculations on three numbers. (You can ignore the Max and Min functions here.) Hint: You need to declare another int variable in Main. The Sum, Product, and Subtract methods must accept three arguments instead of two. You must allow the user

to input a third number, and you must include the third argument when these methods are called.

4.Create two methods called MyMax and MyMin that both take three arguments and find the maximum and minimum value of these arguments. Hint: Math.Max(Math.Max(a, b),c) returns the max of a, b and c.

C H A P T E R 5

YOUR FIRST OBJECT-ORIENTED

C# PROGRAM

You will learn about the following in this chapter:

The atomic elements of a C#

How to initialize the instance vari-

 

source program

 

ables of your newly created

• The conventional styles used for

 

objects

 

 

 

naming classes, methods, and vari-

The ability of objects to contain

 

ables

 

instance variables that contain

Operators, operands, and expres-

 

other objects

 

 

 

sions (introductory)

How programmers implement

How to write and instantiate your

 

relationships between classes to

 

let them collaborate and form

 

own custom-made classes

 

 

 

object-oriented programs

 

 

 

How the theoretical OO discussion

The Unified Modeling Language

 

about Elevators and Person

 

 

(UML) and how it can be used to

 

classes in Chapter 3, “A Guided

 

 

 

graphically illustrate and model

 

Tour Through C#: Part I,” can be

 

 

 

relationships among classes

 

implemented to form a fully

 

 

 

 

 

working C# program

Three common types of relation-

What a simple object-oriented

 

ships among classes called associa-

 

tion, aggregation, and

 

program looks like and its impor-

 

 

 

composition

 

tant elements

 

 

 

 

Introduction

You have now been presented with two source programs—Listing 3.1 of Chapter 3 and Listing 4.1 of Chapter 4, “A Guided Tour through C#: Part II.” The associated presentation of the C# language constructs has been somewhat guided by the contents of each particular line of code and, consequently, touched on many diverse but interrelated aspects simultaneously. To make up for this fast tour through C#, the first part of this chapter provides an overview of the very basic elements of C#.

112 C# PRIMER PLUS

The last part of the chapter contains the first object-oriented C# program of the book. It builds on previous theoretical OO discussions, in particular the Elevator simulation discussion in the beginning of Chapter 3. Among other things, it allows you to see how the relationship between the Elevator and the Person classes discussed in this earlier section is implemented in C#.

Lexical Structure

When the C# compiler receives a piece of source code to compile, it is faced with the seemingly daunting task of deciphering a long list of characters (more specifically Unicode characters, presented in Appendix E, “Unicode Character Set”) which can be found at www.samspublishing.com and turn them into matching MSIL with exactly the same meaning as the original source code. To make sense of this mass of source code, it must recognize the atomic elements of C#—the unbreakable pieces making up the C# source code. Examples of atomic elements are a brace ({), a parenthesis ((), and keywords like class and if. The task performed by the compiler, associated with differentiating opening and closing braces, keywords, parentheses, and so on is called lexical analysis. Essentially, the lexical issues dealt with by the compiler pertain to how source code characters can be translated into tokens that are comprehensible to the compiler.

C# programs are a collection of identifiers, keywords, whitespace, comments, literals, operators, and separators. You have already met many of these C# elements. The following provides a structured overview of these and, whenever relevant, will introduce a few more aspects.

Identifiers and CaPitaLIzaTioN Styles

Identifiers are used to name classes, methods, and variables. We have already looked at the rules any identifier must follow to be valid and how well-chosen identifiers can enhance the clarity of source code and make it self-documenting. Now we will introduce another aspect related to identifiers—namely CaPitaLIzaTioN sTyLe.

Often programmers choose identifiers that are made up of several words to increase the clarity and the self-documentation of the source code. For example, the words could be child-births- per-year. However, because of the compiler’s sensitivity to whitespace, any identifier broken up into words by means of whitespace will be misinterpreted. For example, a variable to represent the average speed per hour cannot be named average speed per hour. We need to discard whitespace to form one proper token, while maintaining a style allowing the reader of the source code to distinguish the individual words in the identifier. Some computer languages have agreed on the convention average_speed_per_hour. In C#, however, most programmers utilizes an agreed-upon sequence of upperand lowercase characters to distinguish between individual words in an identifier.

Chapter 5 • YOUR FIRST OBJECT-ORIENTED C# PROGRAM 113

A couple of important capitalization styles are applied in the C# world:

Pascal casing—The first letter of each word in the name is capitalized, as in AverageSpeedPerHour.

Camel casing—Same as Pascal casing, with the exception of the first word of the identifier that is lowercase, as in averageSpeedPerHour.

Pascal casing is recommended when naming classes and methods, whereas Camel casing is used for variables.

Tip

Not all computer languages are case sensitive. In these languages, AVERAGE and average are identical to the compiler. For compatibility with these languages, you should avoid using case as the distinguishing factor between public identifiers accessible from other languages.

Literals

Consider the following two lines of source code:

int number; number = 10;

number is clearly a variable. In the first line, we declare number to be of type int. In the second line, we assign 10 to number. But what is 10? Well, 10 is incapable of changing its value and is named a literal. Literals are not confined to numbers. They can also be characters, such as B, $, and z or text, such as “This is a literal.” Literals can be stored by any variable with a type compatible with that of the literal.

Comments and Source Code Documentation

The main characteristic of comments is the compiler’s ability to totally ignore them. We have so far seen two ways of making comments—single line with // and multi-line using /* */.

In fact, there is a third type that allows you to write the documentation as part of the source code as shown in this chapter, but with the added ability of extracting this documentation into separate Extensible Markup Language (XML) files. For now, you can appreciate a particular useful end result of this feature; you just need to take a look at the .NET Framework class library documentation, which was created by extracting XML files from the comments/documentation sitting inside the original source code.

Separators

Separators are used to separate various elements in C# from each other. You have already met many of them. An example is the commonly used semicolon ; that is required to terminate a statement. Table 5.1 summarizes the separators we have presented to so far.

114 C# PRIMER PLUS

TABLE 5.1 Important Separators in C#

Name

Symbol

Purpose

Braces

{ }

Used to confine a block of code for classes, methods, and the, yet to be

 

 

presented, branching and looping statements.

 

 

 

Parentheses

( )

Contains lists of formal parameters in method headers and lists of argu-

 

 

ments in method invocation statements. Also required to contain the

 

 

Boolean expression of an if statement and other, yet to be presented,

 

 

branching and looping statements.

 

 

 

Semicolon

;

Terminates a statement.

 

 

 

Comma

,

Separates formal parameters inside the parentheses of a method header

 

 

and separates arguments in a method invocation statement.

 

 

 

Period

.

Used to reference namespaces contained inside other namespaces and to

(dot operator)

 

specify classes inside namespaces and methods (if accessible) inside

 

 

classes and objects. It can also be used to specify instance variables inside

 

 

classes and objects (if accessible), but this practice should be avoided.

 

 

 

Operators

Operators are represented by symbols such as + , = , ==, and *. Operators act on operands, which are found next to the operator. For example

SumTotal + 10

contains the + operator surrounded by the two operands sumTotal and 10. In this context, the + operator combines two operands to produce a result and so it is classified as a binary operator. Some operators act on only one operand; they are termed unary operators.

Operators, together with their operands, form expressions. A literal or a variable by itself is also an expression, as are combinations of literals and variables with operators. Consequently, expressions can be used as operands as long as the rules, which apply to each individual operator, are adhered to, as shown in the following example:

expressions expressions

mySum = (a + 5) * (10 + d);

expression

expressions

a, 5, and 10, d are all expressions acted on by the + operator. However, (a + 5) and (10 + d) are also expressions acted on by the * operator. Finally, (a + 5) * (10 + d) can be regarded