Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Microsoft Visual C++ .NET Professional Projects - Premier Press

.pdf
Скачиваний:
180
Добавлен:
24.05.2014
Размер:
26 Мб
Скачать
☆

980

Part XII

APPENDIXES

 

 

 

In the preceding syntax, modifiers refers to the access modifiers that are used to define the accessibility level of a variable. C# supports five types of access modi-

fiers: public, protected internal, protected, internal, and private.

In C#, before referring to a variable, you need to initialize it. You can assign a value to a variable by using the assignment operator (=):

public int x = 10;

You can assign a well-defined initial value to a variable. Such a variable is called an initially assigned variable. C# also supports an initially unassigned variable that

does not have a well-defined initial value assigned to it. However, you need to

 

Y

assign a well-defined value to an initially unassigned variable before using it.

 

L

Variable Modifiers

F

 

Variable modifiers are used to define the features of a variable. Variable modifiers

 

M

specify the accessibility levels of a variable. For example, a variable modifier

A

decides whether a variable can be used or modified outside the class in which it is

declared. The variableEmodifiers that are supported by C# are listed in Table E-2.

T

 

Table E-2 Variable Modifiers

Variable Modifier

Description

internal

An internal variable is accessed from the current program in which it is

 

declared.

private

A private variable is accessed from the type that contains it.

protected

A protected variable is accessed from the containing class or the types

 

derived from the containing class.

public

A public variable can be accessed from anywhere.

read-only

A read-only variable is assigned a value when the variable is declared ini-

 

tially. If you do not assign a value to a read-only variable when it is first

 

declared, the variable takes the default value of that type. As the name

 

indicates, you cannot change the value of a read-only variable.

static

A static variable is accessed directly from the class and not from the

 

instance of the class.

 

 

Team-Fly®

BASICS OF C# Appendix E 981

Variable Data Types

The data type of a variable defines the type of the variable. Figure E-1 displays the data types in C#.

Data Type

 

Description of the Data Type

 

 

 

 

int

 

An int data type is used to store 32-bit signed integer values.

 

 

 

long

 

A long data type is used to store 64-bit signed integer values.

 

 

 

short

 

A short data type is used to store 16-bit signed integer values.

 

 

 

sbyte

 

A sbyte data type is used to store 8-bit signed integer values.

 

 

 

byte

 

A byte data type is used to store 8-bit unsigned integer values.

 

 

 

ushort

 

An ushort data type is used to store 16-bit unsigned integer values.

 

 

 

uint

 

An uint data type is used to store 32-bit unsigned integer values.

 

 

 

ulong

 

An ulong data type is used to store 64-bit unsigned integer values.

 

 

 

float

 

A float data type is used to store floating point values of

 

 

single precision.

 

 

 

double

 

A double data type is used to store floating poin values of

 

 

double precision.

 

 

 

decimal

 

A decimal data type is used to store 28 digit decimal numbers.

 

 

 

char

 

A char data type is used to store a Unicode character value.

 

 

 

string

 

A string data type is used to store an array of Uniciode characters.

 

 

 

object

 

The object data type is the base type of every type.

 

 

 

bool

 

A bool data type is used to store boolean values, true or false.

 

 

 

FIGURE E-1 Variable data types

Types of Variables

There are seven types of variables in C#:

static. A static variable has a static modifier. You can access a static variable directly from the class to which it belongs. You do not need to create an instance of a class to access a static variable. A static variable

982

Part XII

APPENDIXES

 

 

 

becomes active when the program in which it is declared is loaded, and becomes inactive when the program terminates.

instance. An instance variable is declared without the static modifier.

array elements. An array element stores the starting address of an array in memory. To access an array element, you need to create an instance of the array.

value parameters. A value parameter is a variable declared without a ref or out modifier. When you call a method that contains the value parameter, the parameter becomes active. It takes the value of the argument that you specify in the method. When the method is returned, the value parameter becomes inactive.

reference parameters. A reference parameter has a ref modifier. A reference parameter is initialized with the value of the underlying variable. A reference parameter stores the location of the argument that is specified when the method is declared.

output parameters. An output parameter is a variable declared with the out modifier. The out modifier allows you to pass a variable, which is not initialized, to a method. The variable then takes the value from the method to which it is passed.

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 within which you can access a variable. Table E-3 lists the scopes supported in C#.

Table E-3

Variable Scopes

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.

 

 

 

BASICS OF C# Appendix E 983

As discussed earlier, C# supports several data types. 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 type cast only to another value type. Similarly, a reference type can be type 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 data type to a long data type without any loss of data:

int x = 100;

long y;

y = x;

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

Data Type

Permissible Implicit Data Type Conversion

 

 

int

decimal, long, double, and float

 

 

long

decimal, double, and float

 

 

short

int, long, decimal, double, and float

 

 

sbyte

short, int, long, decimal, double, and float

 

 

byte

int, uint, long, ulong, short, ushort, decimal, double, and float

 

 

ushort

int, uint, long, ulong, decimal, double, and float

 

 

uint

long, ulong, decimal, double, and float

 

 

ulong

decimal, double, and float

 

 

float

double

 

 

char

int, uint, long, ulong, ushort, decimal, double, and float

 

 

FIGURE E-2 Implicit data type conversions

984

Part XII

APPENDIXES

 

 

 

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 E-3 shows explicit data type conversions.

Data Type

Explicit Data Type Conversion

 

 

int

uint, byte, sbyte, short, ushort, char, and ulong

 

 

long

int, unt, byte, sbyte, short, ushort, char, and ulong

 

 

short

uint, ushort, byte, sbyte, char, and ulong

 

 

sbyte

byte, uint, ulong, char, and ushort

 

 

byte

char, and sbyte

 

 

ushort

short, byte, sbyte, int, uint, short, ushort, long, and char

 

 

uint

int, short, ushort, byte, sbyte, and char

 

 

ulong

byte, sbyte, int, uint, short, ushort, long, and char

 

 

float

int, uint, long, ulong, char, decimal, short, ushort, byte, and sbyte

 

 

double

int, uint, short, ushort, byte, sbyte, long, ulong, char, float, and double

 

 

decimal

byte, sbyte, int, uint, short, ushort, long, ulong, char, float, and double

 

 

char

short, byte, and sbyte

 

 

FIGURE E-3 Explicit data type conversions

BASICS OF C# Appendix E 985

In addition to the data type conversion statements, C# provides you with boxing and unboxing data conversion techniques. You can use boxing to convert a value type to an object type. Boxing can be of the type implicit or explicit data conversion.

When you try to convert a value type to an object type, C# creates an instance of the object type. The value stored in the data type is then written to the instance of the object that is created.

Conversely, unboxing converts an object type to a value type. Unboxing is an explicit data type conversion technique. To convert an object type to a value type by using unboxing, you first need to create a value type by using boxing. The concept of boxing and unboxing is explained in detail in Chapter 4.

As you have seen earlier, C# uses variables to store values. To store multiple variables as a single data structure, you can use an array.

Arrays

An array is a data structure that acts as a pointer to an address in memory. However, unlike C++, an array in C# is an object, and therefore, has methods and properties associated with it.

To use an array in a program code, you need to declare and initialize it. In C#, you initialize an array by using the new keyword. To initialize an integer array with 20 elements, you use the following statement:

int [] Integer = new int [20];

C# allows you to specify the size of an array dynamically. Therefore, you can declare an array and initialize it at run time. When you declare an array without initializing it, C# creates a null reference to the array. You can then specify the amount of memory required by using the new keyword. C# allocates the required memory to the array at run time. For example, you can declare an array Integer and then specify the size of the array as 20 by using the new keyword:

int [] Integer;

Integer = new int [20];

To assign a value 100 to the last element of the array Integer, use the following statement:

Integer [19] = 100;

986

Part XII

APPENDIXES

 

 

 

Similar to integers, you can also use arrays to store character values. An array of character values is called a string. The next section details the use of strings.

String

C# provides you with a String type. In C and C++, an array of characters is called a string. String is not a class in C and C++. Therefore, working with strings is a problem in C and C++. Simple operations, such as comparing or adding two strings, require a lot of programming. To provide the programmers with a solution to this problem, C# created a String class.

You can initialize a string by using the String keyword. To initialize a string, string1, use the following statement:

String string1 = “Hello World”;

The preceding sample code declares a String, string1, and initializes it with a value, “Hello World”.

The assignment of a value to a string takes place by the reference type. When you declare a string, an object of the String class is created and placed on the heap. This object of the String class has the reference to the memory location where the string is stored.

Working with Strings

The String class in C# is in the System namespace. String is a class and has several methods associated with it. You can use these methods to perform operations on strings. The following are the commonly used methods in the String class:

Compare. The Compare method is used to compare two strings.

Format. You can use the Format method to format the values in a string. The Format method allows you to specify formatting for each value in a string.

Trim. The Trim method in C# deletes the extra spaces in a string. The Trim method can be used to delete both the leading and trailing spaces.

ToUpper. To change the capitalization of the elements in a string, you can use the ToLower or ToUpper method. The ToLower method converts the elements of the string to lowercase. Similarly, you can convert the string to uppercase by using the ToUpper method.

BASICS OF C# Appendix E 987

Split. Working with large strings can be a problem. Therefore, the System.String class provides the Split method that can be used to break a string into several small strings. You can specify a character from where the string should be split. The Split method breaks the string into substrings at each instance of the given character. The substrings created by the Split method are stored in the form of an array.

IndexOf. The IndexOf method is used to locate a character or substring in the main string. The IndexOf method returns the index of the first instance of the specified character in a string. Similarly, to locate the last occurrence of a character or substring, you can use the LastIndexOf method.

IndexOfAny. If you need to know the index of the first occurrence of any one of a set of characters in a string, you can use the IndexOfAny method. Similarly, the LastIndexOfAny method is used to locate the index of the last occurrence of any one of a set of characters in a string.

Replace. To replace all occurrences of a character or a substring in a string by another character or substring, you use the Replace method.

Simple operations on a string, such as adding or concatenating two strings, can be performed using a + operator. You do not require a method for concatenating two strings. For example, to add string1 and string2, you first need to initialize the two strings. You can then use the + operator to add the two strings and initialize its value to another string, string3. The following is a sample code snippet:

string string1 = “John ”;

string string2 = “Floyd”;

string string3 = string1 + string2;

In the preceding example, the value of string 3 will be John Floyd.

You have learned about performing simple operations on a string. Next, I will discuss the various statements and expressions provided by C#. You can use these statements and expressions to perform specific operations on variables.

Statements and Expressions

Statements in C# are similar to those in C and C++. C# supports the following types of statements:

988Part XII APPENDIXES

Simple. Simple statements include all declaration and labeled statements. Simple statements also include statements that are used to call methods.

Selection. In cases where the program has to execute one block of statements out of all the available blocks of statements, selection statements are used. The selection statements are of two types, if and switch statements.

Iteration. The iteration statements are used to execute a set of statements repeatedly until a condition is met. The types of iteration statements are for, foreach, while, and do-while statements.

Jump. The jump statements are used to pass the control of the execution unconditionally to another line in the program. The line of code to which the control is transferred is called the target of the jump state-

ment. The commonly used jump statements in C# are goto, return, break, and continue statements.

Proceeding further, I will discuss the types of statements that I cited in each of these categories. I discuss only those types that have a different syntax from C++.

Method Call Statements

A method call statement is also a type of a simple statement. A method call statement is used to call a method that is already created. The following code sample is an example of a method call statement:

String x;

x = “This is a sample Message Box.”;

MessageBox.Show(x);

The preceding code calls the Show method of the class MessageBox.

switch-statement

Switch statements are used the same way as in C++. However, in C and C++, a fall-through condition can occur. In a fall-through condition, if you omit any of the break statements, the program executes two cases. Whereas in C#, a fall-through situation is omitted because the compiler throws an error for each case that does not end with a break statement. The following code in C# generates an error:

int x;

switch (x)

BASICS OF C# Appendix E 989

{

case 1:

MessageBox.Show(“x is a positive number.”);

break;

case 2:

MessageBox.Show(“x is a negative number.”);

default:

MessageBox.Show(“x is equal to 0.”);

break;

}

If you need to execute two cases, you need to provide an explicit goto statement. The syntax for such code is given here:

switch (expression)

{

case 1 : statement goto case2;

case 2 : statement

goto default; [default:

statement jump-statement]

}

In this case, the compiler first executes case1, then case2, and then the default case.

In addition to the selection statements, types of statements also include iteration statements.

foreach Statement

The foreach statement is new in C#. The foreach statement iterates the statements in the foreach loop for each element in an array or collection. The following example will help you to understand the foreach loop:

int [] Integer = {15,89,1000,6};

foreach (int x in Integer)