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

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

Интервал:

Закладка:

Сделать

int num = 9;

if (num % 2 == 0) Console.WriteLine("{0} is even", num);

else Console.WriteLine("{0} is odd", num);

In this example, if nummodulus 2 equals to 0, the statement "9 is even" is printed; otherwise ( else), "9 is odd" is printed.

Remember to wrap the Boolean expression in a pair of parentheses when using the ifstatement.

If you have multiple statements to execute after an if-elseexpression, enclose them in {}, like this:

int num = 9;

if (num % 2 == 0) {

Console.WriteLine("{0} is even", num);

Console.WriteLine("Print something here...");

}

else {

Console.WriteLine("{0} is odd", num);

Console.WriteLine("Print something here...");

}

Here's another example of an if-elsestatement:

int num = 9;

string str = string.Empty;

if (num % 2 == 0) str = "even";

else str = "odd";

You can rewrite these statements using the conditional operator ( ?:), like this:

str = (num % 2 == 0) ? "even" : "odd";

Console.WriteLine(str); //---odd---

?:is also known as the ternary operator.

The conditional operator has the following format:

condition ? first_expression : second_expression;

If condition is true, the first expression is evaluated and becomes the result; if false, the second expression is evaluated and becomes the result.

switch Statement

You can evaluate multiple expressions and conditionally execute blocks of code by using if-elsestatements. Consider the following example:

string symbol = "YHOO";

if (symbol == "MSFT") {

Console.WriteLine(27.96);

} else if (symbol == "GOOG") {

Console.WriteLine(437.55);

} else if (symbol == "YHOO") {

Console.WriteLine(27.15);

} else Console.WriteLine("Stock symbol not recognized");

One problem with this is that multiple ifand else-ifconditions make the code unwieldy — and this gets worse when you have lots of conditions to check. A better way would be to use the switchkeyword:

switch (symbol) {

case "MSFT":

Console.WriteLine(27.96);

break;

case "GOOG":

Console.WriteLine(437.55);

break;

case "YHOO":

Console.WriteLine(27.15);

break;

default:

Console.WriteLine("Stock symbol not recognized");

break;

}

The switchkeyword handles multiple selections and uses the casekeyword to match the condition. Each casestatement must contain a unique value and the statement, or statements, that follow it is the block to execute. Each casestatement must end with a breakkeyword to jump out of the switch block. The defaultkeyword defines the block that will be executed if none of the preceding conditions is met.

The following example shows multiple statements in a casestatement:

string symbol = "MSFT";

switch (symbol) {

case "MSFT":

Console.Write("Stock price for MSFT: ");

Console.WriteLine(27.96);

break;

case "GOOG":

Console.Write("Stock price for GOOG: ");

Console.WriteLine(437.55);

break;

case "YHOO":

Console.Write("Stock price for YHOO: ");

Console.WriteLine(27.15);

break;

default:

Console.WriteLine("Stock symbol not recognized");

break;

}

In C#, fall-throughs are not allowed; that is, each caseblock of code must include the breakkeyword so that execution can be transferred out of the switchblock (and not "fall through" the rest of the casestatements). However, there is one exception to this rule — when a caseblock is empty. Here's an example:

string symbol = "INTC";

switch (symbol) {

case "MSFT":

Console.WriteLine(27.96);

break;

case "GOOG":

Console.WriteLine(437.55);

break;

case "INTC":

case "YHOO":

Console.WriteLine(27.15);

break;

default:

Console.WriteLine("Stock symbol not recognized");

break;

}

The casefor " INTC" has no execution block/statement and hence the execution will fall through into the case for " YHOO", which will incorrectly print the output " 27.15". In this case, you need to insert a break statement after the " INTC" case to prevent the fall-through:

switch (symbol) {

case "MSFT":

Console.WriteLine(27.96);

break;

case "GOOG":

Console.WriteLine(437.55);

break;

case "INTC":

break;

case "YHOO":

Console.WriteLine(27.15);

break;

default:

Console.WriteLine("Stock symbol not recognized");

break;

}

Looping

A loop is a statement, or set of statements, repeated for a specified number of times or until some condition is met. C# supports the following looping constructs:

for

foreach

whileand do-while

for Loop

The forloop executes a statement (or a block of statements) until a specified expression evaluates to false. The forloop has the following format:

for (statement; expression; statement(s)) {

//---statement(s)

}

The expression inside the forloop is evaluated first, before the execution of the loop. Consider the following example:

int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

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

Console.WriteLine(nums[i].ToString());

}

Here, nums is an integer array with nine members. The initial value of i is 0 and after each iteration it increments by 1. The loop will continue as long as iis less than 9. The loop prints out the numbers from the array:

1

2

3

4

5

6

7

8

9

Here' s another example:

string[] words = { "C#","3.0","Programming","is","fun"};

for (int j = 2; j <= 4; ++j) {

Console.WriteLine(words[j]);

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

Интервал:

Закладка:

Сделать

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

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


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

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

x