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

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

Интервал:

Закладка:

Сделать

Implicit-typing is very useful when using LINQ queries. Chapter 14 discusses LINQ in more detail.

Type Conversion

C# is a strongly typed language, so when you are assigning values of variables from one type to another, you must take extra care to ensure that the assignment is compatible. Consider the following statements where you have two variables — one of type intand another of type short:

int num;

short sNum = 20;

The following statement assigns the value of sNumto num:

num = sNum; //---OK---

This statement works because you're are assigning the value of a type ( short) whose range is smaller than that of the target type ( int). In such instances, C# allows the assignment to occur, and that's known as implicit conversion .

Converting a value from a smaller range to a bigger range is known as widening.

The following table shows the implicit conversion between the different built-in types supported by C#.

Convert from (type) To (type)
sbyte short, int, long, float, double, or decimal
byte short, ushort, int, uint, long, ulong, float, double, or decimal
short int, long, float, double, or decimal
ushort int, uint, long, ulong, float, double, or decimal
int long, float, double, or decimal
uint long, ulong, float, double, or decimal
long float, double, or decimal
char ushort, int, uint, long, ulong, float, double, or decimal
float double
ulong float, double, or decimal

If you try to assign the value of a type whose range is bigger than the target type, C# will raise an error. Consider the following example:

num = 5;

sNum = num; //---not allowed---

In this case, numis of type int and it may contain a big number (such as 40,000). When assigning it to a variable of type short, that could cause a loss of data. To allow the assignment to proceed, C# requires you to explicitly type-cast (convert) the value to the target type. This process is known as explicit conversion .

Converting a value from a bigger range to a smaller range is known as narrowing. Narrowing can result in a loss of data, so be careful when performing a narrowing operation.

The preceding statement could be made valid when you perform a type casting operation by prefixing the variable that you want to assign with the target type in parentheses:

num = 5;

sNum = (short) num; //---sNum is now 5---

When performing type casting, you are solely responsible for ensuring that the target variable can contain the value assigned and that no loss of data will happen. In the following example, the assignment will cause an overflow, changing the value of numto -25536, which is not the expected value:

By default, Visual Studio 2008 checks statements involving constant assignments for overflow during compile time. However, this checking is not enforced for statements whose values cannot be determined at runtime.

int num = 40000;

short sNum;

sNum =(short) num; //--- -25536; no exception is raised---

To ensure that an exception is thrown during runtime when an overflow occurs, you can use the checkedkeyword, which is used to explicitly enable overflow-checking for integral-type arithmetic operations and conversions:

try {

sNum = checked((short)num); //---overflow exception---

} catch (OverflowException ex) {

Console.WriteLine(ex.Message);

}

If you try to initialize a variable with a value exceeding its range, Visual Studio 2008 raises an error at compile time, as the following shows:

int num = 400000 * 400000;

//---overflows at compile time in checked mode

To turn off the automatic check mode, use the unchecked keyword, like this:

unchecked {

int num = 400000 * 400000;

}

The compiler will now ignore the error and proceed with the compilation.

Another way to perform conversion is to use the System.Convertclass to perform the conversion for you. The System.Convertclass converts the value of a variable from one type into another type. It can convert a value to one of the following types:

Boolean Int16 UInt32 Decimal

Char Int32 UInt64 DateTime

SByte Int64 Single String

Byte UInt16 Double

Using an earlier example, you can convert a value to Int16using the following statement:

sNum = Convert.ToInt16(num);

If a number is too big (or too small) to be converted to a particular type, an overflow exception is thrown, and you need to catch the exception:

int num = 40000;

short sNum;

try {

sNum = Convert.ToInt16(num); //---overflow exception---

} catch (OverflowException ex) {

Console.WriteLine(ex.Message);

}

When converting floating point numbers to integer values, you need to be aware of one subtle difference between type casting and using the Convertclass. When you perform a type casting on a floating point number, it truncates the fractional part, but the Convertclass performs numerical rounding for you, as the following example shows:

int num;

float price = 5.99F;

num = (int)price; //---num is 5---

num = Convert.ToInt16(price); //---num is 6---

When converting a string value type to a numerical type, you can use the Parse()method that is available to all built in numeric types (such as int, float, double, and so on). Here's how you can convert the value stored in the strvariable into an integer:

string str = "5";

int num = int.Parse(str);

Beware that using the Parse()method may trigger an exception, as demonstrated here:

string str = "5a";

int num = int.Parse(str); //---format exception---

This statement causes a format exception to be raised during runtime because the Parse()method cannot perform the conversion. A safer way would be to use the TryParse()method, which will try to perform the conversion. It returns a falseif the conversion fails, or else it returns the converted value in the outparameter:

int num;

string str = "5a";

if (int.TryParse(str, out num)) Console.WriteLine(num);

else Console.WriteLine("Cannot convert");

Flow Control

In C#, there are two ways to determine the selection of statements for execution:

if-elsestatement

switchstatement

if-else Statement

The most common flow-control statement is the if-elsestatement. It evaluates a Boolean expression and uses the result to determine the block of code to execute. Here's an example:

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

Интервал:

Закладка:

Сделать

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

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


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

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

x