Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Microsoft C# Professional Projects - Premier Press.pdf
Скачиваний:
177
Добавлен:
24.05.2014
Размер:
14.65 Mб
Скачать

22Part I INTRODUCTION TO C#

Local variables. A local variable is declared within a method. A local variable is not initialized automatically and becomes active when the program that contains the local variable is executed. It becomes inactive when the execution of the immediate code, which contains the local variable, ceases.

Variable Scope

A scope of a variable defines the region of the code from where you can access a variable. To know more about the various scopes of a variable, refer to Table 2-2.

Table 2-2 Scopes of a Variable

Variable Scope

Description

Block

You can access the variable only within the code in which it is declared.

Procedure

You can access the variable only within the procedure for which it is

 

declared.

Namespace

You can access the variable from anywhere within the namespace.

 

 

C# supports several data types, as discussed. There may be instances where you need to convert one data type to another. To do this, C# provides you with data type casting statements.

Types of Data Type Casting

Data type casting in C# can be of two types:

Implicit conversion

Explicit conversion

C# allows you to initialize variables by using the value or reference type.However, a value type can be casted only to another value type. Similarly, a reference type can be casted only to another reference type. When a data type is converted to another data type without any loss of data, this technique is called implicit conversion.

For example, you can implicitly convert an integer type data type to a long data type without any loss of data.

C# BASICS

Chapter 2

23

 

 

 

int x = 100;

long y;

y = x;

Figure 2-2 shows the implicit data type conversions that are permissible.

FIGURE 2-2 Implicit data type conversion

To convert a long data type to an integer data type, you use the explicit data conversion statements. In addition to all implicit data conversion statements, explicit data conversion statements also include all numeric data type conversions that cannot be implicitly converted. C# provides you with the cast operator to perform explicit data conversion.

int x;

long y = 100;

x = (int) y;

The long data type y is converted to integer x explicitly. An explicit data conversion might lead to some loss of information or may even result in an exception being thrown.

Figure 2-3 shows explicit data type conversions.