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

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

Интервал:

Закладка:

Сделать

Basically, the memory is divided into two parts — the stack and the heap. The stack is a data structure used to store value-type variables. When you create an int variable, the value is stored on the stack. In addition, any call you make to a function (method) is added to the top of the stack and removed when the function returns.

In contrast, the heap is used to store reference-type variables. When you create an instance of a class, the object is allocated on the heap and its address is returned and stored in a variable located on the stack.

Memory allocation and deallocation on the stack is much faster than on the heap, so if the size of the data to be stored is small, it's better to use a value- type variable than reference-type variable. Conversely, if the size of data is large, it is better to use a reference-type variable.

C# supports two predefined reference types — objectand string— which are described in the following table.

C# Type .NET Framework Type Descriptions
object System.Object Root type from which all types in the CTS (Common Type System) derive
string System.String Unicode character string

Chapter 4 explores the System.Objecttype, and Chapter 8 covers strings in more detail.

Enumerations

You can create your own set of named constants by using enumerations. In C#, you define an enumeration by using the enumkeyword. For example, say that you need a variable to store the day of a week (Monday, Tuesday, Wednesday, and so on):

static void Main(string[] args) {

int day = 1; //--- 1 to represent Monday---

//...

Console.ReadLine();

return;

}

In this case, rather than use a number to represent the day of a week, it would be better if the user could choose from a list of possible named values representing the days in a week. The following code example declares an enumeration called Daysthat comprises seven names (Sun, Mon, Tue, and so forth). Each name has a value assigned (Sun is 0, Mon is 1, and so on):

namespace HelloWorld {

public enum Days {

Sun = 0,

Mon = 1,

Tue = 2,

Wed = 3,

Thur = 4,

Fri = 5,

Sat = 6

}

class Program {

static void Main(string[] args) {

Days day = Days.Mon;

Console.WriteLine(day); //---Mon---

Console.WriteLine((int) day); //---1---

Console.ReadLine();

return;

}

}

}

Instead of representing the day of a week using an int variable, you can create a variable of type Days. Visual Studio 2008's IntelliSense automatically displays the list of allowed values in the Daysenumeration (see Figure 3-9).

Figure 39 By default the first value in an enumerated type is zero However - фото 90

Figure 3-9

By default, the first value in an enumerated type is zero. However, you can specify a different initial value, such as:

public enum Ranking {

First = 100,

Second = 50,

Third = 25

}

To print out the value of an enumerated type, you can use the ToString()method to print out its name, or typecast the enumerated type to intto obtain its value:

Console.WriteLine(day); //---Mon---

Console.WriteLine(day.ToString()); //---Mon---

Console.WriteLine((int)day); //---1---

For assigning a value to an enumerated type, you can either use the name directly or typecast the value to the enumerated type:

Days day;

day = (Days)3; //---Wed---

day = Days.Wed; //---Wed---

Arrays

An array is a data structure containing several variables of the same type. For example, you might have an array of integer values, like this:

int[] nums;

In this case, numsis an array that has yet to contain any elements (of type int). To make nums an array containing 10 elements, you can instantiate it with the new keyword followed by the type name and then the size of the array:

nums = new int[10];

The index for each element in the array starts from 0and ends at n-1(where nis the size of the array). To assign a value to each element of the array, you can specify its index as follows:

nums[0] = 0;

nums[1] = 1;

//...

nums[9] = 9;

Arrays are reference types, but array elements can be of any type.

Instead of assigning values to each element in an array individually, you can combine them into one statement, like this:

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

Arrays can be single-dimensional (which is what you have seen so far), multi-dimensional, or jagged. You'll find more about arrays in Chapter 13, in the discussion of collections.

Implicit Typing

In the previous versions of C#, all variables must be explicitly typed-declared. For example, if you want to declare a string variable, you have to do the following:

string str = "Hello World";

In C# 3.0, this is not mandatory — you can use the new var keyword to implicitly declare a variable. Here's an example:

var str = "Hello world!";

Here, stris implicitly declared as a string variable. The type of the variable declared is based on the value that it is initialized with. This method of variable declaration is known as implicit typing. Implicitly typed variables must be initialized when they are declared. The following statement will not compile:

var str; //---missing initializer---

Also notice that IntelliSense will automatically know the type of the variable declared, as evident in Figure 3-10.

Figure 310 You can also use implicit typing on arrays For example the - фото 91

Figure 3-10

You can also use implicit typing on arrays. For example, the following statement declares pointsto be an array containing two Pointobjects:

var points = new[] { new Point(1, 2), new Point(3, 4) };

When using implicit typing on arrays, all the members in the array must be of the same type. The following won't compile since its members are of different types — string and Boolean:

//---No best type found for implicitly-typed array---

var arr = new[] { "hello", true, "world" };

Implicit typing is useful in cases where you do not know the exact type of data you are manipulating and want the compiler to determine it for you. Do not confuse the Objecttype with implicit typing.

Variables declared as Objecttypes need to be cast during runtime, and IntelliSense does not know their type at development time. On the other hand, implicitly typed variables are statically typed during design time, and IntelliSense is capable of providing detailed information about the type. In terms of performance, an implicitly typed variable is no different from a normal typed variable.

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

Интервал:

Закладка:

Сделать

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

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


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

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

x