Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# ПІДРУЧНИКИ / c# / Manning - Windows.forms.programming.with.c#.pdf
Скачиваний:
108
Добавлен:
12.02.2016
Размер:
14.98 Mб
Скачать

C# keywords

(continued)

 

 

 

 

 

 

Keyword

 

Description

Example

See also

 

 

 

 

 

unsafe

 

Indicates an unmanaged

See example for stackalloc keyword.

 

 

 

region of code, in which

 

 

 

 

pointers are permitted and

 

 

 

 

normal runtime verification is

 

 

 

 

disabled.

 

 

ushort

 

Denotes an unsigned 16-bit

ushort apprxCircum

uint;

 

 

integer value. A cast is

ushort radius = (ushort)7;

ulong

 

 

required to convert an int or

ushort pi = (ushort)314;

 

 

 

apprxCircum = (ushort)2

 

 

 

uint value to ushort.

 

 

 

* pi * radius / (ushort)100;

 

using

 

As a directive, indicates a

using System.Windows.Forms;

section 1.2.1 on

 

 

namespace from which types

using App = Application;

page 15

 

 

do not have to be fully

public void Main()

 

 

 

qualified.

 

 

 

{

 

 

 

Alternatively, indicates a

Form f = new MainForm();

 

 

 

shortcut, or alias, for a given

App.Run(f);

 

 

 

class or namespace name.

}

 

 

 

 

 

 

 

As a statement, defines a

using (OpenFileDialog dlg

discussion in

 

 

scope for a given expression or

= new OpenFileDialog())

section 8.2.1,

 

 

type. At the end of this scope,

{

page 233

 

 

// Do something with dlg

 

 

the given object is disposed.

 

 

 

}

 

virtual

 

Declares that a method or

See example for override keyword.

override;

 

 

property member may be

 

section 9.1.1,

 

 

overridden in a derived class.

 

page 265

 

 

At runtime, the override of a

 

 

 

 

type member is always

 

 

 

 

invoked.

 

 

volatile

 

Indicates that a field may be

// Read/Write x anew for each line.

 

 

 

modified in a program at any

volatile double x = 70.0;

 

 

 

time, such as by the operating

int num = x;

 

 

 

x = x * Sqrt(x);

 

 

 

system or in another thread.

 

 

 

 

 

void

 

Indicates that a method does

See examples for override and protected key-

examples

 

 

not return a value.

words.

throughout text

while

 

As a statement, executes a

Photograph p = _album.FirstPhoto;

for;

 

 

statement or block of

while (p != null)

foreach

 

 

statements until a given

{

 

 

 

// Do something with Photograph

 

 

 

expression is false.

 

 

 

p = _album.NextPhoto;

 

 

 

 

}

 

 

 

In a do-while loop, specifies

See example for do keyword.

do;

 

 

the condition that will

 

 

 

 

terminate the loop.

 

 

 

 

 

 

 

A.4 SPECIAL FEATURES

This section presents some noteworthy features of the C# language. These topics did not fit in previous sections of this appendix, but are important concepts for

SPECIAL FEATURES

667

programming in the language. The topics covered are exceptions, arrays, the Main entry point, boxing, and documentation.

Readers more familiar with C# will recognize certain features omitted from this discussion and the book in general. These include attributes, reflection, and the preprocessor. These features, while important, were considered beyond the scope of this book, and are not required in many Windows Forms applications. A brief discussion of attributes is provided in chapter 2 as part of a discussion on the AssemblyInfo.cs file.

A.4.1 EXCEPTIONS

An exception is a type of error. Exceptions provide a uniform type-safe mechanism for handling system level and application level error conditions. In the .NET Framework, all exceptions inherit from the System.Exception class. Even system-level errors such as divide-by-zero and null references have well-defined exception classes.

If a program or block of code ignores exceptions, then exceptions are considered unhandled. By default, an unhandled exception immediately stops execution of a program.2 This ensures that code which ignores exceptions does not continue processing when an error occurs. Code that does not ignore exceptions is said to handle exceptions, and must indicate the specific set of exception classes that are handled by the code. An exception is said to be handled or caught if a block of code can continue processing after an exception occurs. Code which generates an exception is said to throw the exception.

The try keyword is used to indicate a block of code that handles exceptions. The catch keyword indicates which exceptions to explicitly handle. The finally keyword is used to indicate code that should be executed regardless of whether an exception occurs.

Code that handles one or more exceptions in this manner uses the following format:

try

<try-block>

<catch-blocks>opt

<finally-block>opt

where

<try-block> is the set of statements, enclosed in braces, that should handle exceptions.

<catch-blocks> is optional, and consists of one or more catch blocks as defined below.

2 Well, most of the time. If an unhandled exception occurs during the execution of a static constructor, then a TypeInitializationException is thrown rather than the program exiting. In this case, the original exception is included as the inner exception of the new exception.

668

APPENDIX A C# PRIMER

<finally-block> is optional, and consists of the finally keyword followed by the set of statements, enclosed in braces, that should execute whether or not an exception occurs.

The format of a try block allows for one or more catch blocks, also called catch clauses, to define which exceptions to process. These are specified with the catch keyword in the following manner:

catch <exception>opt

<catch-block>

where

<exception> is optional, and indicates the exception this catch clause will handle. This must be a class enclosed in parenthesis with an optional identifier that the block will use to reference this exception. If no class is provided, then all exceptions are handled by the clause.

<catch-block> is the set of statements, enclosed in braces, that handles the given exception.

For example, one use for exceptions is to handle unexpected conversion errors, such as converting a string to an integer. The following side-by-side code contrasts two ways of doing this:

// A string theString requires conversion int version = 0;

try

{

version = Convert.ToInt32(theString);

}

catch

{

version = 0;

}

If any exception occurs while converting the string to an int, then the catch clause will set version to 0. For example, if the theString variable is null, an ArgumentException will occur, and version will still be set to 0.

// A string theString requires conversion int version = 0;

try

{

version = Convert.ToInt32(theString);

}

catch (FormatException)

{

version = 0;

}

The catch clause will set version to 0 only if a FormatException exception occurs while converting the string to an int. Any other exception is unhandled and will exit the program if not handled by a previous method.

When an exception occurs in a program that satisfies more than one catch block within the same try block, the first matching block is executed. For this reason, the more distinct exceptions should appear first in the list of catch blocks. As an example, consider the IOException class, which is thrown when an unexpected I/O error occurs. This class derives from the Exception class. The following code shows how an exception block might be written to handle exceptions that might occur while reading a file:

// Open some file system object

FileStream f = new FileStream(...);

SPECIAL FEATURES

669

try

{

//Code that makes use of FileStream object

}

catch (IOException ioex)

{

//Code that handles an IOException

//This code can use the "ioex" variable to reference the exception

}

catch (Exception ex)

{

// Code that handles any other exception

}

Additional examples of exceptions appear throughout the book, beginning in section 2.3.2 on page 58.

A.4.2 ARRAYS

An array is a data structure consisting of a collection of variables, all of the same type. Arrays are built into C# and may be one-dimensional or many-dimensional. Each dimension of an array has an associated integral length. Arrays are treated as reference types. In the .NET Framework, the System.Array class serves as the base class for all array objects. More information on the Array and related ArrayList class can be found in chapter 5.

A standard array for any type is constructed using square brackets in the following manner:

<type> [ <dimension>opt ]

where

<type> is the non-array type for the array. A non-array type is any type that is not an array.

<dimension> is zero or more commas ‘,’ indicating the dimensions of the array.

Note that multiple square brackets may be specified to have variable length array elements. An example of this is shown below. To reference a value in an array, square brackets are again used, with an integer expression from zero (0) to one less than the length of the array. If an array index is outside of the valid range of the array, an IndexOutOfRangeException object is thrown as an exception.

Some examples of arrays and additional comments on the use of arrays are given below. Note that the Length property from the System.Array class determines the number of elements in an array, and the foreach keyword can be used on all arrays to enumerate the elements of the array.

// an uninitialized array defaults to null

int[] a;

670

APPENDIX A C# PRIMER

Соседние файлы в папке c#