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

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

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

838

Part X

APPENDIXES

 

 

 

address operator. The address operator is used to retrieve the address of the memory location referred by the pointer. In other words, the address operator converts the variable of the value type to a pointer. This operator is denoted by the ampersand (&) sign.

sizeof operator. The sizeof operator is used with the unmanaged-type

pointer to find out the size of the pointer. While allocating memory to

the pointer, you may need to know the size of the pointer. The return

 

 

 

Y

type of the sizeof operator is integer, and it can be used to find the

size of both default and user-defined unmanaged pointers.

 

 

F

stackalloc operator. The stackalloc operator is used to allocate mem-

 

 

M

 

ory from the call stack. The stackalloc operator has the following

syntax:

 

L

stackalloc

A

 

<data type>[expression]

 

 

E

 

Here, data type is the type of variable that you can store at the new

 

T

 

 

memory location, and expression specifies the number of memory locations to be allocated.

-> operator. he -> operator is used to access the struct members by using a pointer. You can use the -> operator as follows:

<expression> -> <identifier>

In the preceding syntax, the expression is any unmanaged-type expression, and identifier is the struct to which the pointer points.

[] operator. The [] operator is used to access an element of the pointer. The syntax of the [] operator is:

<data type>[] <identifier>

Here, the data type is the type of the pointer, and identifier specifies the name of the pointer whose elements are to be accessed.

Working with pointers also involves performing operations on pointers. The following section discusses the pointer arithmetic.

Pointer Arithmetic

Pointer arithmetic is very similar to the operations performed with variables. However, you cannot perform operations on a void type pointer. Similar to

Team-Fly®

UNSAFE CODE Appendix A 839

variables, you can use the increment (+) and the decrement (-) operators to add and subtract values from a pointer, respectively. For example, to add an integer value to a pointer, you use the following statement:

Pointer1 + 20;

Because the size of an integer is 4 bytes, the preceding statement adds 80 bytes to the pointer named Pointer1. However, to increment the value of a pointer by 1 byte, you can add a byte or an sbyte to a pointer.

Similarly, you can use the ++, --, and the comparison operators, such as <, >, ==, !=, <=, and >=, to perform operations on pointers.

In addition to performing operations on pointers, you can also type cast pointers.

Type Casting Pointers

As discussed earlier, you can type cast a pointer type to a variable type and vice versa. Pointers are used to store memory addresses, which are integer values. Therefore, it is possible to explicitly convert a pointer to an integer type. You need to convert a pointer to an integer type to display the pointer. The Console.WriteLine method does not take a pointer as a parameter. However, if you convert a pointer to an integer variable, you can pass it as a parameter to the Console.WriteLine method. To know more about pointer type casting, consider the following example:

int Integer = 20; int *Pointer1; Pointer1 = &Integer;

Console.WriteLine (“The value of Pointer1 is” + (int) Pointer1);

Here, a pointer named Pointer1 is declared and initialized with the address of an integer variable named Integer. To display the value of Pointer1, the pointer is type casted to an integer type by using the cast operator.

Because integer data type has a size of 4 bytes, you cannot use it in 64-bit systems. If you type cast a pointer to an integer value, it may result in an overflow condition. Therefore, it is advisable to type cast a pointer to a ulong type value.

840

Part X

APPENDIXES

 

 

 

TIP

You cannot use the checked keyword to track overflow conditions while working with pointers.

C# also allows you to type cast between different pointer types. Consider the following example:

int Integer = 20;

int *Pointer1;

Pointer1 = &Integer;

sbyte *Pointer2 = (sbyte*) Pointer1;

You can only explicitly convert between pointer types. C# does not allow an implicit pointer type conversion.

In this chapter, you learned about pointers and the use of pointers in your program code. After writing code that contains a pointer, you need to compile the code. Compilation of code containing pointers is slightly different from the compilation of an ordinary code.

Compiling Unsafe Code

As discussed earlier, you need to inform the compiler that the code to be executed is marked as unsafe. If you are compiling the program code from the command line, you can add the unsafe flag with the compile command, as shown:

csc /unsafe file1.cs

The preceding statement includes the unsafe flag with the csc command to inform the compiler that the file named file1.cs is marked as unsafe.

You can also compile the unsafe code by setting the Allow unsafe code blocks property to True in Visual Studio .NET. To do this, you can do the following steps:

1.Right-click on the project name in the Solution Explorer window.

2.Click on the Properties option in the drop-down list. The Property Pages page is displayed.

UNSAFE CODE Appendix A 841

3.In the right pane, select the Configuration Properties option.

4.Change the value of Allow unsafe code blocks property in the Build option to True.

The default value of this property is False.

5.Click on the OK button to close the Property Pages page.

Figure A-1 shows the Allow unsafe code blocks option.

FIGURE A-1 Allow unsafe code blocks option

Summary

In this chapter, you learned about pointers. A pointer is a variable similar to a reference and points to an address in memory. A pointer stores the actual memory address and makes it available to you. Pointers are extensively used in C and C++ for dynamic allocation of memory and to directly access the memory. Working with pointers requires extensive programming. Therefore, C# allows you to use pointers only within blocks of code for which the pointer is required. You can use the unsafe keyword to mark the block of code in which you need to declare a pointer.

Then you learned about the classification of code in C#. All program code in C# is classified as managed or unmanaged code. Managed code contains some information about the code.This information contained in the managed code is called

842

Part X

APPENDIXES

 

 

 

metadata.The code that is marked with the unsafe keyword is called unmanaged code. The unmanaged code does not contain metadata.

Next, you learned about the operators used with pointers.These operators include

the indirection operator, the address operator, the sizeof operator, the stack-

alloc operator, the -> operator, and the [] operator. Finally, you learned about the commands used to compile the code that uses pointers.

Appendix B

Introduction to Visual Basic .NET

844

Part X

APPENDIXES

 

 

 

In this appendix, you will learn about the languages of Visual Studio .NET. In addition, you will learn in detail about Visual Basic .NET as an object-oriented programming language. The appendix will also cover the different features of an object-oriented programming language. In addition, you will learn about the

components of Visual Basic. NET.

Based on your knowledge of Visual Basic .NET, you will learn to create a simple Visual Basic .NET Windows application and compare a Visual Basic .NET application with a Visual C# .NET application.

Introduction to the Languages of Visual Studio .NET

The latest version of Visual Studio is Visual Studio .NET, which is based on the

.NET Framework. The tools and languages provided by Visual Studio .NET enable you to build applications such as Web-based applications, desktop applications, and mobile applications. In addition, you can create Web services in Visual Studio .NET.

The following programming languages are included in Visual Studio .NET:

Visual C# .NET

Visual Basic .NET

Visual C++ .NET

Visual Studio .NET also supports technologies such as ASP.NET. These technologies enable you to develop and deploy various applications. Visual Studio

.NET also includes the MSDN Library, which contains complete documentation on various applications and development tools.

The IDE (Integrated Development Environment) of Visual Studio .NET helps you to create applications in various .NET languages. Visual Studio .NET allows the IDE to share tools and create applications in multiple languages.

Visual Studio .NET includes various advanced features compared to the earlier versions of Visual Studio. The following sections discuss the languages included in Visual Studio .NET.

COMMON LANGUAGE SPECIFICATION
A set of rules and constructs supported by the CLR is known as CLS. Visual Basic
.NET supports CLS. CLS also shares the objects, classes, or components created in Visual Basic .NET with any other language that supports CLS.
Regardless of the language used in creating the application, CLS ensures that there is interoperability between the different applications. You can derive a class that is based on a class written in Visual C# .NET while you work in Visual Basic
.NET, where the data types and variables of the class that is derived matches the base class.

INTRODUCTION TO VISUAL BASIC .NET Appendix B 845

Visual C# .NET

Visual C# .NET is a new language provided by Visual Studio .NET. Visual C#

.NET is an object-oriented language based on languages such as C and C++. You can create applications for the .NET Framework by using Visual C# .NET. Visual C# .NET supports CLR (common language runtime). Code written in Visual C#

.NET is managed code. Various templates,designers, and wizards,which help you create applications in Visual C# .NET, are provided by IDE. You have learned about Visual C# .NET throughout this book. The next sections will look at the other languages provided by Visual Studio .NET.

Visual Basic .NET

The latest version of Visual Basic, which is Visual Basic .NET, includes se veral new features. Unlike the earlier versions of Visual Basic, Visual Basic .NET supports inheritance. Version 4 and Version 6 of Visual Basic supported interfaces but not implementation inheritance. Visual Basic .NET supports both implementation inheritance and interfaces. Overloading is another new feature of Visual Basic .NET, which I will discuss later in this appendix.

Visual Basic .NET also supports multithreading, which allows you to create multithreaded and scalable applications. Visual Basic .NET can also be used with CLS (common language specification) and

supports structured exception handling.

Visual C++ .NET

The enhanced version of Visual C++ is Visual C++ .NET. Features such as support for managed extensions and attributes are included in Visual C++ .NET.

You can create applications for the .NET Framework by using a set of language extensions of C++ that are included in managed extensions. You can also convert the components that are already present in C++ into components that support the

.NET Framework by using managed

846

Part X

APPENDIXES

 

 

 

extensions.Therefore, using managed extensions, the existing code can be reused, saving both time and effort. You can also use managed extensions to merge both unmanaged and managed C++ code in an application.

Attributes that enable you to extend the functionality of a language and simplify the creation of COM components are supported by Visual C++ .NET. You can also apply classes, data members, or member functions to attributes.

Overview of Visual Basic .NET

The complete framework of Visual Basic .NET is based on the .NET Framework. Visual Basic .NET inherits the various features of the .NET Framework along with features of the earlier versions of Visual Basic. In this section, you will learn about the features of Visual Basic .NET as compared to the features in the earlier versions of Visual Basic.

As discussed earlier, Visual Basic .NET supports implementation inheritance as compared to the earlier versions of Visual Basic that supported interface inheritance. In other words, you can implement only interfaces with the earlier versions of Visual Basic. All the methods of the interface need to be implemented when you implement an interface in Visual Basic 6.0. In addition, the code has to be rewritten each time you implement the interface.

Visual Basic .NET, on the other hand, supports implementation inheritance.This implies that while applications are created in Visual Basic .NET, a class can also be derived from another class, which is known as the base class. The methods and properties of the base class are inherited by the derived class. In the derived class, you can either use or override the code that already exists in the base class.Therefore, code can be reused with the help of implementation inheritance. Although multiple interfaces can be implemented in a class in Visual Basic .NET, the class can inherit from only one class.

Visual Basic .NET also provides constructors and procedures, where constructors are used to initialize objects. The Sub New procedure replaces the Class_Initialize event in Visual Basic .NET. The Sub New procedure is executed when an object of the class is created, unlike the Class_Initialize event that is available in the earlier versions of Visual Basic.The first procedure to be executed in a class is the Sub New procedure. Instead of the Class_Terminate event, the Sub Finalize procedure is available in Visual Basic .NET. When an object is destroyed, the Sub

INTRODUCTION TO VISUAL BASIC .NET Appendix B 847

Finalize procedure is automatically called to complete the tasks that remain incomplete. In addition, the Sub Finalize procedure can only be called from the class to which it belongs or from the classes from which it is derived.

Visual Basic .NET has another additional feature known as garbage collection. Allocated resources such as objects and variables are monitored by the .NET Framework. In addition, the destroying objects, which are no longer in use, automatically release memory for reusing the objects in the .NET Framework. When an object is set to Nothing, in Visual Basic 6.0, it is destroyed automatically, whereas in Visual Basic .NET, it continues to occupy space even when it is set to Nothing. In Visual Basic .NET, the garbage collector checks the objects that are not currently used by the applications.The garbage collector releases the memory occupied by the object when any object is found marked for garbage collection.

The GC class, the Sub Finalize procedure, and the IDisposable interface are used to perform garbage selection operations in the .NET Framework. The System namespace contains the GC class that provides various methods that enable you to control the system garbage collector. In the .NET Framework, a member of the Object class, the Sub Finalize procedure, acts as a destructor. You can also override this procedure in your applications. However, the Sub Finalize procedure is not executed when the application is executed. The Sub Finalize procedure is called by the GC class to release the memory that is occupied by a destroyed object. However, an explicit way of managing resources in the form of the IDisposable interface is provided by the .NET Framework.The Dispose() method is included in the IDisposable interface. After the IDisposable interface is implemented, the Dispose() method can be overridden in the applications. You can release resources and database connections in the Dispose() method.

Overloading is a feature that enables you to define several procedures with the same name, where each procedure has a different set of arguments. Visual Basic

.NET supports this feature of overloading as compared to the earlier versions of Visual Basic. You can use overloading for constructors and properties in a class along with the procedures. The Overloads keyword is used for overloading procedures.

Consider a scenario in which a procedure needs to be created to display the address of an employee. The address of the employee should be viewed based on either the employee name or the employee code, which can be done by using the overload feature. You need to create two procedures with the same name but