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

C# ПІДРУЧНИКИ / c# / Premier Press - C# Professional Projects

.pdf
Скачиваний:
475
Добавлен:
12.02.2016
Размер:
14.7 Mб
Скачать

18

Part I

INTRODUCTION TO C#

 

 

 

n this chapter, you will learn about the basics of C#. This chapter will discuss

Ivariables and data type casting. You will also learn about arrays and strings

used in C#. Finally, you will be introduced to the statements and expressions used

in C#.

 

 

 

Y

 

 

 

L

 

 

F

Introduction to C#

 

 

 

 

M

 

C# is an advanced version of C and C++ and is designed specially for the .NET

environment. C#, pronounced C sharp, is a new object-oriented language used by

E

 

 

programmers worldwide to develop applications that run on the .NET platform.

T

 

 

 

However, C# is not a part of the .NET environment. C# is a part of Microsoft

Visual Studio .NET 7.0.

Ahe other languages included in the Visual Studio pack-

age are Visual C++ and Visual Basic. Visual Studio 7.0 also includes scripting languages, such as VBScript and JScript. You can use all these languages to create applications that run in the .NET environment. C# is a significant step in the evolution of programming languages, and C# is an ideal solution for high-level business applications. Using C#, you can create a wide range of projects that can be used to build a complete client/server application.

C# builds on the features of C, C++, Visual Basic (VB), and Java to provide a complete environment for developing applications.C# merges the power of C, the object-oriented features of C++, and the graphical interface of VB. In addition, the programs in both C# and Java compile to a byte code.

Now look at the basic components of a C# application.

Variables

Variables are storage locations for values in C#. A variable has a variable name and a data type associated with it. The data type represents the type of values that can

Team-Fly®

C# BASICS

Chapter 2

19

 

 

 

be stored in the variable. Variables can store characters, character strings, numeric values, or memory addresses.

Initializing Variables

To use a variable, you first need to declare it. In C#, you can declare a variable by using the following syntax:

<modifiers> <data type> <variable1, variable2,..........>;

Here, modifiers are the access modifiers that are used to define the accessibility level of a variable. C# supports five types of access modifiers: public, protected internal, protected, internal, and private. Data type is the type of the variable.

To use a variable in an application, you need to assign a value to it. You can assign a value to a variable by using the assignment operator (=). To assign a value 10 to the integer variable x, you use the following statement:

public int x = 10;

In C#, you cannot use a variable without initializing it. You can assign a welldefined 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 assign a welldefined value to an initially unassigned variable before using it.

Variable Modifiers

Variable modifiers are used to define the features of a variable. Variable modifiers specify the accessibility levels of a variable. For example, a variable modifier decides whether a variable can be used or modified outside the class in which it is declared. The variable modifiers that are supported by C# are listed in Table 2-1.

20

Part I

 

INTRODUCTION TO C#

 

 

 

 

 

 

Table 2-1 The Variable Modifiers in C#

 

 

 

 

 

 

 

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 fr om anywhere.

 

 

read-only

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

 

 

 

 

initially. 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 fr om the class and not from the

 

 

 

 

instance of the class.

 

 

 

 

 

You can specify the variable modifier while declaring a variable.

Variable Data Types

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

Types of Variables

There are seven types of variables in C#. These are as follows:

Static variables. 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 becomes active when the program in which it is declared is loaded and becomes inactive when the program terminates.

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

C# BASICS

Chapter 2

21

 

 

 

FIGURE 2-1 Variable data types

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.

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.

FIGURE 2-3 Explicit data type conversion

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, “More about Components.”

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. An array stores a number of variables and has an index attached to it.The index of an

C# BASICS

Chapter 2

 

25

 

 

 

 

 

array is used to access the elements of the array. The elements of an array are the variables that are stored in the array. An array can store only the elements of the same data type. For example, an integer array can store only the variables of the integer type. Unlike C++, an array in C# is an object and, therefore, has methods and properties associated with it.

To access the elements in an array, you use indices. An array can have a single index or multiple indices attached to it. The number of indices on each element of an array defines the rank of the array. For example, if an array has one index attached to its elements, the rank of the array is one. Such an array is called a single-dimensional array. Similarly, if an array has more than one index, it is called a multidimensional array. You will learn more about multidimensional arrays in Chapter 4, in the section “Multidimensional Arrays.”

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];

When the array is initialized with the value 20, you can access any elements of the array. The elements of an array are accessed by their indices.The index of an array in C# starts from zero. Therefore, the first element of an array has an index zero. To assign a value 100 to the last element of the array Integer, use the following statement:

Integer [19] = 100;

Similar to integers, you can use arrays to store character values. An array of character values is called a string. Strings will now be discussed in detail.

26

Part I

INTRODUCTION TO C#

 

 

 

Strings

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.

Initializing Strings

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

string string1 = “Hello World”;

The previous 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 commonly used methods in the String class are as follows:

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() methods. The ToLower() method

C# BASICS

Chapter 2

 

27

 

 

 

 

 

converts the elements of the string to lowercase. Similarly, you can convert the string to uppercase by using the ToUpper() method.

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 their value to another string, string3. The code sample that follows displays this.

string string1 = ‘John ‘; string string2 = ‘Floyd’;

string string3 = string1 + string2;

The value of string3 in the previous sample is John Floyd.

You have learned about performing simple operations on a string. Now look at the various statements and expressions provided by C#. You can use these statements and expressions to perform specific operations on variables.