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

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

Интервал:

Закладка:

Сделать

To get the size of a type, use the sizeof()method:

Console.WriteLine("{0} bytes", sizeof(int)); //---4 bytes---

In C#, all noninteger numbers are always treated as a double. And so if you want to assign a noninteger number like 3.99 to a floatvariable, you need to append it with the F(or f) suffix, like this:

float price = 3.99F;

If you don't do this, the compiler will issue an error message: "Literal of type double cannot be implicitly converted to type 'float'; use an 'F' suffix to create a literal of this type."

Likewise, to assign a noninteger number to a decimal variable, you need to use the M suffix:

decimal d = 4.56M; //---suffix M to convert to decimal---

float f = 1.23F; //---suffix F to convert to float---

You can also assign integer values using hexadecimal representation. Simply prefix the hexadecimal number with 0x, like this:

int num1 = 0xA;

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

Nullable Type

All value types in C# have a default value when they are declared. For example, the following declaration declares a Boolean and an intvariable:

Boolean married; //---default value is false---

int age; //--- default value is 0---

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

object x; x = default(int);

Console.WriteLine(x); //---0---

x = default(bool);

Console.WriteLine(x); //---false---

However, C# forbids you from using a variable if you do not explicitly initialize it. The following statements, for instance, cause the compiler to complain:

Boolean married;

//---error: Use of unassigned local variable 'married'---

Console.WriteLine(married);

To use the variable, you first need to initialize it with a value:

Boolean married = false;

Console.WriteLine(married); //---now OK---

Now marriedhas a default value of false. There are times, though, when you do not know the marital status of a person, and the variable should be neither truenor false. In C#, you can declare value types to be nullable, meaning that they do not yet have a value.

To make the marriedvariable nullable, the above declaration can be rewritten in two different ways (all are equivalent):

Boolean? married = null;

//---or---

Nullable married = null;

The syntax T?(example, Boolean?) is shorthand for Nullable(example, Nullable), where T is a type.

You read this statement as "Nullable of Boolean." The <> represents a generic type and will be discussed in more detail in Chapter 9.

In this case, married can take one of the three values: true, false, or null.

The following code snippet prints out "Not Married":

Boolean? married = null;

if (married == true)

Console.WriteLine("Married");

else

Console.WriteLine("Not Married"); //---this will be printed---

That's because the ifstatement evaluates to false(married is currently null), so the elseblock executes. A much better way to check would be to use the following snippet:

if (married == true)

Console.WriteLine("Married");

else if (married==false)

Console.WriteLine("Not Married");

else

Console.WriteLine("Not Sure"); //---this will be printed---

Once a nullable type variable is set to a value, you can set it back to nothing by using null, as the following example shows:

married = true; //---set it to True---

married = null; //---reset it back to nothing---

To check the value of a nullable variable, use the HasValueproperty, like this:

if (married.HasValue) {

//---this line will be executed only

// if married is either true or false---

Console.WriteLine(married.Value);

}

You can also use the == operator to test against null, like the following:

if (married == null) {

//---causes a runtime error---

Console.WriteLine(married.Value);

}

But this results in an error because attempting to print out the value of a null variable using the Valueproperty causes an exception to be thrown. Hence, always use the HasValueproperty to check a nullable variable before attempting to print its value.

When dealing with nullable types, you may want to assign a nullable variable to another variable, like this:

int? num1 = null;

int num2 = num1;

In this case, the compiler will complain because num1is a nullable type while num2is not (by default, num2cannot take on a null value unless it is declared nullable). To resolve this, you can use the null coalescing operator ( ??). Consider the following example:

int? num1 = null;

int num2 = num1 ?? 0;

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

In this statement, if num1is null, 0 will be assigned to num2. If num1is not null, the value of num1will be assigned to num2, as evident in the following few statements:

num1 = 5;

num2 = num1 ?? 0;

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

Reference Types

For reference types, the variable stores a reference to the data rather than the actual data. Consider the following:

Button btn1, btn2;

btn1 = new Button();

btn1.Text = "OK";

btn2 = btn1;

Console.WriteLine("{0} {1}", btn1.Text, btn2.Text);

btn2.Text = "Cancel";

Console.WriteLine("{0} {1}", btn1.Text, btn2.Text);

Here, you first declare two Button controls — btn1and btn2. btn1's Textproperty is set to " OK" and then btn2is assigned btn1. The first output will be:

OK OK

When you change btn2's Text property to " Cancel", you invariably change btn1's Textproperty, as the second output shows:

Cancel Cancel

That's because btn1and btn2are both pointing to the same Button object. They both contain a reference to that object instead of storing the value of the object. The declaration statement ( Button btn1, btn2;) simply creates two variables that contain references to Buttonobjects (in the example these two variables point to the same object).

To remove the reference to an object in a reference type, simply use the nullkeyword:

btn2 = null;

When a reference type is set to null, attempting to access its members results in a runtime error.

Value Types versus Reference Types

For any discussion about value types and reference types, it is important to understand how the .NET Framework manages the data in memory.

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

Интервал:

Закладка:

Сделать

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

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


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

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

x