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 — object
and 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.Object
type, and Chapter 8 covers strings in more detail.
You can create your own set of named constants by using enumerations. In C#, you define an enumeration by using the enum
keyword. 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 Days
that 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 Days
enumeration (see Figure 3-9).
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 int
to 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---
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, nums
is 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 0
and ends at n-1
(where n
is 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.
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, str
is 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 3-10
You can also use implicit typing on arrays. For example, the following statement declares points
to be an array containing two Point
objects:
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 Object
type with implicit typing.
Variables declared as Object
types 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.
Читать дальше