ASP.NET Programming with C# and SQL Server First Edition

advertisement

ASP.NET Programming with C# and SQL Server

First Edition

Chapter 10

Developing Object-Oriented

C# Programs

Objectives

In this chapter, you will:

• Study object-oriented programming concepts

• Define custom classes

• Declare class fields

• Work with class methods

ASP.NET Programming with C# and SQL Server, First Edition 2

Introduction

• The programs written so far have been selfcontained

– Most of the code exists within a script section

• Object-oriented programming allows you to use and create self-contained sections of code that can be reused without having to copy them

ASP.NET Programming with C# and SQL Server, First Edition 3

Introduction to

Object-Oriented Programming

• Object-oriented programming ( OOP ): refers to the creation of reusable software objects

• Object : programming code and data that can be treated as an individual unit or component

• Code that comprises an object is organized into classes

• Objects may range from simple controls, such as a button, to entire programs

• Objects are often designed to perform specific tasks

ASP.NET Programming with C# and SQL Server, First Edition 4

Introduction to

ObjectOriented Programming (cont’d.)

• Popular object-oriented programming languages include C++, Java, and Visual Basic

• In many cases, objects written in one language can be used by programs written in another language

– You only need to know how to access the methods and properties of those objects to use them

ASP.NET Programming with C# and SQL Server, First Edition 5

Understanding Encapsulation

• Encapsulated objects: all code and required data are contained within the object itself

– Usually within a single file

• Interface : refers to the methods and properties that are required for a source program to communicate with an object

• Objects can be thought of as “black boxes”

– Users of the object can see only the methods and properties that you allow them to see

• Example: handheld calculator

– You do not need to know its inner workings to use it

ASP.NET Programming with C# and SQL Server, First Edition 6

Understanding Encapsulation (cont’d.)

Figure 10-1 Calculator interface

ASP.NET Programming with C# and SQL Server, First Edition 7

Using Objects in C# Programs

• Object-oriented techniques will help you build more extensible code that is easier to reuse, modify, and enhance

• Class : a template, or blueprint, that serves as the basis for creating new instances of objects from the class

• Instantiation : the creation of an object from a class

• A particular instance of an object inherits its methods and properties from the class from which it was created

ASP.NET Programming with C# and SQL Server, First Edition 8

Using Objects in C# Programs

(cont’d.)

• Syntax to instantiate an object from a class:

ClassName objectName = new ClassName();

• Class constructors are used to initialize properties when an object is first instantiated

– Many constructors accept arguments

• Use a period to access the methods and properties of an object

• Methods require a set of parentheses at the end of the method name, like functions

– Methods can accept arguments

ASP.NET Programming with C# and SQL Server, First Edition 9

Using Objects in C# Programs

(cont’d.)

• Sample application: Central Valley Bakery Web site

• Has four shopping categories: cakes, cookies, pies, and breads

• Goal: develop a reusable class named

ShoppingCart to handle the functionality of building and updating a shopping cart for a Web site

• ShoppingCart class requires four fields for product information: productID , name , description , and price

ASP.NET Programming with C# and SQL Server, First Edition 10

Figure 10-2 Central Valley Bakery home page

ASP.NET Programming with C# and SQL Server, First Edition 11

Figure 10-3 Cakes product page after adding Web server controls

ASP.NET Programming with C# and SQL Server, First Edition 12

Defining Custom C# Classes

• Data structure : a system for organizing data

• Field : a variable defined within a class

• Class members : the methods and fields defined in a class

• Data members (or member variables ): class variables

• Function members (or member functions ): the methods defined in a class

ASP.NET Programming with C# and SQL Server, First Edition 13

Defining Custom C# Classes (cont’d.)

• After an object has been instantiated:

– Class data members are called properties of the object

– Class function members are called methods of the object

• Classes are also called user-defined data types or programmer-defined data types

ASP.NET Programming with C# and SQL Server, First Edition 14

Defining Custom C# Classes (cont’d.)

• Why use classes?

– They help make complex programs easier to manage by logically grouping related methods and fields

– They can be used to hide information that users of the class do not need to access

– They provide an easy way to reuse code

– Instances of class objects inherit class members from the class on which they are based, allowing you to build new classes based on existing classes

ASP.NET Programming with C# and SQL Server, First Edition 15

Working with Access Modifiers

• Access modifiers : control a client’s access to classes, individual fields, methods and their members

• There are five access modifiers in C#:

– public

– private

– protected

– internal

– protected internal

• The default value is internal

ASP.NET Programming with C# and SQL Server, First Edition 16

Working with Access Modifiers

(cont’d.)

Table 10-1 C# access modifiers

ASP.NET Programming with C# and SQL Server, First Edition 17

Creating a Class Definition

• Class definition : contains the class members that make up the class

• Syntax: accessModifier class ClassName

{

//Class member definitions

}

• Class names should start with an uppercase letter

• partial keyword: indicates that a class definition can be split across multiple files

ASP.NET Programming with C# and SQL Server, First Edition 18

Collecting Garbage

• Garbage collection : the cleaning up, or reclaiming, of a member that is reserved by a program

• C# knows when a program no longer needs a variable or object and automatically cleans up the memory for that program

– Exception: open database connections must be closed by the program

ASP.NET Programming with C# and SQL Server, First Edition 19

Declaring Class Fields

• A class definition requires the declaration of class fields

• To design a class definition, you must understand the principle of information hiding

ASP.NET Programming with C# and SQL Server, First Edition 20

What Is Information Hiding?

• Information hiding : any class members that client programs do not need to know about should be hidden

• Information hiding gives an encapsulated object its

“black box” capabilities

– Users of the class see only the members of the class that you allow them to see

– Reduces the complexity of the code that clients see

– Prevents the accidental introduction of a bug into a program by other programmers

ASP.NET Programming with C# and SQL Server, First Edition 21

Using Access Modifiers with Fields

• Class fields are declared like standard variables, except that an access modifier is included at the beginning of the declaration

• It is good programming practice to assign an initial value to a field when it is declared

• To access a field as an object property, append the property name to the object with a period

ASP.NET Programming with C# and SQL Server, First Edition 22

Serializing Objects

• Serialization : the process of converting an object’s field into a string that can be stored for reuse

• .NET Framework supports two types of serialization:

– Binary serialization

– XML serialization

• Binary serialization : converts object properties to a binary format

– Very efficient

– Maintains the data types of the properties

– Readable only by the .NET Framework

ASP.NET Programming with C# and SQL Server, First Edition 23

Serializing Objects (cont’d.)

• XML serialization : converts object properties to

XML

– Does not maintain the data types of properties

– Good for sharing the data with other applications

• Must mark a class as serializable in order to serialize an object of that class

– Add the Serializable attribute immediately above the class definition, surrounded by brackets []

• Binary serialized objects are commonly stored in binary files on a local computer

ASP.NET Programming with C# and SQL Server, First Edition 24

Serializing Objects (cont’d.)

• File stream : used for accessing a resource, such as a file

• Input stream : reads data from a resource

• Output stream : writes data to a resource

– Response.Write() statements send data to an output stream (the Web browser window)

• You must include the System.IO

namespace before you can use the FileStream class

• Use the Serialize() method of the

BinaryFormatter class to serialize objects in binary format

ASP.NET Programming with C# and SQL Server, First Edition 25

Serializing Objects (cont’d.)

• Use the Deserialize() method of the

BinaryFormatter class to convert serialized data back into an object

• Add the NonSerialized attribute in brackets before the declaration of any field in the class that does not have to be serialized

• You can store a serialized object in session state

• To deserialize, you must cast the session variable to the class from which the serialized object was created

ASP.NET Programming with C# and SQL Server, First Edition 26

Working with Class Methods

• Methods perform most of the work in a class

• Methods are usually declared as public or private

– public methods can be called by anyone

– private methods can be called only by other methods in the same class

• Only methods that clients need to access should be declared as public

• Include an access modifier before the method’s return type

ASP.NET Programming with C# and SQL Server, First Edition 27

Initializing with Constructor Methods

• Constructor method : a special method that is called automatically when an object is instantiated from a class

– Its name is the same as the class name

– It is declared without a return type

– Must have the public access modifier

– Usually used to assign initial values to fields or to perform other initialization tasks

• A class may have one or more constructor methods

ASP.NET Programming with C# and SQL Server, First Edition 28

Cleaning Up with Destructor Methods

• Destructor method : called when the object is destroyed

– Cleans up any resources allocated to an object

• You cannot explicitly call a destructor method

– It is called automatically by the C# garbage collection

– Often used to close files or database connections

• Destructor name is the same as the class name, but preceded by a tilde symbol (~)

– No access modifier or return type is used

ASP.NET Programming with C# and SQL Server, First Edition 29

Writing Accessors

• Accessor methods : public methods that a client can call to retrieve or modify the value of a field

– Also called set or get methods

– Set methods modify field values and accept parameters to pass in the new value for the field

– Get methods retrieve field values

• C# allows you to create accessors using properties

• Properties : special methods that can be used as public data members to set and get field values

– Defined using the reserved words get and set

ASP.NET Programming with C# and SQL Server, First Edition 30

Figure 10-5 Shopping Cart page after adding several items

ASP.NET Programming with C# and SQL Server, First Edition 31

Summary

• An object is programming code and data that can be treated as an individual unit or component

• Objects are encapsulated; all code and data are contained within the object itself

• An interface refers to the methods and properties that are required for a source program to communicate with an object

• A class is a template, or blueprint, that serves as the basis for new objects

• When you create an object from a class, you are said to be instantiating the object

ASP.NET Programming with C# and SQL Server, First Edition 32

Summary (cont ’d.)

• An instance of an object inherits its methods and properties from the class on which it is based

• A data structure is a system for organizing data

• A field is a variable defined within a class

• Methods and fields defined in a class are called class members

• Classes help make complex programs easier to manage by logically grouping related methods and fields

• Access modifiers control a client’s access to classes, data members, and function members

ASP.NET Programming with C# and SQL Server, First Edition 33

Summary (cont ’d.)

• Garbage collection refers to cleaning up, or reclaiming, memory that is reserved by a program

• The principle of information hiding states that any class members that clients do not need to access or know about should be hidden

• Fields are declared like standard variables, except that you must include an access modifier

• Serialization is the process of converting an object’s fields into a string that can be stored for reuse

ASP.NET Programming with C# and SQL Server, First Edition 34

Summary (cont ’d.)

• A file stream is used for accessing a resource, such as a file, that you can read from and write to

• Public methods can be called by anyone, while private methods can be called only by other methods in the same class

• Only methods that clients need to access should be declared as public

• A constructor method is a special method that is called automatically when an object is instantiated from a class

ASP.NET Programming with C# and SQL Server, First Edition 35

Summary (cont ’d.)

• Any resources allocated to an object are cleaned up by a destructor method after the object is destroyed

• Accessor methods are public methods that a client can call to retrieve or modify the value of a field

• C# allows you to create accessors using properties, which are special methods that can be used as public data members to set and get field values

ASP.NET Programming with C# and SQL Server, First Edition 36

Download