Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# and the NET Platform, Second Edition - Andrew Troelsen.pdf
Скачиваний:
67
Добавлен:
24.05.2014
Размер:
22.43 Mб
Скачать

Summary C# and the .NET Platform, Second Edition

by Andrew Troelsen ISBN:1590590554

This (very, very lengthy) chapter has exposed you to the numerous core aspects of the C# programming

Apress © 2003 (1200 pages)

language. The focus was to examine the constructs that will be commonplace in any application you may

This comprehensive text starts with a brief overview of the

be interested in buildingC# language. First,andeverythenC#quicklyprogrammovesmusttohavekey technicala class definingand a static Main() method, which serves as the program'sarchitecturalentryissuespoint.forWithin.NETthed velscopersof. Main(), you typically create any number of objects, which work together to breathe life into your application.

TableAs youf Contentshave seen, all intrinsic C# data types alias a corresponding type in the System namespace. Each C#systemand thetype.NEThasPlatfornumber, Secondof membersEdition that provide a programmatic manner to obtain the range of the

type. Furthermore, you have learned the basic process of building C# class types, and examined the

Introduction

various parameter passing conventions, value types and reference types, and the role of the mighty

Part One - Introducing C# and the .NET Platform

System.Object.

Chapter 1 - The Philosophy of .NET

Chapter 2 - Building C# Applications

You also examined various aspects of the CLR that place an OO spin on common programming

Part Two - The C# Programming Language

constructs, such as arrays, strings, structures, and enumerations. This chapter also illustrated the concept

Chapter 3 - C# Language Fundamentals

of boxing and unboxing. This simple mechanism allows you to easily move between value-based and

Chapter 4 - Object-Oriented Programming with C#

reference-based data types. Finally, the chapter wrapped up by explaining how to build your own custom

Chapter 5 - Exceptions and Object Lifetime namespaces, and why you might want to do so.

Chapter 6 - Interfaces and Collections

ChapterSo at this7 point,- Callbackfeel freeInt rfaces,to takeDelegates,break andandrelaxEvents. When you are ready to pound out some further code,

turn to Chapter 4 and see how C# contends with the mighty pillars of OOP.

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

Chapter C#4:andObjectthe .NET -Platform,OrientedSecond EditionProgramming with C#

by Andrew Troelsen

ISBN:1590590554

Apress © 2003 (1200 pages)

 

Overview This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and

In the previous chapterarchite,cturalyou wereissuesintroducedf r .NET developersto a number. of core constructs of the C# language and the

.NET platform in general. Here, you will spend your time digging deeper into the details of object-based development. I begin by reviewing the famed "pillars of OOP" from a high level, and then examine exactly

TablehowofC#Contentscontends with the notions of encapsulation, inheritance, and polymorphism. This will equip you

C#withandthetheknowledge.NET Platform,you needS condin orderEditionto build custom class hierarchies using C#.

Introduction

During this process, you examine some new constructs such as establishing type (rather than member)

Part One - Introducing C# and the .NET Platform

level visibility, building type properties, versioning type members, and designing "sealed" classes. Do be

Chapter 1 - The Philosophy of .NET

aware that the information presented here will serve as the foundation for more advanced class design

Chapter 2 - Building C# Applications

techniques (such as over-loaded operators, events, and custom conversion routines) seen in later

Part Two - The C# Programming Language

chapters.

Chapter 3 - C# Language Fundamentals

Chapter 4 - Object-Oriented Programming with C#

By way of a friendly invitation, even if you are currently comfortable with the constructs of object-oriented

Chapter 5

- Exceptions

d Object Lifetime

programming, I would encourage you to pound out the code examples found within this chapter. As you

Chapter 6

- Int rfaces

Collections

will see, C# does placeandnew spin on many common OO techniques.

Chapter 7

- Callback Interfaces, Delegates, and Events

Chapter 8

- Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 12 - Object Serialization and the .NET Remoting Layer
Part Four - Leveraging the .NET Libraries

Formal DefinitionC# and theof.NETthePlatform,C# ClassSecond Edition

by Andrew Troelsen

ISBN:1590590554

If you have been "doing objects" in another programming language, you are no doubt aware of the role of

Apress © 2003 (1200 pages)

class definitions. Formally, a class is nothing more than a custom user defined type (UDT) that is composed

This comprehensive text starts with a brief overview of the

of data (sometimesC#termedlanguageattributesand then) andquicklyfunctionsmoves thatto keyactechnicalon this dataand (often called methods in OO speak). The power of objectarchitectural-based languagesiss es for is.NETthatdevelopersby grouping. data and functionality in a single UDT, you are able to model your software types after real-world entities.

TableFor example,of Contentsassume you are interested in modeling a generic employee. At minimum, you may wish to C#buildandatheclass.NETthatPlatform,maintainsSecondthe name,Editioncurrent pay, and employee ID for each worker. In addition, the

Employee class defines one method named GiveBonus(), which increases an individual's current pay by

Introduction

some amount, and another named DisplayStats(), which prints out the relevant statistics for this individual

Part One - Introducing C# and the .NET Platform

(Figure 4-1).

Chapter 1 - The Philosophy of .NET

Chapter 2 - Building C# Applications

Part

Chapter

Chapter

Chapter

Chapter

Chapter

Chapter

Part Three - Programming with .NET Assemblies

Figure 4-1: A simple class definition

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

As you recall from Chapter 3, C# classes can define any number of constructors. These special class

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

methods provide a simple way for an object user to create an instance of a given class with an initial look and feel. As you know, every C# class is endowed with a freebie default constructor. The role of the default constructor is to ensure that all state data is set to an initial safe value. In addition to the default constructor,

you are also free to define as many custom constructors as you feel are necessary. To get the ball rolling,

Chapter 14 - A Better Painting Framework (GDI+) here is our first crack at the Employee class:

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

// The initial Employee class definition.

Chapter 17 - Data Access with ADO.NET class Employee

Part Five - Web Applications and XML Web Services

{

Chapter 18 - ASP.NET Web Pages and Web Controls

// Private state data.

Chapter 19 - ASP.NET Web Applications private string fullName;

Chapter 20 - XML Web Services private int empID;

Index private float currPay;

List of Figures

// Constructors.

List of Tables

public Employee(){ }

public Employee(string fullName, int empID, float currPay)

{

this.fullName = fullName; this.empID = empID; this.currPay = currPay;

}

// Bump the pay for this employee.

public void GiveBonus(float amount)

{currPay += amount; }

// Show current state of this object.

public virtual void DisplayStats()

{

Console.WriteLine("Name: {0} ", fullName);

Console.WriteLine("Pay: {0} ", currPay);

Console.WriteLine("ID: {0} ", empID);

}

}

C# and the .NET Platform, Second Edition

 

// See note that follows!

ISBN:1590590554

 

 

by Andrew Troelsen

Apress © 2003 (1200 pages)

This comprehensive text starts with a brief overview of the

C# language and then quickly moves to key technical and

architectural issues for .NET developers.

Note Unlike C++, C# class definitions do not end with a terminating semicolon (however, if you do add such a token, your *.cs file will still compile).

Table of Contents

Notice the empty implementation of the default constructor for the Employee class:

C# and the .NET Platform, Second Edition

Introduction

class Employee

Part One - Introducing C# and the .NET Platform

{

Chapter 1 - The Philosophy of .NET

// Remember! All member variables assigned to default values automatically.

Chapter 2 - Building C# Applications

public Employee(){ }

Part Two - The C# Programming Language

...

Chapter 3 - C# Language Fundamentals

}

Chapter 4 - Object-Oriented Programming with C#

Chapter 5 - Exceptions and Object Lifetime

Like C++ and Java, if you choose to include custom constructors in a class definition, the default constructor

Chapter 6 - Interfaces and Collections

issilently removed. Therefore, if you wish to allow the object user to create an instance of your class as

Chapter 7 - Callback Interfaces, Delegates, and Events

follows:

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

// Calls the default constructor.

Chapter 9 - Understanding .NET Assemblies

Employee e = new Employee();

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

you must explicitly redefine the default constructor for your class. If you forget to do so, you will receive

Chapter 12 - Object Serialization and the .NET Remoting Layer

compile time errors. This point aside, triggering the logic behind a constructor is self-explanatory:

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

// Call some custom ctors (two approaches).

Chapter 15 - Programming with Windows Forms Controls public static void Main()

Chapter 16 - The System.IO Namespace

{

Chapter 17 - Data Access with ADO.NET

Employee e = new Employee("Joe", 80, 30000);

Part Five - Web Applications and XML Web Services

e.GiveBonus(200);

Chapter 18 - ASP.NET Web Pages and Web Controls

Employee e2;

Chapter 19 - ASP.NET Web Applications

e2 = new Employee("Beth", 81, 50000);

Chapter 20 - XML Web Services

e2.GiveBonus(1000);

Index e2.DisplayStats();

List} of Figures

List of Tables

SOURCE The complete Employees example that we examine over the course of this chapter is

CODE included under the Chapter 4 subdirectory.

Understanding Method Overloading

Like other object-oriented languages, C# allows a type to "overload" various members. Simply put, when a class has a set of identically named members that differ by the number (or type) of parameters, the member in question is said to be overloaded. In the Employee class, you have overloaded the class constructor, given that you have provided two definitions that differ only by the parameter set:

class Employee

{

public Employee(){ }

public Employee(string fullName, int empID, float currPay){...}

...

C# and the .NET Platform, Second Edition

 

by Andrew Troelsen

ISBN:1590590554

}

Apress © 2003 (1200 pages)

 

 

 

This comprehensive text starts with a brief overview of the

Constructors, however,C# languageare notandthethenonlyquicklymembersmovesthattomaykey technicalbe overloadedand for a type. Assume you have a

architectural issues for .NET developers.

class named Triangle that supports an overloaded Draw() method. By doing so, you allow the object user to render the image using various input parameters:

Table of Contents

class Triangle

C# and the .NET Platform, Second Edition

{

Introduction

// The overloaded Draw() method.

Part One - Introducing C# and the .NET Platform

public void Draw(int x, int y, int height, int width);

Chapter 1 - The Philosophy of .NET

public void Draw(float x, float y, float height, float width);

Chapter 2 - Building C# Applications

public void Draw(Point upperLeft, Point bottomRight);

Part Two - The C# Programming Language

public void Draw(Rect r);

Chapter 3 - C# Language Fundamentals

}

Chapter 4 - Object-Oriented Programming with C# Chapter 5 - Exceptions and Object Lifetime

ChapterIf C# did6 not- Interfacessupport methodand Collectionsoverloading, you would be forced to create four uniquely named members,

Chapterwhich as7 you- Callbackcan see,Interfis farces,fromDelegideal:tes, and Events

Chapter 8 - Advanced C# Type Construction Techniques

PartclassThreeTriangle- Programming with .NET Assemblies

Chapter{ 9 - Understanding .NET Assemblies

Chapter//10Yuck- Processes,... AppDomains, Contexts, and Threads

Chapterpublic11 - TypevoidReflection,DrawWithInts(intdLate Binding, Attributex, int-Basedy, intProgrammingheight, int width);

Part Fourpublic- Leveragingvoid theDrawWIthFloats(float.NET Libraries x, float y, float height, float width);

public void DrawWithPoints(Point upperLeft, Point bottomRight);

Chapter 12 - Object Serialization and the .NET Remoting Layer

public void DrawWithRect(Rect r);

Chapter 13 - Building a Better Window (Introducing Windows Forms)

}

Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Finally, be aware that when you are overloading a class member, the return type alone is not unique enough.

Chapter 17 - Data Access with ADO.NET

Thus, the following is illegal:

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

class Triangle

Chapter 19 - ASP.NET Web Applications

{

Chapter 20 - XML Web Services

...

Index // Error! Cannot overload methods

List of Figures

// based solely on return values!

List of Tables

public float GetX();

public int GetX();

}

Self-Reference in C#

Next, note that the custom constructor of the Employee class makes use of the C# "this" keyword:

// Like C++ and Java, C# also supplies a 'this' keyword.

public Employee(string fullName, int empID, float currPay)

{

// Assign the incoming params to my state data.

this.fullName = fullName;

this.empID = empID;

 

C# and the .NET Platform, Second Edition

 

 

this.currPay = currPay;

ISBN:1590590554

}

by Andrew Troelsen

Apress © 2003 (1200 pages)

 

 

 

This comprehensive text starts with a brief overview of the

This particular C#C#keywordlanguageis usedand thenwheneverquicklyyoumoveswishtotokeymaketechnicalreferencea d to the current object. Visual Basic

architectural issues for .NET developers.

programmers can equate the C# "this" keyword with the VB "Me" keyword. C++ and Java programmers should feel right at home, given that these languages have an identically named "this" keyword used for the

same purpose.

Table of Contents

C#Theandreasonthe .NETyouPlatform,make useSecondof "this"Editionin your custom constructor is to avoid clashes between the parameter

Inamestroductionand names of your internal state variables. Of course, another approach would be to change the

PartnamesOne for- Introducingeach parameterC# andandtheavoid.NET Platformthe name clash altogether (but I am sure you get the point).

Chapter 1

 

- The Philosophy of .NET

 

 

 

Note Be aware that static member functions of a type cannot use the "this" keyword within its method

Chapter 2

 

- Building C# Applications

 

 

 

 

 

scope. This fact should make perfect sense, as static member functions operate on the class (not

Part Two - The C# Programming Language

 

Chapter 3

 

object) level.

 

 

 

 

- C# Language Fundamentals

 

 

 

Chapter 4

 

- Object-Oriented Programming with C#

 

Forwarding Constructor Calls Using "this"

 

Chapter 5

 

- Exceptions and Object Lifetime

 

Chapter 6

 

- Interfaces and Coll ctions

 

 

 

Another use of the C# "this" keyword is to force one constructor to call another during the time of

Chapter 7

 

- Callback Interfaces,

 

and Ev nts

 

construction. As suggested in ChapterDelegates,3 this is yet another way to avoid redundant member initialization

 

 

 

 

 

logic. Consider the following example:

 

 

 

Chapter 8

 

- Advanced C# Type Construction Techniques

 

Part Three - Programming with .NET Assemblies

 

Chapter 9

 

- Understanding .NET Assemblies

 

class

Employee

 

 

 

Chapter 10

- Processes, AppDomains, Contexts, and Threads

 

{

 

 

 

 

 

 

Chapter 11

- Type Reflection, Late B nding, and Attribute-Based Programming

 

public Employee(string

fullName, int empID, float currPay)

Part Four - Leveraging the .NET Libraries

 

 

 

{

 

 

 

 

 

 

Chapter 12

- Object Seria ization and the .NET Remoting Layer

 

 

 

this.fullName = fullName;

 

Chapter 13

- Buildthisng.aempIDBetter Window= empID;(Introducing Windows Forms)

 

Chapter 14

- A thisBetter.PaintingcurrPayFramewo= currPay;k (GDI+)

 

Chapter }15

- Programming with Windows Forms Controls

 

Chapter //16

-IfThetheSystem.IOuser Namespacecalls this ctor, forward to the 3-arg version.

Chapter public17 - DataEmployee(stringAccess with ADO.NET

fullName)

0.0F) { }

Part Five - Web Applications: this(fullName,and XML WebIDGenerator.GetNewEmpID(),Services

...

Chapter 18 - ASP.NET Web Pages and Web Controls

}

Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services

Index

List of Figures

This iteration of the Employee class defines two custom constructors, the second of which requires a single

List of Tables

parameter (the individual's name). However, to fully construct a new Employee, you want to ensure you have a proper Employee ID and rate of pay. Assume you have a custom class (IDGenerator) that defines a static method named GetNewEmpID() to generate a new ID for a given employee. Once you gather the correct set of start-up parameters, you forward the creation request to the alternate three-argument constructor. If you did not forward the call, you would need to add redundant code to each constructor:

// currPay automatically set to 0.0F...

public Employee(string fullName)

{

this.fullName = fullName;

this.empID = IDGenerator.GetNewEmpID();

}

Defining the "Default Public Interface" of a Type

C# and the .NET Platform, Second Edition

 

by Andrew Troelsen

ISBN:1590590554

Once you have establishedApress a class' internal state data and constructor set, your next step is to flesh out the

© 2003 (1200 pages)

details of the default public interface to the class. The term refers to the set of public members that are directly

This comprehensive text starts with a brief overview of the

accessible from anC#objectlanguagevariablend then. Fromquicklythe classmovesbuilder'sto key technicalpoint of view,and the default public interface is any item declared in a classarchitecturalusing the "public"issues forkeyword.NET developers. In C#, the. default interface of a class may be populated by any of the following members:

Table Methods:of ContentsNamed units of work that model some behavior of a class.

C# and the .NET Platform, Second Edition

Properties: Accessor and mutator functions in disguise.

Introduction

Part One - Introducing C# and the .NET Platform

Public field data: Although public data is typically a bad idea, C# supports it.

Chapter 1 - The Philosophy of .NET

ChapterAs you2will-seeBuildingChapterC# Applications7, the default public interface of a class may also be configured to support custom

ParteventsTwoand- ThedelegatesC# Programming. Furthermore,Languasgeyou will see later in this chapter, nested type definitions may also appea Chapteron a type's3 -defaultC# Langpublicage Fundaminterfacentals. For the time being, let's concentrate on the use of properties, methods, and

field data.

Chapter 4 - Object-Oriented Programming with C# Chapter 5 - Exceptions and Object Lifetime

ChaSpecifyingt r 6 - I terfacesTypeandVisibility:Collections Public and Internal Types

Chapter 7 - Callback Interfaces, Delegates, and Events

Before we get too far along into this employee example, you must understand how to establish visibility levels

Chapter 8 - Advanced C# Type Construction Techniques

for your custom types. In the previous chapter, you were introduced to the following class definition:

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Chapter// Note10 -theProcesses,lack AppDomainof access, Contexts,modifierand Threadson the class definition.

Chapterclass11HelloClass- Type Reflection, Late Binding, and Attribute-Based Programming

Part{ Four - Leveraging the .NET Libraries

// Any number of methods with any number of parameters...

Chapter 12 - Object Serialization and the .NET Remoting Layer

// Default and/or custom constructors...

Chapter 13 - Building a Better Window (Introducing Windows Forms)

// If this is the program's entry point, a static Main() method.

Chapter 14 - A Better Painting Framework (GDI+)

}

Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Recall that each member defined by a class must establish its level of visibility using the "public", "private",

Chapter 18 - ASP.NET Web Pages and Web Controls

"protected", "internal", or "protected internal" keywords. In the same vein, C# types also need to specify their

Chapter 19 - ASP.NET Web Applications

level of visibility. The distinction is that method visibility is used to constrain which members can be accessed

Chapter 20 - XML Web Services

from a given object, and type visibility is used to establish which parts of the system can create the types

Indthemselvesx .

List of Figures

A non-nested C# type can be marked by one of two visibility keywords: "public" or "internal" (as you will see

List of Tables

later in this chapter, nested types can be marked as "private"). Public types may be created by any other object within the same assembly as well as by other external assemblies. If you wish to allow HelloClass to be created by other .NET assemblies, you could redefine it as follows:

// We are now creatable by types outside this assembly.

public class HelloClass

{

//Any number of methods with any number of parameters...

//Default or custom constructors...

//If this is the program's entry point, a static Main() method.

}

By default, if you do not explicitly mark the visibility level of a class, it is implicitly set to "internal". Internal classe can only be created by types living within the same assembly, and are not accessible from outside the

assembly's bounds. As you might suspect, internal items can be viewed as "helper types" used by an

C# and the .NET Platform, Second Edition assembly's types to help the contained classes get their work done:

by Andrew Troelsen

ISBN:1590590554

Apress © 2003 (1200 pages)

// Internal classes can only be used by other types within the same assembly.

This comprehensive text starts with a brief overview of the internal class HelloClassHelper

C# language and then quickly moves to key technical and

{architectural issues for .NET developers.

...

}

Table of Contents

C# and the .NET Platform, Second Edition

Classes are not the only UDT that can accept a visibility attribute. As you recall, a type is simply a generic term

Introduction

used to refer to classes, structures, enumerations, interfaces, and delegates. Any .NET type can be assigned

Part One - Introducing C# and the .NET Platform

public or internal visibility. For example:

Chapter 1 - The Philosophy of .NET

Chapter 2 - Building C# Applications

// Any type may be assigned public or internal visibility.

Part Two - The C# Programming Language

namespace HelloTypes

Chapter 3 - C# Language Fundamentals

Chapter{

4

- Object-Oriented Programming with C#

Chapter //5

-CannotExceptionsbeandusedObjectoutsideLifetime this assembly.

Chapter internal6 - Interfacesstructand CollectionsX

 

{

- Callback Interfaces, Delegates, and Events

Chapter 7

Chapter 8

private int myX;

- Advanced C# Type Construction Techniques

 

 

public int GetMyX() { return myX; }

Part Three - Programming with .NET Assemblies

public X(int x){ myX = x; }

Chapter 9 - Understanding .NET Assemblies

}

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

// Cannot be used outside this assembly.

Part Four - Leveraging the .NET Libraries

internal enum Letters

Chapter 12 - Object Serialization and the .NET Remoting Layer

{ a = 0, b = 1, c = 2 }

Chapter //13 -MayBuildingbe ausedBetteroutsideWindow (InthisroducingassemblyWindows.Forms)

Chapter public14 - A BetterclassPaintingHelloClassFramework (GDI+)

Chapter {15 - Programming with Windows Forms Controls

public static int Main(string[] args)

Chapter 16 - The System.IO Namespace

{

Chapter 17 - Data Access with ADO.NET

X theX = new X(26);

Part Five - Web Applications and XML Web Services

Console.WriteLine("{0}\n{1}", theX.GetMyX(), Letters.b.ToString())

Chapter 18 - ASP.NET Web Pages and Web Controls

return 0;

Chapter 19 - ASP.NET Web Applications

}

Chapter 20 - XML Web Services

}

Index

}

List of Figures

List of Tables

Logically, the previously defined types can be envisioned as seen in Figure 4-2.

Figure 4-2: Internal and public types

Chapter 9 drills into the specifics of composing .NET assemblies. Until then, just understand that all of your

C# and the .NET Platform, Second Edition

nonnested types may be defined as public (accessible by other assemblies) or internal (not accessible by other

assemblies). by Andrew Troelsen ISBN:1590590554

Apress © 2003 (1200 pages)

This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.

Table of Contents

C# and the .NET Platform, Second Edition

Introduction

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

Chapter 2 - Building C# Applications

Part Two - The C# Programming Language

Chapter 3 - C# Language Fundamentals

Chapter 4 - Object-Oriented Programming with C#

Chapter 5 - Exceptions and Object Lifetime

Chapter 6 - Interfaces and Collections

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

RecappingC#theandPillarsthe .NETofPlatform,OOPSecond Edition

by Andrew Troelsen

ISBN:1590590554

C# is a newcomer to the world of object-oriented languages (OOLs). Java, C++, Object Pascal, and (to some

Apress © 2003 (1200 pages)

extent) Visual Basic 6.0 are but a small sample of the popularity of the object paradigm. Regardless of exactly

This comprehensive text starts with a brief overview of the

a given OOL cameC#intolanguageexistence,and thenall objectqui kly-basedmoveslanguagesto key technicalcontendandwith three core principals of object-orien programming, oftenarchitecturalcalled theissuesfamedfor"pillars.NET developersof OOP.".

Encapsulation: How well does this language hide an object's internal implementation?

Table of Contents

Inheritance: How does this language promote code reuse?

C# and the .NET Platform, Second Edition

Introduction

Polymorphism: How does this language let you treat related objects in a similar way?

Part One - Introducing C# and the .NET Platform

ChapterBefore1digging- TheintoPhilosophythe syntacticof .NETdetails of each pillar, it is important you understand the basic role of each.

ChapterTherefore,2 -hereBuildingis aC#brisk,Applicationshigh-level rundown, just to clear off any cobwebs you may have acquired between pr

PartdeadlinesTwo - The. C# Programming Language

Chapter 3 - C# Language Fundamentals

ChapterEncapsulation4 - Object-OrientedServicesProgramming with C#

Chapter 5 - Exceptions and Object Lifetime

ChapterThe first6 pillar- Interfacesof OOPandis calledCollectionsencapsulation. This trait boils down to the language's ability to hide unnecessar Chaimplementationt r 7 - CallbackdetailsInterfaces,from theDelegaobjectes,userand. ForEventsexample, assume you have created a class named DBReader

(database reader) that has two primary methods: Open() and Close():

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

Chapter// The9 database- Understandingreader.NET Assembliesencapsulates the details of opening and closing a databas

ChaptDBReaderr 10 - Processf = news, AppDomains,DBReader();Contexts, and Threads

Chapterf.Open11(@"C:\foo- Type Reflection,.mdf");Late Binding, and Attribute-Based Programming

Part Four//- LeveragingDo something.NETwithL brariesdatabase...

f.Close();

Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

The fictitious DBReader class has encapsulated the inner details of locating, loading, manipulating, and closing

Chapter 15 - Programming with Windows Forms Controls

data file. Object users love encapsulation, as this pillar of OOP keeps programming tasks simpler. There is no

Chapter 16 - The System.IO Namespace

to worry about the numerous lines of code that are working behind the scenes to carry out the work of the

Chapter 17 - Data Access with ADO.NET

DBReader class. All you do is create an instance and send the appropriate messages (e.g., "open the file nam

Part Five - Web Applications and XML Web Services

foo.mdf located on my C drive").

Chapter 18 - ASP.NET Web Pages and Web Controls

ChaptCloselyr 19related- ASP.toNETtheWebnotionApplicationsof encapsulating programming logic is the idea of data hiding. As you know, an obj Chapterstate data20 -shouldXML WebideallyServicesbe specified as private. In this way, the outside world must ask politely in order to chan

obtain the underlying value. This is a good thing, as publicly declared data points can easily become corrupted

Index

(hopefully by accident rather than intent!).

List of Figures

List of Tables

Inheritance: The "is-a" and "has-a" Relationships

The next pillar of OOP, inheritance, boils down to the languages' ability to allow you to build new class definition based on existing class definitions. In essence, inheritance allows you to extend the behavior of a base (parent) class by inheriting core functionality into a subclass (also called a child class or derived class).Figure 4-3 show simple example.

Part Three - Programming with .NET Assemblies

Second Edition

ISBN:1590590554

with a brief overview of the

moves to key technical and

developers.

Table

C# andFigurethe .NET4-3:Platform,The "is-a"SecondrelationshipEdition

Introduction

Part One - Introducing C# and the .NET Platform

As you are aware, System.Object is always the topmost node in any .NET hierarchy. Here, the Shape class ext

Chapter 1 - The Philosophy of .NET

Object. You can assume that Shape defines some number of properties, fields, methods, and events that are

Chapter 2 - Building C# Applications

common to all shapes. The Hexagon class extends Shape, and inherits the core functionality defined by Shape

Part Two - The C# Programming Language

Object, as well as defines additional hexagon-related details of its own (whatever those may be).

Chapter 3 - C# Language Fundamentals

ChapterYou can4 read- Objectthis -diagramOrientedasProgramming"A hexagonwithis-aC#shape that is-an object." When you have classes related by this f Chapterof inheritance,5 - Exceptionsyou establishand Object"is-a"Lifetimerelationships between types. The "is-a" relationship is often termed classical

inheritance.

Chapter 6 - Interfaces and Collections

Chapter 7 - Callback Interfaces, Delegates, and Events

There is another form of code reuse in the world of OOP: the containment/delegation model (also known as th

Chapter 8 - Advanced C# Type Construction Techniques

"has-a" relationship). This form of reuse is not used to establish base/subclass relationships. Rather, a given cl

can define a member variable of another class and expose part or all of its functionality to the outside world.

Chapter 9 - Understanding .NET Assemblies

ChaptFor example,r 10 - Processes,if you areAppDomains,modeling anConautomobile,exts, andyouThreadsmight wish to express the idea that a car "has-a" radio. It

Chapterwould be11illogical- Type Reflection,to attemptLateto deriveBinding,theandCarAttributeclass from-BasedRadio,Programmingor vice versa. (A Car "is-a" Radio? I think not!

PartRather,Four you- Leveraginghave twotheindependent.NET Librariesclasses working together, where the containing class creates and exposes t

Chapcontaineder 12 -class'ObjectfunctionalitySerialization(Figureand the4-.4NET). Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter

Chapter

Chapter

Chapter

Part

Chapter

ChapterFigure19 - 4ASP-4:.NETTheWeb"has-Applicationsa" relationship

Chapter 20 - XML Web Services

Here, the containing type (Car) is responsible for creating the inner object (Radio). If the Car wishes to make th

Index

Radio's behavior accessible from a Car instance, it must extend its own public interface with some set of functio

List of Figures

that operate on the inner type. Notice that the object user has no clue that the Car class is making use of an inn

List of Tables object.

// The inner Radio is encapsulated by the outer Car class.

Car viper = new Car();

viper.TurnOnRadio(false);

// Forward request to inner Radio object.

Polymorphism: Classical and Ad Hoc

The final pillar of OOP is polymorphism. This trait captures a language's ability to treat related objects the same way. Like inheritance, polymorphism falls under two camps: classical and ad hoc. Classical polymorphism can take place in languages that also support classical inheritance. If this is the case (as it is in C#), it becomes pos for a base class to define a set of members that can be overridden by a subclass. When sub-classes override t behavior defined by a base class, they are essentially redefining how they respond to the same message.

To illustrate classical polymorphism, let's revisit the shapes hierarchy. Assume that the Shape class has define

C# and the .NET Platform, Second Edition

function named Draw(), taking no parameters and returning nothing. Given the fact that every shape needs to

by Andrew Troelsen ISBN:1590590554

render itself in a unique manner, subclasses (such as Hexagon and Circle) are free to reinterpret this method t

Apress © 2003 (1200 pages)

their own liking (Figure 4-5).

This comprehensive text starts with a brief overview of the

C# language and then quickly moves to key technical and

developers.

Table

C# and

Part

Chapter

Chapter 2 - Building C# Appolymorphismlications

Figure 4-5: Classical

Part Two - The C# Programming Language

ChapterClassical3 polymorphism- C# LanguageallowsFundamentalsbase class to enforce a given behavior on all descendents. From Figure 4-5,

can assume that any object derived from the Shape class has the ability to be rendered. This is a great boon to

Chapter 4 - Object-Oriented Programming with C#

language because you are able to avoid creating redundant methods to perform a similar operation (e.g.,

Chapter 5 - Exceptions and Object Lifetime

DrawCircle(), DrawRectangle(), DrawHexagon(), and so forth).

Chapter 6 - Interfaces and Collections

Chapter 7 - Callback Interfaces, Delegates, and Events

Next, you have ad hoc polymorphism. This flavor of polymorphism allows objects that are not related by classic

Chapter 8 - Advanced C# Type Construction Techniques

inheritance to be treated in a similar manner, provided that every object has a method of the exact same signat

Part Three - Programming with .NET Assemblies

(that is, method name, parameter list, and return type). Languages that support ad hoc polymorphism employ a

Chapter 9 - Understanding .NET Assemblies

technique called late binding to discover at runtime the underlying type of a given object. Based on this discove

Chapter 10 - Processes, AppDomains, Contexts, and Threads

the correct method is invoked. As an illustration, first ponder Figure 4-6.

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Chapter

Chapter

Chapter

Chapter

Chapter

Chapter

Part

ChapterFigure18 - 4ASP-6:.NETAd hocWebpolymorphismPages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Notice how there is no common base class between the CCircle, CHexagon, and CRectangle classes. Howeve

Index

each class supports an identical Draw() method. To illustrate what this boils down to syntactically, consider the

List of Figures

following Visual Basic 6.0 code. Until the advent of VB .NET, the Visual Basic language did not support classica

List of Tables

polymorphism (or classical inheritance for that matter), forcing developers to make due with the following ad ho functionality:

'Visual Basic 6.0 code below!

'First create an array of Object data types, setting each to an object referenc

Dim objArr(3) as Object

Set objArr(0) = New CCircle

Set objArr(1) = New CHexagon

Set objArr(2) = New CCircle

Set objArr(3) = New CRectangle

' Now loop over the array, asking each object to render itself.

Dim i as Integer

For i = 0 to 3

objArr(i).Draw

' Late binding...

Next i

In this code block,C#youandbeginthe by.NETcreatingPlatform,an arraySecondof genericEditionObject data types (which is an intrinsic Visual Basic type capable of holdingby A drewanyTroelsenobject reference, and has nothingISBN:1590590554to do with System.Object). As you iterate over th array at runtime, Apresseach shape© 2003is(1200askedpages)to render itself. Again, the key difference is that you have no common ba

class that contains a default implementation of the Draw() method.

This comprehensive text starts with a brief overview of the

C# language and then quickly moves to key technical and

Note A savvyarchitectuVB programmerl issuescouldfor .NETmaked velopersuse of interface. -based programming techniques (as opposed to hoc polymorphism) to build relationships among related classes, but that's another story. We'll exami the role of interfaces in Chapter 6.

Table of Contents

To wrap up this brisk review of the pillars of OOP, recall that every object-oriented language needs to address

C# and the .NET Platform, Second Edition

it contends with encapsulation, polymorphism, and inheritance. As you may already suspect, C# completely

Introduction

supports each pillar of object technology, including both flavors of inheritance ("is-a" and "has-a") as well as

Part One - Introducing C# and the .NET Platform

classical and ad hoc polymorphism. Now that you have the theory in your minds, the bulk of this chapter explor

Chapter 1 - The Philosophy of .NET

the exact C# syntax that represents each trait.

Chapter 2 - Building C# Applications

Part Two - The C# Programming Language

Chapter 3 - C# Language Fundamentals

Chapter 4 - Object-Oriented Programming with C#

Chapter 5 - Exceptions and Object Lifetime

Chapter 6 - Interfaces and Collections

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

The First Pillar:C# andC#'sthe .NETEncapsulationPlatform, Second EditionServices

by Andrew Troelsen

ISBN:1590590554

The concept of encapsulation revolves around the notion that an object's internal data should not be directly

Apress © 2003 (1200 pages)

accessible from an object instance. Rather, if an object user wishes to alter the state of an object, it does so

This comprehensive text starts with a brief overview of the

indirectly using accessorC# language(get)andandthenmutatorquickly(set)movesmethodsto key. IntechnicalC#, encapsulationand is enforced at the syntactic leve using the "public",architectural"private", "protected",issu s for .NETanddevelopers"protected. internal" keywords. To illustrate, assume you have crea the following class definition:

Table of Contents

// A class with a single field.

C# and the .NET Platform, Second Edition

public class Book

Introduction

{

Part One - Introducing C# and the .NET Platform

public int numberOfPages;

Chapter 1 - The Philosophy of .NET

...

Chapter 2 - Building C# Applications

}

Part Two - The C# Programming Language

Chapter 3 - C# Language Fundamentals

ChapterWhen a4class- Objectdefines-OrientedpointsProgrof data,mmingwe typicallywith C# term these items fields. The problem with public field data is t

the items have no ability to "understand" if the current value to which they are assigned is valid with regard to th

Chapter 5 - Exceptions and Object Lifetime

current business rules of the system. As you know, the upper range of a C# integer is quite large (2,147,483,64

Chapter 6 - Interfaces and Collections

Therefore, the compiler allows the following assignment:

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter 8 - Advanced C# Type Construction Techniques

Part// ThreeHumm-...Programming with .NET Assemblies

public static void Main()

Chapter 9 - Understand ng .NET Assemblies

{

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Book miniNovel = new Book();

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

miniNovel.numberOfPages = 30000000;

Part Four - Leveraging the .NET Libraries

}

Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Although you do not overflow the boundaries of an integer data type, it should be clear that a mini-novel with a

Chapter 15 - Programming with Windows Forms Controls

page count of 30,000,000 pages is a bit unreasonable. As you can see, public fields do not provide a way to tra

Chapter 16 - The System.IO Namespace

logical upper (or lower) limits. If your current system has a business rule that states a mini-novel must be betwe

Chapter 17 - Data Access with ADO.NET

1 and 200 pages, you are at a loss to enforce this programmatically. Because of this, public fields typically have

PartplaceFivein-aWebproductionApplications-level andclassXMLdefinitionWeb Services.

Chapter 18 - ASP.NET Web Pages and Web Controls

Encapsulation provides a way to preserve the integrity of state data. Rather than defining public fields (which ca

Chapter 19 - ASP.NET Web Applications

easily foster data corruption), you should get in the habit of defining private data fields, which are indirectly

Chapter 20 - XML Web Services

manipulated using one of two main techniques:

Index

List of Figures

Define a pair of traditional accessor and mutator methods.

List of Tables

Define a named property.

Additionally, C# supports a special keyword, "readonly," that also delivers an additional form of data protection. Whichever technique you choose, the point is that a well-encapsulated class should hide its raw data and the details of how it operates from the prying eyes of the outside world. This is often termed black box programming

The beauty of this approach is that an object is free to change how a given method is implemented under the hood, without breaking any existing code making use of it (provided that the signature of the method remains constant).

Enforcing Encapsulation Using Traditional Accessors and Mutators

Let's return to the existing Employee class. If you want the outside world to interact with your private fullName d field, tradition dictates defining an accessor (get method) and mutator (set method). For example, if you wish to provide safe access to the Employee's internal fullName data member using accessors and mutators, you wou write:

private string fullName;
This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and
architectural issues for .NET developers.
// Accessor.

// TraditionalC# andccessorthe .NETandPlatform,mutatorSecondforEditiona point of private data.

public class byEmployeeAndrew Troelsen ISBN:1590590554

{Apress © 2003 (1200 pages)

...

public string GetFullName() { return fullName; }

// Mutator.

Table of Contents

public void SetFullName(string n)

C# and the .NET Platform, Second Edition

{

Introduction

// Remove any illegal characters (!, @, #, $, %),

 

Part One - Introducing C# and the .NET Platform

 

// check maximum length (or case rules) before making assignment.

Chapter 1 - The Philosophy of .NET

 

fullName = n;

Chapter 2 - Building C# Applications

}

 

Part Two - The C# Programming Language

}

 

Chapter 3 - C# Language Fundamentals

Chapter 4 - Object-Oriented Programming with C#

Chapter 5 - Exceptions and Object Lifetime

Understand, of course, that the compiler could care less what you call your accessor and mutator methods. Gi

Chapter 6 - Interfaces and Collections

the fact that GetFullName() and SetFullName() encapsulate a private string named fullName, this choice of

Chapter 7 - Callback Interfaces, Delegates, and Events

method names seems to fit the bill. The calling logic is as follows:

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

// Accessor/mutator usage.

Chapter 9 - Understanding .NET Assemblies

public static int Main(string[] args)

Chapter 10 - Processes, AppDomains, Contexts, and Threads

{

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Employee p = new Employee();

Part Four - Leveraging the .NET Libraries

p.SetFullName("Fred Flintstone");

Chapter 12 - Object Serialization and the .NET Remoting Layer

Console.WriteLine("Employee is named: {0}", p.GetFullName());

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

// Error below! Can't access private data from an object instance.

Chapter 15 - Programming with Windows Forms Controls

// p.fullName;

Chapter 16 - The System.IO Namespace return 0;

Chapter 17 - Data Access with ADO.NET

}

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Another Form of Encapsulation: Class Properties

Chapter 20 - XML Web Services

Index

In addition to traditional accessor and mutator methods, .NET classes (as well as structures and interfaces) can

List of Figures

also define properties. Visual Basic and COM programmers have long used properties to simulate publicly Listaccessibleof Ta l spoints of data (that is, fields). Under the hood, however, properties resolve to a pair of hidden interna methods. Rather than requiring the user to call two discrete methods to get and set the state data, the user is a to call what appears to be a single named field. To illustrate, assume you have provided a property named Em that wraps the internal empID member variable of the Employee type. The calling logic would look like this:

// Representing a person's first name as a property.

public static int Main(string[] args)

{

Employee p = new Employee();

// Set the value.

p.EmpID = 81;

// Get the value.

Console.WriteLine("Person ID is: {0} ", p.EmpID); return 0;

}

C# and the .NET Platform, Second Edition

Type properties always map to "real" accessor and mutator methods. Therefore, as a class designer you are a by Andrew Troelsen ISBN:1590590554

to perform any internal logic necessary before making the value assignment (e.g., uppercase the value, scrub t

Apress © 2003 (1200 pages)

value for illegal characters, check the bounds of a numerical value, and so on). Here is the C# syntax behind th

This comprehensive text starts with a brief overview of the EmpID property: C# language and then quickly moves to key technical and

architectural issues for .NET developers.

// Custom property for the EmpID data point.

public class Employee

Table of Contents

{

C# and the .NET Platform, Second Edition

...

Introduction

private int empID;

Part One - Introducing C# and the .NET Platform

// Property for the empID data point.

Chapter 1 - The Philosophy of .NET

public int EmpID

Chapter 2 - Building C# Applications

{

Part Two - The C# Programming Language

get { return empID;}

Chapter 3 - C# Language Fundamentals

set

Chapter 4 - Object{ -Oriented Programming with C#

Chapter 5 - Exceptions// andYouObjectare Lifetstillme free to investigate (and possibly transform)

Chapter 6 - Interfaces//andtheCollectiincomingns value before making an assignment.

empID = value;

Chapter 7 - Callback Interfaces, De egates, and Events

}

Chapter 8 - Advanced C# Type Construction Techniques

}

Part Three - Programming with .NET Assemblies

}

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

A C# property is composed using a get block (accessor) and set block (mutator). The C# "value" keyword

Part Four - Leveraging the .NET Libraries

represents the right-hand side of the assignment. Like all things in C#, "value" is also an object. However, the

Chapter 12 - Object Serialization and the .NET Remoting Layer

underlying type of the object depends on which sort of data it represents. In this example, the EmpID property is

Chapter 13 - Building a Better Window (Introducing Windows Forms) operating on a private integer, which, as you recall, maps to a System.Int32:

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

// 81 is an instance of System.Int32, so 'value' is a System.Int32.

Chapter 16 - The System.IO Namespace e3.EmpID = 81;

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

ChapterTo prove18the- ASPpoint,.NETassumeWeb PagesyouandhaveWebupdatedControlsyour set logic as follows:

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

// Property for the empID.

Index

public int EmpID

List{ of Figures

List of Tablesget { return empID;}

set

{

#if DEBUG

Console.WriteLine("value is an instance of: {0} ", value.GetType());

Console.WriteLine("value as string: {0} ", value.ToString());

#endif

empID = value;

}

}

You would see the output shown in Figure 4-7.

Edition

ISBN:1590590554

brief overview of the key technical and

.

Figure 4-7: The value of "value" when setting EmpID to 81

Table of Contents

Note Strictly speaking, the C# "value" token is not a keyword, but rather a placeholder that represents the

C# and the .NET Platform, Second Edition

Introductionimplicit parameter used during a property assignment. Therefore, you are free to have member varia

and local data points named "value".

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

Understand that properties (as opposed to traditional accessors and mutators) tend to make your types easier t

Chapter 2 - Building C# Applications

manipulate, in that properties are able to respond to the intrinsic operators of C#. For example, assume that the

Part Two - The C# Programming Language

Employee type had an internal private member variable representing the age of the employee. On his or her

Chapter 3

- C# Language Fundamentals

birthday, you wish to increment the age by one. Using traditional accessor and mutator methods, you would ne

Chapter 4

- Object-Oriented Programming with C#

to write:

 

Chapter 5

- Exceptions and Object Lifetime

Chapter 6

- Interfaces and Collections

Employee joe = new Employee();

Chapter 7

- Callback Interfaces, Delegates, and Events

joe.SetAge(joe.GetAge() + 1);

Chapter 8

- Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

ChaptHowever,r 9 using- U derstandingtype properties,.NET Assembliesyou are able to simply write:

Chapter 10

- Processes, AppDomains, Contexts, and Threads

Chapter 11

- Type Reflection, Late Binding, and Attribute-Based Programming

Employee joe = new Employee();

PartjoeFour.Age- ++;Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

This being said, for the examples that follow, assume you have configured the Employee type to support a

Chapter 14 - A Better Painting Framework (GDI+)

property named Pay that interacts with the private currPay field:

Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace

// Property for the currPay.

Chapter 17 - Data Access with ADO.NET

public float Pay

Part Five - Web Applications and XML Web Services

{

Chapter 18 - ASP.NET Web Pages and Web Controls

get {return currPay;}

Chapter 19 - ASP.NET Web Applications

set {currPay = value;}

Chapter 20 - XML Web Services

}

Index

List of Figures

List of Tables

Internal Representation of C# Properties

Many programmers (especially those of the C++ ilk) tend to design traditional accessor and mutator methods using "get_" and "set_" prefixes (e.g., get_Name() and set_Name()). This naming convention itself is not problematic. However, it is important to understand that under the hood, a C# property is internally represented using these same prefixes. For example, if you open up the Employees.exe assembly using ildasm.exe, you se that each property actually resolves to two discrete (and hidden) methods (Figure 4-8).

 

Second Edition

 

ISBN:1590590554

 

with a brief overview of the

 

moves to key technical and

 

developers.

Table

 

C# and

 

Part

 

Chapter

 

Chapter

 

Part

 

Chapter

 

Chapter

C#

Chapter 5 - Exceptions and Object Lifetime

Figure 4-8: Properties map to hidden get_ and set_ methods.

Chapter 6 - Interfaces and Collections

ChapterAssume7 the- CallbackEmployeeInterfaces,type nowDelegates,has privateand Evmembernts variable named empSSN to represent an individual's

Social Security number, which is manipulated by a property named SSN. Given the previous property-related

Chapter 8 - Advanced C# Type Construction Techniques

factoid, if you were to also define two methods named get_SSN() and set_SNN(), you would be issued compile

Part Three - Programming with .NET Assemblies

Chaptertime errors:9 - Understanding .NET Assemblies

 

Chapter 10

- Processes, AppDomains, Contexts, and Threads

Chapter// Remember,11 - Type Reflection,a C# propertyLate Binding,reallyand Attributemaps -toBased Programmingget /set_ pair.

PartpublicFour - classLeveragingEmployeethe .NET Libraries

 

Chapter{

12

- Object Serialization and the .NET Remoting Layer

Chapter //13

-AssumeBuilding athisBettermemberWindow (Introducingis assignedWindowsby theForms)class constructors.

Chapter private14 - A BetterstringPaintingempSSN;Framework (GDI+)

 

Chapter...

15

- Programming with Windows Forms Controls

 

Chapter public16 - The System.IOstring SSNNamespace

 

Chapter {17

- Data Access with ADO.NET

// Maps to get_SSN().

Part Five - WebgetApplications{ returnand XMLempSSN;Web Services}

Chapter 18

- ASP.NETset {WebempSSNPages and= value;}Web Controls

// Maps to set_SSN().

 

}

- ASP.NET Web Applications

 

Chapter 19

 

Chapter 20

- XML Web Services

 

Index

// ERROR! Already defined under the hood by SSN property!

public string get_SSN() { return empSSN;}

List of Figures

empSSN = val;}

 

public void set_SSN(string val) {

List of Tables

}

Finally, understand that the reverse of this situation is not true. Meaning, if you define two methods named get_ and set_X() in a given class, you cannot write syntax that references a property named X:

//Assume Foo has two methods named get_X() and set_X() but not a

//literal C# property definition.

Foo

f

= new Foo();

//

Error!

!

Must

be defined as C# property,

not set_X

f.X

=

100;

Console.WriteLine(f.X);

//

Error!

!

Must

also be a C# property, not

get_X().

float currPay, string ssn)

Note The .NETC#baseand theclass.NETlibrariesPlatform,alwaysSecondfavor typeEditionproperties over traditional accessor and mutator methodsby. Therefore,Andr w Troelsenif you wish to build custom typesISBN:1590590554that integrate well with the .NET platform, avoid definingAprGetXXX()ss © 2003and(1200SetXXX()pages) methods.

This comprehensive text starts with a brief overview of the

C# language and then quickly moves to key technical and

Read-Only and Write-Only Properties

architectural issues for .NET developers.

Recall that EmpID was established as a read/write property. When building custom properties, you may wish to

configure a read-only property. To do so, simply build a property without a corresponding set block. Likewise, if

Table of Contents

wish to have a write-only property, omit the get block. To illustrate, here is the SSN property, retrofitted as read-

C# and the .NET Platform, Second Edition

only (note that the constructor set has been modified to allow the caller to set the initial value of the private

Introduction empSSN field):

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

public class Employee

Chapter 2 - Building C# Applications

{

Part Two - The C# Programming Language

...

Chapter 3 - C# Language Fundamentals

private string empSSN;

Chapter 4 - Object-Oriented Programming with C#

public Employee(string FullName, int empID,

Chapter 5 - Exceptions and Object Lifetime

Chapter 6 - Interfaces and Collections

{

Chapter 7 - Callback Interfaces, Delegates, and Events

this.fullName = FullName;

Chapter 8 - Advanced C# Type Construction Techniques

this.empID = empID;

Part Three - Programming with .NET Assemblies

this.currPay = currPay;

Chapter 9 - Understanding .NET Assemblies

this.empSSN = ssn;

Chapter}10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

// Now as a read-only property.

Part Fourpublic- Leveragingstringthe SSN.NET Libraries{ get { return empSSN; } }

Chapter} 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

ChapterUnderstanding15 - ProgrammingStaticwith WindowsPropertiesForms Controls

Chapter 16 - The System.IO Namespace

ChapterC# also17supports- Data Accessstatic propertieswith ADO.NET. Recall that static members are bound to a given class, not an instance (obje

Partof thatFiveclass- Web. ForApplicationsexample, assumend XML Webthat theS rvicesEmployee type defines a point of static data to represent the name

Chapterthe organization18 - ASP.NETemployingWeb PagestheseandworkersWeb Controls. You may define a static (e.g., class level) property as follows:

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

// Static properties must operate on static data!

Indexpublic class Employee

List{ of Figures

List of Tablesprivate static string companyName; public static string Company

{

get { return companyName; } set { companyName = value;}

}

...

}

Static properties are manipulated in the same manner as static methods, as seen here:

// Set and get the name of the company that employs these people...

public static int Main(string[] args)

{

Employee.Company = "Intertech, Inc";

Console.WriteLine("These folks work at {0} ", Employee.Company);

}

...

C# and the .NET Platform, Second Edition

 

by Andrew Troelsen

ISBN:1590590554

 

Apress © 2003 (1200 pages)

This comprehensive text starts with a brief overview of the

C# language and then quickly moves to key technical and

Understanding Static Constructors

architectural issues for .NET developers.

As an interesting sidebar to the topic of static properties, consider the use of static constructors. This construct

seem strange given that the term constructor is typically understood as a method called to create a new object.

Table of Contents

Nevertheless, C# supports the use of static constructors that serve no other purpose than to assign initial value

C# and the .NET Platform, Second Edition

static data. Syntactically, static constructors are odd in that they cannot take a visibility modifier (but must take t

Introduction

"static" keyword).

Part One - Introducing C# and the .NET Platform

ChapterTo illustrate,1 - Theif youPhilosophywished tof ensure.NET that the name of the static companyName field was always assigned to Chapter"Intertech,2 -Inc"Buildingby default,C# Applicationsyou would write:

Part Two - The C# Programming Language

Chapter 3 - C# Language Fundamentals

// Static constructors are used to initialize static data.

Chapterpublic4 class- ObjectEmployee-Oriented Programming with C#

Chapter{ 5 - Exceptions and Object Lifetime

Chapter... 6 - Interfaces and Collections

private static string companyName;

Chapter 7 - Callback In erfaces, Delegates, and Events

static Employee()

Chapter 8 - Advanced C# Type Construction Techniques

{ companyName = "Intertech, Inc"; }

Part Three - Programming with .NET Assemblies

}

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

If you were to invoke the Employee.Company property, there would be no need to assign an initial value within

Part Four - Leveraging the .NET Libraries

Main() method, as the static constructor does so automatically:

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

// Automatically set to "Intertech, Inc" via the static constructor.

Chapter 14 - A Better Painting Framework (GDI+) public static int Main(string[] args)

Chapter 15 - Programming with Windows Forms Controls

{

Chapter 16 - The System.IO Namespace

Console.WriteLine("These folks work at {0} ", Employee.Company);

Chapter 17 - Data Access with ADO.NET

}

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

ChapterTo wrap19up- thisASP.examinationNET Web Applicationsof C# properties, understand that these syntactic entities are used for the same Chapterpurpose20as- aXMLclassicalWeb Servicesaccessor/mutator pair. The benefit of properties is that the users of your objects are able

manipulate the internal data point using a single named item.

Index

List of Figures

List of Tables

Chapter 20 - XML Web Services
Chapter 19 - ASP.NET Web Applications

Pseudo-Encapsulation:C# and the .NET Platform,CreatingSecondReadEdition-Only Fields

by Andrew Troelsen

ISBN:1590590554

Closely related to read-only properties is the notion of read-only fields. Read-only fields offer data preservation

Apress © 2003 (1200 pages)

via the "readonly" keyword. By way of a simple example, assume you have a read-only field named SSNField

This comprehensive text starts with a brief overview of the

that offers an alternativeC# languagemannerandforthenthequicklycallermovesto obtainto keyan employee'stechnical andSSN (again note that you update the constructor to assignarchitecturala value toissuesthis forread.NET-onlydevelopersfield): .

public class Employee

Table of Contents

{

C# and the .NET Platform, Second Edition

...

Introduction

// Read-only field (set in the ctors).

Part One - Introducing C# and the .NET Platform

public readonly string SSNField;

Chapter 1 - The Philosophy of .NET

public Employee(string FullName, int empID,

Chapter 2 - Building C# Applications

float currPay, string ssn)

Part Two{- The C# Programming Language

Chapter 3 - C# Language Fundamentals

this.fullName = FullName;

Chapter 4 - Object-Oriented Programming with C# this.empID = empID;

Chapter 5 - Exceptionsthis.currPayand Object= LifetimecurrPay;

Chapter 6 - Inthiserfaces.empSSNand Collections= ssn;

Chapter 7 - Callback// AssignInterfaces,readDelegates,-only fieldand Events.

SSNField = ssn;

Chapter 8 - Advanced C# Type Construction Techniques

}

Part Three - Programming with .NET Assemblies

}

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

As you can guess, any attempt to make assignments to a field marked "readonly" results in a compiler error:

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

// Error! This code won't compile!

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Employee brenner = new Employee();

Chapter 14 - A Better Painting Framework (GDI+) brenner.SSNField = "666-66-6666";

Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Static Read-Only Fields

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Static read-only fields are also permissible. This can be helpful if you wish to create a number of constant values bound to a given class. In this light, "readonly" seems to be a close cousin to the "const" keyword. The

difference is that the value assigned to "const" must be resolved at compile time, and therefore cannot be

Index

assigned a new type instance (as this is computed at runtime). The value of read-only static fields, however,

List of Figures

may be computed at runtime, and therefore may be assigned type instances as well as simply data types (int,

List of Tables float, string, etc.).

For example, assume a type named Car that needs to establish a set of tires at runtime. You can create a new class (Tire) consisting of a number of static read-only fields:

// The Tire class has a number of read-only fields.

public class Tire

{

//Given that the state of the Tire type is determined at

//runtime, we cannot use the 'const' keyword here!

//ERROR: public const Tire GoodStone = new Tire(90);

//In contrast, the 'readonly' keyword can be assigned

//values which are computed at runtime.

public static readonly Tire GoodStone = new Tire(90); public static readonly Tire FireYear = new Tire(100);

public static readonly Tire ReadyLyne= new Tire(43);

C# and the .NET Platform, Second Edition

public static readonly Tire Blimpy = new Tire(83);

by Andrew Troelsen

ISBN:1590590554

private int manufactureID;

 

Apress © 2003 (1200 pages)

 

public int MakeID

 

This comprehensive text starts with a brief overview of the

{ get { return manufactureID; } }

C# language and then quickly moves to key technical and public Tire (int ID)

architectural issues for .NET developers.

{ manufactureID = ID; }

}

Table of Contents

C# and the .NET Platform, Second Edition

Introduction

Here is an example of working with these new types:

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

// Make use of a dynamically created read-only field.

Chapter 2 - Building C# Applications

public class Car

Part Two - The C# Programming Language

{

Chapter 3 - C# Language Fundamentals

// What sort of tires do I have?

Chapter 4 - Object-Oriented Programming with C#

public Tire tireType = Tire.Blimpy; // Returns a new Tire.

Chapter 5 - Exceptions and Object Lifetime

...

Chapter 6 - Interfaces and Collections

}

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapterpublic8 class- AdvancedCarAppC# Type Construction Techniques

Part{ Three - Programming with .NET Assemblies

Chapter public9 - Undersstandticng int.NET AssembliesMain(string[] args)

Chapter {10 - Processes, AppDomains, Contexts, and Threads

Car c = new Car();

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

// Prints out "Manufacture ID of tires: 83"

Chapter 12 - Object Serialization and the .NET Remoting Layer

Console.WriteLine("Manufacture ID of tires: {0} ", c.tireType.MakeID);

Chapter 13 - Building a Better Window (Introducing Windows Forms)

return 0;

Chapter 14 - A Better Painting Framework (GDI+)

}

Chapter 15 - Programming with Windows Forms Controls

}

Chapter 16 - The System.IO Namespace Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

SOURCE The StaticReadOnlyData project is included under the Chapter 4 subdirectory.

Chapter 19 - ASP.NET Web Applications

CODE

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

Соседние файлы в предмете Программирование