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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

} catch (Exception e) {

Console.WriteLine(e.Message);

}

}

}

When the foreachloop reaches the fifth element of the array (0), it throws an exception and exits the loop. The exception is then caught by the try-catchloop in the Main()method.

goto

The goto keyword transfers program control directly to a labeled statement. Using goto is not considered a best practice because it makes your program hard to read. Still, you want to be aware of what it does, so the following example shows its use:

string[] words = {

"-online", "4u", "adipex", "advicer", "baccarrat", "blackjack",

"bllogspot", "booker", "byob", "car-rental-e-site",

"car-rentals-e-site", "carisoprodol", "casino", "casinos",

"chatroom", "cialis", "coolcoolhu", "coolhu",

"credit-card-debt", "credit-report-4u"

};

foreach (string word in words) {

if (word == "casino")

goto Found;

}

goto Resume;

Found:

Console.WriteLine("Word found!");

Resume:

//---other statements here---

In this example, if the word casino is found in the wordsarray, control is transferred to the label named Found:and execution is continued from there. If the word is not found, control is transferred to the label named Resume:.

Skipping an Iteration

To skip to the next iteration in the loop, you can use the continuekeyword. Consider the following block of code:

for (int i = 0; i < 9; i++) {

if (i % 2 == 0) {

//---print i if it is even---

Console.WriteLine(i);

continue;

}

//---print this when i is odd---

Console.WriteLine("******");

}

When i is an even number, this code block prints out the number and skips to the next number. Here's the result:

0

******

2

******

4

******

6

******

8

Operators

C# comes with a large set of operators that allows you to specify the operation to perform in an expression. These operators can be broadly classified into the following categories:

□ Assignment

□ Relational

□ Logical (also known as conditional)

□ Mathematical

Assignment Operators

You've already seen the use of the assignment operator ( =). It assigns the result of the expression on its left to the variable on its right:

string str = "Hello, world!"; //---str is now "Hello, world!"---

int num1 = 5;

int result = num1 * 6; //---result is now 30---

You can also assign a value to a variable during declaration time. However, if you are declaring multiple variables on the same line, only the variable that has the equal operator is assigned a value, as shown in the following example:

int num1, num2, num3 = 5; //---num1 and num2 are unassigned; num3 is 5---

int i, j = 5, k; //---i and k are unassigned; j is 5---

You can also use multiple assignment operators on the same line by assigning the value of one variable to two or more variables:

num1 = num2 = num3;

Console.WriteLine(num1); //---5---

Console.WriteLine(num2); //---5---

Console.WriteLine(num3); //---5---

If each variable has a unique value, it has to have its own line:

int num1 = 4

int num2 = 3

int num3 = 5

Self-Assignment Operators

A common task in programming is to change the value of a variable and then reassign it to itself again. For example, you could use the following code to increase the salary of an employee:

double salary = 5000;

salary = salary + 1000; //---salary is now 6000---

Similarly, to decrease the salary, you can use the following:

double salary = 5000;

salary = salary - 1000; //---salary is now 4000---

To halve the salary, you can use the following:

double salary = 5000;

salary = salary / 2; //---salary is now 2500--

To double his pay, you can use the following:

double salary = 5000;

salary = salary * 2; //---salary is now 10000---

All these statements can be rewritten as follows using self-assignment operators:

salary += 1000; //---same as salary = salary + 1000---

salary -= 1000; //---same as salary = salary - 1000

salary /= 2; //---same as salary = salary / 2---

salary *= 2; //---same as salary = salary * 2---

A self-assignment operator alters its own value before assigning the altered value back to itself. In this example, +=, -=, /=, and *=are all self-assignment operators.

You can also use the modulus self-assignment operator like this:

int num = 5;

num %= 2; //---num is now 1---

Prefix and Postfix Operators

The previous section described the use of the self-assignment operators. For example, to increase the value of a variable by 1, you would write the statement as follows:

int num = 5;

num += 1; //---num is now 6---

In C#, you can use the prefix or postfix operator to increment/decrement the value of a variable by 1. The preceding statement could be rewritten using the prefix operator like this:

++num;

Alternatively, it could also be rewritten using the postfix operator like this:

num++;

To decrement a variable, you can use either the prefix or postfix operator, like this:

--num;

//---or---

num--;

So what is the difference between the prefix and postfix operators? The following example makes it clear:

int num1 = 5;

int num2 = 5;

int result;

result = num1++;

Console.WriteLine(num1); //---6---

Console.WriteLine(result); //---5---

result = ++num2;

Console.WriteLine(num2); //---6---

Console.WriteLine(result); //---6---

As you can see, if you use the postfix operator ( num1++), the value of num1is assigned to result before the value of num1is incremented by 1. In contrast, the prefix operator ( ++num2) first increments the value of num2by 1 and then assigns the new value of num2(which is now 6) to result.

Here's another example:

int num1 = 5;

int num2 = 5;

int result;

result = num1++ + ++num2;

Console.WriteLine(num1); //---6---

Console.WriteLine(num2); //---6---

Console.WriteLine(result); //---11---

In this case, both num1and num2are initially 5. Because a postfix operator is used on num1, its initial value of 5 is used for adding. And because num2uses the prefix operator, its value is incremented before adding, hence the value 6 is used for adding. This adds up to 11 (5 + 6). After the first statement, both num1and num2would have a value of 6.

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

Интервал:

Закладка:

Сделать

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

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


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

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

x