Wei-Meng Lee - C# 2008 Programmer's Reference

Здесь есть возможность читать онлайн «Wei-Meng Lee - C# 2008 Programmer's Reference» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Город: Indianapolis, Год выпуска: 2009, ISBN: 2009, Издательство: Wiley Publishing, Inc., Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

C# 2008 Programmer's Reference: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «C# 2008 Programmer's Reference»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

C# 2008 Programmers Reference provides a concise and thorough reference on all aspects of the language. Each chapter contains detailed code samples that provide a quick and easy way to understand the key concepts covered.

C# 2008 Programmer's Reference — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «C# 2008 Programmer's Reference», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

The AllNumbersZeroExceptionclass contains three overloaded constructors that initialize the constructor in the base class. To see how you can use this custom exception class, let's take another look at the program you have been using all along:

static void Main(string[] args) {

int num1, num2, result;

try {

Console.Write("Please enter the first number:");

num1 = int.Parse(Console.ReadLine());

Console.Write("Please enter the second number:");

num2 = int.Parse(Console.ReadLine());

Program myApp = new Program();

Console.WriteLine("The result of {0}/{1} is {2}", num1, num2,

myApp.PerformDivision(num1, num2));

} catch (AllNumbersZeroException ex) {

Console.WriteLine(ex.Message);

} catch (DivideByZeroException ex) {

Console.WriteLine(ex.Message);

} catch (ArithmeticException ex) {

Console.WriteLine(ex.Message);

} catch (FormatException ex) {

Console.WriteLine(ex.Message);

} catch (Exception ex) {

Console.WriteLine(ex.Message);

}

Console.ReadLine();

}

private int PerformDivision(int num1, int num2) {

if (num1 == 0 && num2 == 0) {

AllNumbersZeroException ex =

new AllNumbersZeroException("Both numbers cannot be 0.") {

HelpLink = "http://www.learn2develop.net"

};

throw ex;

}

if (num1 == 0) {

ArithmeticException ex =

new ArithmeticException("Value of num1 cannot be 0.") {

HelpLink = "http://www.learn2develop.net"

};

throw ex;

}

if (num2 == 0) {

DivideByZeroException ex =

new DivideByZeroException("Value of num2 cannot be 0.") {

HelpLink = "http://www.learn2develop.net"

};

throw ex;

}

return num1 / num2;

}

This program shows that if both num1and num2are zero, the AllNumbersExceptionexception is raised with the custom message set.

Here's the output when 0 is entered for both num1and num2:

Please enter the first number:0

Please enter the second number:0

Both numbers cannot be 0.

Summary

Handling exceptions is part and parcel of the process of building a robust application, and you should spend considerable effort in identifying code that is likely to cause an exception. Besides catching all the exceptions defined in the .NET Framework, you can also define your own custom exception containing your own specific error message.

Chapter 13

Arrays and Collections

In programming, you often need to work with collections of related data. For example, you may have a list of customers and you need a way to store their email addresses. In that case, you can use an array to store the list of strings.

In .NET, there are many collection classes that you can use to represent groups of data. In addition, there are various interfaces that you can implement so that you can manipulate your own custom collection of data.

This chapter examines:

□ Declaring and initializing arrays

□ Declaring and using multidimensional arrays

□ Declaring a parameter array to allow a variable number of parameters in a function

□ Using the various System.Collectionsnamespace interfaces

□ Using the different collection classes (such as Dictionary, Stacks, and Queue) in .NET

Arrays

An array is an indexed collection of items of the same type. To declare an array, specify the type with a pair of brackets followed by the variable name. The following statements declare three array variables of type int, string, and decimal, respectively:

int[] num;

string[] sentences;

decimal[] values;

Array variables are actually objects. In this example, num, sentences, and valuesare objects of type System.Array.

These statements simply declare the three variables as arrays; the variables are not initialized yet, and at this stage you do not know how many elements are contained within each array.

To initialize an array, use the newkeyword. The following statements declare and initialize three arrays:

int[] num = new int[5];

string[] sentences = new string[3];

decimal[] values = new decimal[4];

The numarray now has five members, while the sentencesarray has three members, and the valuesarray has four. The rank specifier of each array (the number you indicate within the []) indicates the number of elements contained in each array.

You can declare an array and initialize it separately, as the following statements show:

//---declare the arrays---

int[] num;

string[] sentences;

decimal[] values;

//---initialize the arrays with default values---

num = new int[5];

sentences = new string[3];

values = new decimal[4];

When you declare an array using the new keyword, each member of the array is initialized with the default value of the type. For example, the preceding numarray contains elements of value 0. Likewise, for the sentencesstring array, each of its members has the default value of null.

To learn the default value of a value type, use the default keyword, like this:

object x;

x = default(int); //---0---

x = default(char); //---0 '\0'---

x = default(bool); //---false---

To initialize the array to some value other than the default, you use an initialization list. The number of elements it includes must match the array's rank specifier. Here's an example:

int[] num = new int[5] { 1, 2, 3, 4, 5 };

string[] sentences = new string[3] {

"C#", "Programmers", "Reference"

};

decimal[] values = new decimal[4] {1.5M, 2.3M, 0.3M, 5.9M};

Because the initialization list already contains the exact number of elements in the array, the rank specifier can be omitted, like this:

int[] num = new int[] { 1, 2, 3, 4, 5 };

string[] sentences = new string[] {

"C#", "Programmers", "Reference"

};

decimal[] values = new decimal[] {1.5M, 2.3M, 0.3M, 5.9M};

Use the new varkeyword in C# to declare an implicitly typed array:

var num = new [] { 1, 2, 3, 4, 5 };

var sentences = new [] {

"C#", "Programmers", "Reference"

};

var values = new [] {1.5M, 2.3M, 0.3M, 5.9M};

For more information on the varkeyword, see Chapter 3.

In C#, arrays all derive from the abstract base class Array(in the System namespace) and have access to all the properties and methods contained in that. In Figure 13-1 IntelliSense shows some of the properties and methods exposed by the numarray.

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «C# 2008 Programmer's Reference»

Представляем Вашему вниманию похожие книги на «C# 2008 Programmer's Reference» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «C# 2008 Programmer's Reference»

Обсуждение, отзывы о книге «C# 2008 Programmer's Reference» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x