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

C# ПІДРУЧНИКИ / c# / Hungry Minds - ASP.NET Bible VB.NET & C#

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

End Class

Notice that the Inherits keyword is used to inherit the Trainee class from the Employee class.

Step 2: Specify the override

The next step would be to override the methods of the Employee class. Before doing this, you need to specify that the child classes can override the methods of the Employee class. The Overridable modifier helps you in doing so. To do this, open the Employee.vb page and edit the declaration of the DisplayDeduction function as shown here:

Public Overridable Function DisplayDeduction(ByVal strSal As

String) As Double

In this code snippet, the keyword Overridable indicates that the method can be overridden in derived classes.

Step 3: Override the methods of the base class

Now, you need to add code to the Trainee class so that it can override the methods of the base class. To do so, add the following code to the Trainee class (open the Trainee.vb page). This method is slightly different from the one used in the base class. It calculates deduction as 5 percent of the earnings.

Public Overrides Function DisplayDeduction(ByVal strSal As String) As Double

Dim intsal As Integer

intSal = CType(strSal, Integer)

Dim dblDedn As Double

dblDedn = intSal * 0.05

DisplayDeduction = dblDedn

End Function

End Class

Step 4: Use the child class methods in the form

After creating the child class, you need to use its methods in the form. To do so, switch to the EmployeeDetails.Aspx page and open its code window. Add the following code to the code window:

Public Sub CallMethod(ByVal EmpCat As Employee, ByVal salary As

String)

lblDedn.Text = EmpCat.DisplayDeduction(salary)

End Sub

The preceding code accepts an object of the Employee class and the salary of the employee as parameters. However, you can also pass an object of any class derived from the Employee class, such as Trainee, and the method then calls the DisplayDeduction method of the appropriate class. This is an example of polymorphism. Now, switch to the EmployeeDetails.Aspx page and double-click the Calculate Deduction button to open the code window containing the Click event of the button. Edit the existing code to read as follows:

If lstCategory.SelectedItem.Text = "Employee" Then

Dim emp As New Employee()

'Pass the object of the Employee class

CallMethod(emp, txtSalary.Text)

Else

Dim trn As New Trainee()

'Pass the object of Trainee class

CallMethod(trn, txtSalary.Text)

End If

This code uses a simple if...then...else statement. This code helps calculate the deduction on the salary on a different rate for an employee or a trainee. The code invokes the method CallMethod by passing either the Employee or the Trainee object along with the salary. CallMethod in turn calls the DisplayDeduction method of the appropriate class.

This way, we develop a simple application that accepts data from the user and performs certain calculations on it. After the user enters the information, the Show Details button displays the information entered by the user in the form. The Calculate Deduction button calculates the deduction based on the employee category selected from the Employee Category drop down list.

Summary

In this appendix, you learned the concept of object-oriented programming. You also learned the concepts of objects and classes, and the context in which they are used in Visual Basic. The concepts of encapsulation, polymorphism, and inheritance were also covered. Next, you learned to create and use classes. Finally, you learned how to create an object hierarchy by using inheritance.

Appendix D: C# Syntax

Overview

C#, pronounced "C sharp," is the latest offering from Microsoft. This programming language is set to revolutionize the concept of object-oriented programming (OOP), because, according to Microsoft, it offers the power of C and C++ along with the simplicity of Visual Basic. In other words, it is easy to write and understand like Visual Basic. However, it has the functionality of C++. For this reason, it is being touted in the programming world as "the biggest shake up in the programming environment since the advent of Windows." In addition to Visual Basic, Visual C++, and Visual FoxPro, Microsoft ships C# as a part of Microsoft Visual Studio 7.0.

Note Microsoft Visual Studio 7.0 also supports scripting languages, such as VBScript and JScript.

Although a little bit of C++ functionality has been compromised in C#, it offers various advantages. These include:

§Simplicity of coding.

§Consistency in treating everything from classes, structures, arrays, and data types as objects.

§Automatic garbage collection, as in Java.

Although the automatic garbage collection feature makes it easier to Note perform memory-related operations in coding, it can also cause

problems, such as stray pointers and unsafe casts.

§Type-safety, which doesn't allow a programmer to create invalid references and overwrite unallocated memory.

§Convenience of splitting source files and compiling these scattered files, irrespective of where they are stored.

§Exclusion of cumbersome header files.

All of these features make the C# programming language a force to be reckoned with. In this appendix, you will learn about the various data types and variables that are supported by C#. You'll learn about the looping structures, such as while, do, for, and foreach, that cause a program to run repeatedly to perform a specified task. You'll learn about decision structures that help an application to determine the action to be taken under different circumstances. These include the if...else and switch...case constructors. You'll also learn to handle unexpected events that can cause your program or your computer to behave abnormally. You'll learn to use the try, catch, and finally blocks for this purpose.

Writing C# Code in the ASP.NET Framework

You'll find writing the C# code in VS.NET an easy task. You won't need to remember the complete set of functions and classes because of the pop-up IntelliSense menu, from which you can choose the required classes, methods, or functions. The key words are depicted in blue so that you can read and understand the codes with ease. Moreover, you won't have to struggle with missing or extra braces that can cause big headaches.

In the ASP.NET Framework, you need to write the C# code in a C# project. The following are the steps to create a C# project in the ASP.NET Framework:

1.Select File New Project, to open the New Project dialog box.

Tip You can also press Ctrl + Shift + N to open the New Project dialog box.

2.Select Visual C# Projects from the Project Types list.

3.From the Templates pane, select Empty Project.

4.In the Name Box, specify the name of the project, say HW. In the Location box, specify the location, say C:\WorkArea, where you want to create your project. The completed dialog box is shown in Figure D-1.

Figure D-1: The completed New Project dialog box

Note The Name and Location boxes contain a default project name and the location, respectively. You can either accept the default values or edit these boxes to specify the name of the project and the location.

5.Click OK. A new project is created and indicated in the Solution Explorer window (see Figure D-2).

Figure D-2: The Solution Explorer window depicting the new project

Note You might have to wait for some time while ASP.NET creates the project.

6.Because the project you created is empty, you need to add a class to it. To do so, select Project Add Class. The Add New Item dialog box appears.

7.Under Categories, verify that Local Project Items is selected. From the Templates pane, select C# Class.

8.In the Name box, type "HelloWorld." Click Open to create the class HelloWorld.cs. Notice that some preliminary code already is written in the class.

9.Highlight the code as shown in Figure D-3 and delete it. You'll add your own code.

Figure D-3: Code that you need to delete to be able to add your code

10.Type as follows:

11.public static void Main()

12.{

13.Console.WriteLine("Hello World!!");

}

This code represents typical C# code. The code contains the following elements:

§using System: Represents that the namespace called System is being referenced, which contains the Console class used in the Main method. A namespace is used to

organize the elements of a class library in a hierarchical manner. The keyword using allows you to use the specified namespace and its members.

Note C# does not have its own class library in the ASP.NET Framework. It uses the same class library used by other languages, such as Visual Basic and Visual C++.

§class HelloWorld: Represents a user-defined class called HelloWorld.

§public static void Main: Represents the Main method. Like C++, the compiler searches for the Main method in the entire code (or project) and begins the program execution by executing the statements in it. The access specifier public represents that the Main method can be accessed from anywhere in this project. The keyword static represents that there can be just one copy of the method, which would be available to all

CrossReference

the members of the HelloWorld class. The keyword void means that the Main method does not return anything.

For more information on classes and access specifiers, refer to Appendix E, "C# Classes."

§Console.WriteLine("Hello World!!"): Represents the member class of the namespace System called Console, whose method called WriteLine is being used to display the message "Hello World!!" on the console.

14.The completed code should resemble the code shown in Figure D-4. Select File Save All to save the changes you've made to the project.

Figure D-4: The complete code of the HelloWorld.cs class

Tip

You can also press Ctrl + Shift + S to save the changes.

 

15.Select Build Build (or press Ctrl + Shift + B). If no errors were detected in the code, the result of the code would also be displayed. If errors are reported, you'll need to check the project for syntax errors.

16.If there were no build errors, run the application by pressing F5. The output of the application is displayed at the console.

Variables

A programming language uses variables to store results of calculations and data inputs from the users, functions (or methods), other programs, or subprograms. As opposed to the constants that never change their value, you can perform various operations, such as +, ++, -, --, and so forth, on the variables during an operation and change the values of the data stored by them.

Note Variables are also commonly referred to as fields in C#.

C# supports seven categories of variables:

§Static variables: When a variable is declared using the keyword static, the variable is known as the static variable. A static variable is initialized when the class in which the static variable is declared is loaded. The following is the syntax to declare static variables:

§access_specifier static datatype variable_name;

§public static char Reply;

In this statement:

o access specifier can be public, private, protected, internal, or protectedinternal.

odatatype can be int, char, string, float, decimal, double, and so on. For more information on data types, refer to the section "Data Types" in this chapter.

ovariable_name specifies the name of the variable.

§Instance variables: When a variable is declared without the keyword static, it is known as an instance variable. An instance variable is

instantiated (or comes into existence) when an object of the class to which

it belongs is created. Such variables cease to exist when the object is destroyed. The following is the syntax to declare instance variables:

§datatype variable_name;

§

int Sum;

§Array elements: When a variable is stored in an array, it is known as an array element. An array is a contiguous block of memory allocated to the variables that have similar data types. These elements are referred by the array index, which starts from zero. The array elements are instantiated when the array to which they belong comes into existence, and are destroyed when the array is removed from the memory. The following is the syntax to declare an array:

§datatype array_name[array_size];

§

§int Month[12] = {Jan, Feb, Mar, Apr, May, Jun, Jul, Aug,

Sept, Oct, Nov, Dec};

In this statement, 12 represents the size of the array called Month. This means the Months array can hold a maximum of 12 elements. Jan can be referred to as

Month[0], and Dec as Month[11].

§Value parameters: When a variable is declared without the keyword out or ref, it is called a value parameter. These variables are instantiated when the method to which they belong is invoked. After the method returns a value, the value parameters cease to exist. The following is the syntax for declaration of value parameters:

§datatype variable_name;

§

int Result;

§Reference parameters: When a variable is declared with the keyword ref, it is called a reference parameter. These variables are instantiated when the method to which they belong is invoked. After the method returns a value, the output parameters cease to exist. The following is the syntax for declaration of value parameters:

§ref datatype variable_name;

§

ref int DayNumber;

§Output parameters: When a variable is declared with the keyword out, it is called an output parameter. These variables are instantiated when the method to which they belong is invoked. After the method returns a value, they cease to exist. The following is the syntax for declaration of value parameters:

§out datatype variable_name;

§

out int DayNumber;

Note

The difference between reference and output parameters is that the

reference parameters must be assigned a value before they are passed

to a function. Conversely, the output parameters need not be assigned a value before they are passed as an output parameter to a function.

§Local variables: When a variable is declared within a for loop, a switch or using statement, or a similar block, it is called a local

variable. The local variables are instantiated and exist until the block, for loop, switch, or using statement holds the control.

Static variables, instance variables, and array elements are automatically initialized to their default values after they are instantiated. The default value of reference type variables is null. The value parameters are initialized by the default constructor, if any. These variable types are known as initially assigned variables. The output parameters and the local variables, on the other hand, belong to the category of initially unassigned variables.

Data Types

In a programming language, every variable is associated with a data type. A data type defines the type of values that can be stored in a variable. C# supports three categories of data types:

§Value type: Variables of this data type actually store the data. In other words, each variable contains its own copy of this data. As a result, operation on one variable does not affect the other variable, even if they happen to contain the same data value. Simple data types, such as char, int, and float, belong to this category. In addition, enum and struct data types also belong to this category.

§Reference type: Instead of storing the data directly, variables of this data type store the reference to it. As a result, two variables might point to the same data. If an operation is performed on one variable, it might also affect the other variable that is referencing the same data. The class, delegate, array, and interface data types belong to this category.

§Pointers: Variables of this data type store the memory address of other variables. However, this data type is used in unsafe codes only. In C#, the code using pointer operations is known as unsafe code. Programmers can write and perform pointer operations and convert pointer types to other data types.

Note

C# differs from its predecessors by virtue of the omission of pointer

operations in normal coding, apart from unsafe codes. Instead, most of

 

the pointer operations are managed by the garbage collector. The

 

garbage collector is a mechanism that periodically searches for unused

memory and references and frees the memory so that it can be used by other applications that require the memory urgently.

In C#, the value of any data type is treated as an object. As a result, every data type is derived from the Object class, which serves as the ultimate base class for all the data types. In the case of reference data types, the data being referenced also belongs to the Object type.

Value type

The value data type can be further subdivided into the two categories — struct type and enumeration type.

Struct type

Struct types can be used to declare constants, variables, methods, and properties. They can also be used to declare nested type variables and operators. The C# environment provides a set of predefined struct types known as simple types, which are listed in Table D-1.

Table D-1: Simple data types

Type

Object

Description

Serves as

Table D-1: Simple data types

Type

Description

the base type for the rest of the types

String

 

Represents

 

 

 

 

a set of

 

 

Unicode

 

 

characters

 

 

 

Int

 

Represents

 

 

 

 

32-bit

 

 

signed

 

 

integers

 

 

 

Char

 

Represents

 

 

 

 

a single

 

 

Unicode

 

 

character

 

 

 

Float

 

Represents

 

 

 

 

a single-

 

 

precision

 

 

floating-

 

 

point

 

 

decimal

 

 

value

 

 

 

Decimal

 

Represents

 

 

 

 

a decimal

 

 

number with

 

 

28

 

 

significant

 

 

digits; i.e.,

 

 

28 decimal

 

 

places

 

 

 

Double

 

Represents

 

 

 

 

a double-

 

 

precision

 

 

floating-

 

 

point value

 

 

 

Bool

 

Represents

 

 

 

 

the Boolean

 

 

data type,

 

 

whose value

 

 

can either

 

 

be True or

 

 

False

 

 

 

Long

 

Represents

 

 

 

 

the 64-bit

 

 

signed

 

 

integer

 

 

 

Ulong

 

Represents

 

 

 

 

the 64-bit

 

 

unsigned

 

 

integer

 

Table D-1: Simple data types

 

 

 

 

 

 

 

 

 

Type

 

Description

 

 

 

 

 

 

 

Short

 

Represents

 

 

 

 

 

 

 

 

the 16-bit

 

 

 

 

signed

 

 

 

 

integer

 

 

 

 

 

 

 

Ushort

 

Represents

 

 

 

 

 

 

 

 

the 16-bit

 

 

 

 

unsigned

 

 

 

 

integer

 

 

 

 

 

 

 

Uint

 

Represents

 

 

 

 

 

 

 

 

the 32-bit

 

 

 

 

unsigned

 

 

 

 

integer

 

 

 

 

 

 

 

Byte

 

Represents

 

 

 

 

 

 

 

 

the 8-bit

 

 

 

 

unsigned

 

 

 

 

integer

 

 

 

 

 

 

 

Sbyte

 

Represents

 

 

 

 

 

 

 

 

the 8-bit

 

 

 

 

signed

 

 

 

 

integer

 

 

 

 

 

 

The simple data types can be further divided into four subcategories — Boolean type, numeric type, floating-point type, and integral type.

Boolean type

The Boolean data type is represented by the bool type, which can take either of the two Boolean logical values — True or False. The Boolean data types cannot be converted to other data types, and vice versa.

Numeric type

The numeric type is represented by the decimal type, which is a 128-bit data type. This data type is used for financial calculations. The decimal type variables can hold values that range from 1.0 x 1028 to 7.9 x 1028. The decimal type operations are precise to the 28-29 significant digits.

Note In an operation, if a decimal value is too small after rounding off, it is treated as 0. On the other hand, if the value is too large for the decimal format, OverFlowException is thrown.

Floating-point type

float and double are the two types that belong to the floating-point type category. The

range of float type values is from 1.5 x 1045 to 3.4 x 1038. For example, 2.5675 is a valid float type value. The range of double type values is from 5.0 x 10324 to 1.7 x 10308. In the

operations involving floating-point data type variables, the following values are valid:

§Not a Number, which is generated by invalid floating-point operations such as dividing infinity by infinity or zero by zero.

§Positive and negative infinity, which are generated by dividing a nonzero number by zero. For example, -2/0 generates negative infinity,

and 2/0 generates positive infinity.

§Positive and negative zero.

§Finite set of non-zero values in the form of X x Y x 2e, where X = 1 or

–1 and Y and e are determined by the floating point.

Integral types

Nine integral types are supported by C#:

§ int: Represents signed 32-bit integer values that can range from – 2,147,483,648 to 2,147,483,648

§ uint: Represents unsigned 32-bit integer values that can range from 0 to 4,294,967,295

§ char: Represents unsigned 16-bit integer values that can range from 0 to 65,535

§byte: Represents unsigned 8-bit integer values that can range from 0 to 255

§sbyte: Represents signed 8-bit integer values that can range from - 128 to 127

§long: Represents signed 64-bit integer values that can range from - 9,223,372,036,854,775,808 to 9,223,372,036,854,775,808

§ulong: Represents unsigned 64-bit integer values that can range

from 0 to 18,446,744,073,709,551,615

§ short: Represents signed 16-bit integer values that can range from - 32,768 to 32,767

§ ushort: Represents unsigned 16-bit integer values that can range from 0 to 65,535

Enumeration types

The enumeration data types are represented by named constants. Every enumeration data type must have an underlying integral data type, such as short, ushort, int, uint, byte, sbyte, long, and ulong. char cannot be used as the underlying type of the enumeration type.

Reference data types

The reference data types do not store the data itself. Rather, they store the reference to the intended data. The following are the four reference data types:

§Class type: This reference data type represents a data structure. A data structure can contain data members, such as constants, methods, variables, fields, constructors, destructors, and events. As in C and C++, the class types support inheritance. Inheritance is the mechanism by

which a class derives its properties and functionality from a parent class, also known as a base class. In C#, two class types are used most frequently:

oObject type: This class serves as the base (or parent) type for the rest of the data types, because every data type is derived from this data type — directly or indirectly.

Note

Actually, the object keyword is just an alias for the

 

System.Object class. You can use object or

 

System.Object interchangeably.

oString type: Like all the other classes and types in C#, this class is directly inherited from the object (or System.Object) class. It represents a set of Unicode characters. The string keyword is merely an alias of the System.String class. You can use string or System.String interchangeably.

§Interface type: Interfaces are special classes that can be inherited by other classes that are not directly related to them. They contain member functions, but these member functions do not have bodies (in other words, these functions are empty). The class or struct that inherits from an interface must implement these functions without renaming them. However, the inheriting class or struct can implement these functions, as they like.

§Array type: An array is a contiguous memory allocation to variables of similar data type. The variables that are stored in an

Соседние файлы в папке c#