- •Table of Contents
- •C# and the .NET Platform, Second Edition
- •Introduction
- •Part One: Introducing C# and the .NET Platform
- •Part Two: The C# Programming Language
- •Part Three: Programming with .NET Assemblies
- •Part Four: Leveraging the .NET Libraries
- •Part Five: Web Applications and XML Web Services
- •Obtaining This Book's Source Code
- •The .NET Solution
- •What C# Brings to the Table
- •The Role of the Assembly Manifest
- •Summary
- •Chapter 2: Building C# Applications
- •Summary
- •Chapter 3: C# Language Fundamentals
- •Defining Program Constants
- •Defining Custom Class Methods
- •C# Enumerations
- •Summary
- •The Second Pillar: C#'s Inheritance Support
- •Summary
- •Catching Exceptions
- •Finalizing a Type
- •Garbage Collection Optimizations
- •Summary
- •Chapter 6: Interfaces and Collections
- •Building Comparable Objects (IComparable)
- •Summary
- •Summary
- •Internal Representation of Type Indexers
- •Summary
- •An Overview of .NET Assemblies
- •Understanding Delayed Signing
- •Using a Shared Assembly
- •GAC Internals
- •Summary
- •Spawning Secondary Threads
- •A More Elaborate Threading Example
- •Summary
- •Summary
- •Object Persistence in the .NET Framework
- •The .NET Remoting Namespaces
- •Understanding the .NET Remoting Framework
- •All Together Now!
- •Terms of the .NET Remoting Trade
- •Testing the Remoting Application
- •Revisiting the Activation Mode of WKO Types
- •Deploying the Server to a Remote Machine
- •Summary
- •Control Events
- •The Form Class
- •Summary
- •Regarding the Disposal of System.Drawing Types
- •Understanding the Graphics Class
- •Summary
- •The TextBox Control
- •Working with Panel Controls
- •Configuring a Control's Anchoring Behavior
- •Summary
- •Chapter 16: The System.IO Namespace
- •The Static Members of the Directory Class
- •The Abstract Stream Class
- •Summary
- •The Role of ADO.NET Data Providers
- •The Types of System.Data
- •Selecting a Data Provider
- •The Types of the System.Data.OleDb Namespace
- •Working with the OleDbDataReader
- •Summary
- •Submitting the Form Data (GET and POST)
- •Some Benefits of ASP.NET
- •Creating an ASP.NET Web Application by Hand
- •The Composition of an ASP.NET Page
- •The Derivation of an ASP.NET Page
Building Comparable Objects (IComparable) |
|
C# and the .NET Platform, Second Edition |
|
by Andrew Troelsen |
ISBN:1590590554 |
The IComparable interface (defined in the System namespace) specifies a behavior that allows an object
Apress © 2003 (1200 pages)
to be sorted based on some internal key. Here is the formal definition:
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.
// This interface allows an object to specify its
// relationship between other like objects.
interfaceIComparable
Table of Contents
{
C# and the .NET Platform, Second Edition int CompareTo(object o);
Introduction
}
Part One - Introducing C# and the .NET Platform
Chapter 1 - The Philosophy of .NET
ChapterLet's assume2 - Buildingyou haveC# Aupdatedplicationsthe Car class to maintain an internal ID number. Object users might
PacreateTwoan- ThearrayC#ofProgCarammingtypes asLanguagefollows:
Chapter 3 - C# Language Fundamentals
Chapter 4 - Object-Oriented Programming with C#
// Make an array of Car types.
ChCar[]pter 5 - Exceptions and Object Lifetime
myAutos = new Car[5];
ChaptermyAutos[0]6 - Interfac= news andCar(123,Collections"Rusty");
ChaptermyAutos[1]7 - Callback= newInterfaces,Car(6,Delegates,"Mary");and Events
ChaptermyAutos[2]8 - Advanced= newC#Car(83,Type Construction"Viper");Techniques
PartmyAutos[3]Three - Programming= new Car(13,with .NET "NoName");Assemblies
myAutos[4] = new Car(9873, "Chucky");
Chapter 9 - Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
As you recall, the System.Array class defines a static method named Sort(). When you invoke this method on an array of intrinsic types (e.g., int, short), you are able to sort the items in the array from lowest to
highest, as these intrinsic data types implement IComparable. However, what if you were to send an array
Chapter 13 - Building a Better Window (Introducing Windows Forms) of Car types into the Sort() method as follows:
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 |
- Programming with Windows Forms Controls |
|
Chapter// Sort16 |
-myThecars?System.IO Namespace |
|
Array.Sort(myAutos); |
// Nope, not yet...sorry! |
|
Chapter 17 |
- Data Access with ADO.NET |
|
Part Five - Web Applications and XML Web Services |
||
Chapter 18 |
- ASP.NET Web Pages and Web Controls |
|
If you run this test, you would find that an ArgumentException exception is thrown by the runtime, with the |
||
Chapter 19 |
- ASP.NET Web Applicati ns |
following message: "At least one object must implement IComparable." Therefore, when you build custom
Chaptertypes, you20 -canXMLimplementWeb S rvicesIComparable to allow arrays of your types to be sorted. When you flesh out the
Indexdetails of CompareTo(), it will be up to you to decide what the baseline of the ordering operation will be. ListForoftheFiguresCar type, the internal ID seems to be the most logical candidate:
List of Tables
//The iteration of the Car can be ordered
//based on the CarID.
public class Car : IComparable
{
...
// IComparable implementation.
int IComparable.CompareTo(object o)
{
Car temp = (Car)o; if(this.CarID > temp.CarID)
return 1; if(this.CarID < temp.CarID)
return -1;
else
return 0;
}
C# and the .NET Platform, Second Edition
}
by Andrew Troelsen |
ISBN:1590590554 |
Apress © 2003 (1200 pages)
As you can see, theThislogiccomprehensivebehind CompareTo()text starts withis toatestbrieftheoverviewincomingof typehe against the current instance. The return valueC#of CompareTo()langu ge and thenis usedquicklyto discovermoves toif thiskeytypetechnicalis lessandthan, greater than, or equal to the
architectural issues for .NET developers. object it is being compared with (Table 6-1).
Table 6-1: CompareTo() Return Values
Table of Contents |
|
|
|
|
C#CompareTo()and the .NET Platform,ReturnSecondValueEdition |
|
Meaning in Life |
|
|
|
|
|
|
|
|
Introduction |
|
This instance is less than object. |
|
|
Any number less than zero |
|
|
|
Part One - Introducing C# and the .NET Platform |
|
|
|
|
|
|
|
||
|
Chapter 1 - The Philosophy of .NET |
|
This instance is equal to object. |
|
|
Zero |
|
|
|
|
|
|
|
|
|
Chapter 2 - Building C# Applications |
|
This instance is greater than object. |
|
|
Any number greater than zero |
|
|
|
Part Two - The C# Programming Language |
|
|
|
|
|
|
|
||
|
|
|
|
|
Chapter 3 - C# Language Fundamentals
Now that your Car type understands how to compare itself to like objects, you can write the following user
Chapter 4 - Object-Oriented Programming with C# code:
Chapter 5 - Exceptions and Object Lifetime Chapter 6 - Interfaces and Collections
// Exercise the IComparable interface.
Chapter 7 - Callback Interfaces, Delegates, and Events
public class CarApp
Chapter 8 - Advanced C# Type Construction Techniques
{
Part Three - Programming with .NET Assemblies
public static int Main(string[] args)
Chapter 9 |
- Understanding .NET Assemblies |
|
|
{ |
- Processes, AppDomains, Contexts, and Threads |
||
Chapter 10 |
|||
Chapter 11 |
|
// Make an array of Car types. |
|
- Type Reflection, Late Binding, and Attribute-Based Programming |
|||
|
|
Car[] myAutos = new Car[5]; |
|
Part Four - Leveraging the .NET Libraries |
|
||
|
|
myAutos[0] = new Car(123, "Rusty"); |
|
Chapter 12 |
- Object Serialization and the .NET Remoting Layer |
||
|
|
myAutos[1] = new Car(6, "Mary"); |
|
Chapter 13 |
- Building a Better Window (Introducing Windows Forms) |
||
|
|
myAutos[2] = new Car(83, "Viper"); |
|
Chapter 14 |
- A Better Painting Framework (GDI+) |
|
|
|
|
myAutos[3] = new Car(13, "NoName"); |
|
Chapter 15 |
- Programming with Windows Forms Controls |
||
|
|
myAutos[4] = new Car(9873, "Chucky"); |
|
Chapter 16 |
- The System.IO Namespace |
|
|
|
|
// Dump current array. |
is the unordered set of cars:"); |
Chapter 17 |
- DataConsoleAccess.withWriteLine("HereADO.NET |
||
Part Five - Webforeach(CarApplications andcXMLinWebmyAutos)Services |
|||
Chapter 18 |
- ASP.NET ConsoleWeb Pag s.WriteLine("{0}band Controls {1}", c.ID, c.PetName); |
||
Chapter 19 |
- ASP.NET// Now,WebsortApplicathemions using IComparable! |
||
Chapter 20 |
- XMLArray.Sort(myAutos);Web Services |
|
|
Index |
|
// Dump sorted array. |
|
List of Figures |
Console.WriteLine("Here is the ordered set of cars:"); |
||
List of Tables |
foreach(Car c in myAutos) |
Console.WriteLine("{0} {1}", c.ID, c.PetName); return 0;
}
}
Figure 6-9 illustrates a test run.
Second Edition
ISBN:1590590554
with a brief overview of the
moves to key technical and
developers.
Figure 6-9: Comparing automobiles based on car ID
Table of Contents
C# and the .NET Platform, Second Edition
As a side note, if multiple items in the Car array have the same value assigned to the ID member variable,
Introduction
the sort simply lists them according to their occurrence in the sort (notice in Figure 6-9 there are three cars
Part One - Introducing C# and the .NET Platform
with the ID of 6).
Chapter 1 - The Philosophy of .NET
Chapter 2 - Building C# Applications
Specifying Multiple Sort Orders (IComparer)
Part Two - The C# Programming Language
Chapter 3 - C# Language Fundamentals
In this version of the Car type, you made use of the underlying ID to function as the baseline of the sort
Chapter 4 - Object-Oriented Programming with C#
order. Another design might have used the pet name of the car as the basis of the sorting algorithm (to list
Chapter 5 - Exceptions and Object Lifetime
cars alphabetically). Now, what if you wanted to build a Car that could be sorted by ID as well as by pet
Chapter 6 - Interfaces and Collections
name? If this is the behavior you are interested in, you need to make friends with another standard
Chapter 7 - Callback Interfaces, Delegates, and Events
interface named IComparer, defined within the System.Collections namespace as follows:
Chapter 8 - Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
// A generic way to compare two objects.
Chapter 9 - Understanding .NET Assemblies interfaceIComparer
Chapter 10 - Processes, AppDomains, Contexts, and Threads
{
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
int Compare(object o1, object o2);
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+)
Unlike the IComparable interface, IComparer is typically not implemented on the type you are trying to sort
Chapter 15 - Programming with Windows Forms Controls
(i.e., the Car). Rather, you implement this interface on any number of helper objects, one for each sort
Chapter 16 - The System.IO Namespace
order (pet name, ID, etc.). Currently, the Car type already knows how to compare itself against other cars
Chapter 17 - Data Access with ADO.NET
based on the internal car ID. Therefore, to allow the object user to sort an array of Car types by pet name
Part Five - Web Applications and XML Web Services
will require an additional helper class that implements IComparer. Here's the code:
Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications
// This helper class is used to sort an array of Cars by pet name.
Chapter 20 - XML Web Services
using System.Collections;
Index
public class SortByPetName : IComparer
List of Figures
{
List of Tables
public SortByPetName(){ }
// Test the pet name of each object.
int IComparer.Compare(object o1, object o2)
{
Car |
t1 |
= |
(Car)o1; |
Car |
t2 |
= |
(Car)o2; |
return |
String.Compare(t1.PetName, t2.PetName); |
}
}
The object user code is able to make use of this helper class. System.Array has a number of overloaded Sort() methods, one that just happens to take an object implementing IComparer (Figure 6-10):
// Now sort by pet name.
Array.Sort(myAutos,new SortByPetName());
C# and the .NET Platform, Second Edition
// Dump sorted array.
by Andrew Troelsen |
ISBN:1590590554 |
Console.WriteLine("Ordering by pet name:"); |
|
Apress © 2003 (1200 pages) |
|
foreach(Car c in myAutos) |
|
This comprehensive text starts with a brief overview of the
Console.WriteLine("{0} {1}", c.ID, c.PetName);
C# language and then quickly moves to key technical and architectural issues for .NET developers.
Table
C# and
Part
Chapter
Chapter
Part
Chapter |
|
Chapter |
C# |
Chapter |
|
Chapter 6 - Interfaces and Collections
Figure 6-10: Sorting automobiles by pet name
Chapter 7 - Callback Interfaces, Delegates, and Events
Chapter 8 - Advanced C# Type Construction Techniques
Part Three - ProgProperties,amming with .NETCustomA semblies
Custom Sort Types
Chapter 9 - Understanding .NET Assemblies
ChapterIt is worth10 pointing- Processes,out thatAppDyoumains,can makeContextuse, andof aThreadscustom static property in order to help the object user
Chapteralong when11 - TypesortingReflection,your CarLatetypesBinding,by petanamed Attribute. Assume-BasedtheProgrammingCar class has added a static read-only
PapropertyFour -namedLev ragingSortByPetName()the .NET Librariesthat returns the correct IComparer interface:
Chapter 12 - Object Serialization and the .NET Remoting Layer
Chapter 13 - Building a Better Window (Introducing Windows Forms)
// We now support a custom property to return
Chapter 14correct- A B tter PaintingIComparerF amework (GDI+)
// the interface.
Chapterpublic15class- ProgrammingCar : withIComparableWindows Forms Controls
Chapter{ 16 - The System.IO Namespace
Chapter ...17 - Data Access with ADO.NET
Part Five//- WebPropertyApplicationsto andreturnXML WebtheServicesSortByPetName comparer.
public static IComparer SortByPetName
Chapter 18 - ASP.NET Web Pages and Web Con rols
{ get { return (IComparer)new SortByPetName(); } }
Chapter 19 - ASP.NET Web Applications
}
Chapter 20 - XML Web Services
Index
List of Figures
The object user code can now be modified as follows:
List of Tables
//This was a bit cumbersome.
//Array.Sort(myAutos, new SortByPetName());
//Cleaner! Just ask the car for the correct sort object.
Array.Sort(myAutos,Car.SortByPetName);
SOURCE The ObjComp project is located under the Chapter 6 subdirectory.
CODE
Exploring theC# andSystemthe .NET.CollectionsPlatform, SecondNamespaceEdition
by Andrew Troelsen |
ISBN:1590590554 |
The most primitive C# collection construct is System.Array. As you have already seen in Chapter 3, this
Apress © 2003 (1200 pages)
class does provide quite a number of member functions that encapsulate a number of interesting services
This comprehensive text starts with a brief overview of the
(e.g., reversing, sorting,C# languagecloning,andandthenenumerating)quickly moves. Intoakeysimilartechnicalvein, thisand chapter has also shown you how to build custom typesarchitecturalwith manyissuesof thefor same.NET developersservices using. standard interfaces. To round out your appreciation of the various .NET interfaces, the final order of business is to investigate the various types defined within the System.Collections namespace.
Table of Contents
C# and the .NET Platform, Second Edition
The Interfaces of System.Collections
Introduction
Part One - Introducing C# and the .NET Platform |
||||||||||
|
First of all, System.Collections defines a number of standard interfaces (many of which you have already |
|||||||||
Chapter 1 |
- The Philosophy of .NET |
|
|
|
|
|||||
|
implemented during the course of this chapter). Most of the classes defined within the System.Collections |
|||||||||
Chapter 2 |
- Building C# Applications |
|
|
|
|
|||||
|
namespace implement these interfaces to provide access to their contents. Table 6-2 gives a breakdown |
|||||||||
Part Two - The C# Programming Language |
||||||||||
|
of the core collectioncentric interfaces. |
|
|
|
|
|||||
Chapter 3 |
- C# Language Fundamentals |
|
|
|
|
|||||
Ch pter 4 |
- Object-Oriented Programming with C# |
|||||||||
|
Table 6-2: Interfaces of System.Collections |
|||||||||
|
|
|
|
|
|
|
|
|
|
|
|
|
Chapter 5 |
- Exceptions and Object Lifetime |
|
|
|
||||
|
|
ChapterSystem.Collections6 - Interfaces and Collections |
Meaning in Life |
|
|
|
||||
|
|
ChapterInterface7 - Callback Interfaces, Delegates, and Events |
|
|
|
|||||
|
|
|
|
|||||||
|
|
|
|
|
|
|
|
|
|
|
|
|
Chapter 8 |
- Advanced C# Type Construction T chniques |
|
|
|
||||
|
|
ICollection |
Defines generic characteristics (e.g., read-only, thread safe, |
|
|
|
||||
Part Three - Programming with .NET Assemblies |
|
|
|
|||||||
|
|
|
|
|
|
|
etc.) for a collection class |
|
|
|
|
|
|
|
|
|
|
|
|||
|
|
Chapter 9 |
- Understanding .NET Assemblies |
|
|
|
||||
|
|
IComparer |
Allows two objects to be compared |
|
|
|
||||
|
|
Chapter 10 |
- Processes, AppDomains, |
|
Contexts, and Threads |
|
|
|
||
|
|
|
|
|
|
|
|
|
|
|
|
|
Chapter 11 |
- Type Reflection, Late Binding, |
and Attribute-Based Programming |
|
|
|
|||
|
|
IDictionary |
Allows an object to represent its contents using name/value |
|
|
|
||||
Part Four - Leveraging the .NET Libraries |
pairs |
|
|
|
||||||
|
|
|
|
|
|
|
|
|
|
|
|
|
Chapter 12 |
- Object Serialization and the |
|
|
.NET Remoting Layer |
|
|
||
|
|
IDictionaryEnumerator |
|
|
|
Used to enumerate the contents of an object supporting |
|
|
|
|
|
Chapter 13 |
- Building a Better Window |
|
|
|
(Introducing Windows Forms) |
|
|
|
|
|
|
|
|
|
|
|
IDictionary |
|
|
|
|
|
Chapter 14 |
- A Better Painting Framework |
|
|
|
(GDI+) |
|
|
|
|
|
|
|
|
|
|
|
|||
|
ChapterIEnumerable15 - Programming with Windows |
|
|
|
ReturnsForms Controlsthe IEnumerator interface for a given object |
|
|
|
||
|
|
|
|
|
|
|||||
|
|
Chapter 16 |
- The System.IO Namespace |
|
|
|
Generally used to support foreach-style iteration of subtypes |
|
|
|
|
|
IEnumerator |
|
|
|
|
|
|
||
|
Chapter 17 |
- Data Access with ADO.NET |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
||
PartIHashCodeProviderFive - W b Applications and XML WebReturnsServicesthe hash code for the implementing type using a |
|
|
|
|||||||
Chapter 18 |
- ASP.NET Web Pages and WebcustomizedControls hash algorithm |
|
|
|
||||||
|
|
|
|
|
|
|
|
|
|
|
|
|
Chapter 19 |
- ASP.NET Web Applications |
|
|
|
Provides behavior to add, remove, and index items in a list |
|
|
|
|
|
IList |
- XML Web Services |
|
|
|
|
|
|
|
|
Chapter 20 |
|
|
|
of objects |
|
|
|
||
|
|
|
|
|
|
|
|
|
|
|
|
Index |
|
|
|
|
|
|
|
|
|
List of Figures |
|
|
|
|
ListAsofyouTablesmay suspect, many of these interfaces are related by an interface hierarchy, while others are stand-alone entities. Figure 6-11 illustrates the relationship between each type (recall that it is permissible for a single interface to derive from multiple interfaces).
Figure 6-11: The System.Collections interface hierarchy
As you have already seen the behavior provided by IComparer, IEnumerable, and IEnumerator firsthand
C# and the .NET Platform, Second Edition
during this chapter, let's check out the remainder of these key interfaces of the System.Collections
by Andrew Troelsen ISBN:1590590554 namespace, and then turn our attention to select class types.
Apress © 2003 (1200 pages)
The Role of ICollectionThis comprehensive text starts with a brief overview of the
C# language and then quickly moves to key technical and
architectural issues for .NET developers.
The ICollection interface is the most primitive interface of the System.Collections namespace in that it defines a behavior supported by a collection type. In a nutshell, this interface provides a small set of
properties that allow you to determine (a) the number of items in the container, (b) the thread-safety of the
Table of Contents
container, as well as (c) the ability to copy the contents into a System.Array type. Formally, ICollection is
C# and the .NET Platform, Second Edition
defined as follows (again note that ICollection extends IEnumerable):
Introduction
Part One - Introducing C# and the .NET Platform
public interface ICollection : IEnumerable
Chapter 1 - The Philosophy of .NET
{
Chapter 2 - Building C# Applications
// IEnumerable member...
Part Two - The C# Programming Language
int Count { get; }
Chapter 3 - C# Language Fundamentals bool IsSynchronized { get; }
Chapter 4 - Object-Oriented Programming with C# object SyncRoot { get; }
Chapter 5 - Exceptions and Object Lifetime
void CopyTo(Array array, int index);
Chapter 6 - Interfaces and Collections
}
Chapter 7 - Callback Interfaces, Delegates, and Events
Chapter 8 - Advanced C# Type Construction Techniques
PartTheThreeRole- ProfgrammingIDictionarywith .NET Assemblies
Chapter 9 - Understanding .NET Assemblies
IDictionary is a fairly simple interface, in that much of its functionality is obtained by its base interfaces
Chapter 10 - Processes, AppDomains, Contexts, and Threads
ICollection and IEnumerable. Here is the formal definition:
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Part Four - Leveraging the .NET Libraries
public interface IDictionary :
Chapter 12 - Object Serialization and the .NET Remoting Layer
ICollection, IEnumerable
Chapter 13 - Building a Better Window (Introducing Windows Forms)
{
Chapter 14 - A Better Painting Framework (GDI+)
// ICollection and IEnumerable members...
Chapter 15 - Programming with Windows Forms Controls
bool IsFixedSize { get; }
Chapter 16 - The System.IO Namespace
bool IsReadOnly { get; }
Chapter 17 - Data Access with ADO.NET
object this[ object key ] { get; set; }
Part Five - Web Applications and XML Web Services
ICollection Keys { get; }
Chapter 18 - ASP.NET Web Pages and Web Controls
ICollection Values { get; }
Chapter 19 - ASP.NET Web Applications
void Add(object key, object value);
Chapter 20 - XML Web Services void Clear();
Index bool Contains(object key);
List of Figures
IDictionaryEnumerator GetEnumerator();
List of Tables
void Remove(object key);
}
As you may already be aware, a dictionary is simply a collection that maintains a set of name/value pairs. For example, you could build a custom type that implements IDictionary such that you can store Car types (the values) that may be retrieved by ID or pet name (e.g., names). Given this functionality, you can see that the IDictionary interface defines a Keys and Values property as well as Add(), Remove(), and Contains() methods. The individual items may be obtained by the type indexer.
The Role of IDictionaryEnumerator
If you were paying attention, you may have noted that IDictionary.GetEnumerator() returns an instance of the IDictionaryEnumerator type. As you may be expecting, IDictionaryEnumerator is simply a strongly typed enumerator, given that it extends IEnumerator by adding the following functionality:
public interface IDictionaryEnumerator : IEnumerator
C# and the .NET Platform, Second Edition
{
by Andrew Troelsen ISBN:1590590554
// IEnumerator methods...
Apress © 2003 (1200 pages)
DictionaryEntry Entry { get; }
This comprehensive text starts with a brief overview of the
object Key { get; }
C# language and then quickly moves to key technical and
object Value { get; }
archit ctural issues for .NET developers.
}
Table of Contents
Notice how IDictionaryEnumerator allows you to enumerate over items in the dictionary via the generic
C# and the .NET Platform, Second Edition
Entry property, which returns a System.Collections.DictionaryEntry class type. In addition, you are also
Introduction
able to traverse the name/value pairs using the Key/Value properties.
Part One - Introducing C# and the .NET Platform
Chapter 1 - The Philosophy of .NET
The Role of IHashCodeProvider
Chapter 2 - Building C# Applications
Part Two - The C# Programming Language
IHashCodeProvider is a very simple interface defining only one member:
Chapter 3 - C# Language Fundamentals
Chapter 4 - Object-Oriented Programming with C# public interface IHashCodeProvider
Chapter 5 - Exceptions and Object Lifetime
{
Chapter 6 - Interfaces and Collections
int GetHashCode(object obj);
Chapter 7 - Callback Interfaces, Delegates, and Events
}
Chapter 8 - Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
ChaTypester that9 -implementUnd rstandingthis .interfaceNET Assembliesprovide the ability to retrieve the hash code for a particular type (which
may or may not leverage the type's implementation of System.Object.GetHashCode()).
Chapter 10 - Process s, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
The Role of IList
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
The final key interface of System.Collections is IList, which provides the ability to insert, remove, and index
Chapter 13 - Building a Better Window (Introducing Windows Forms) items into (or out of) a container:
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls public interface IList :
Chapter 16 - The System.IO Namespace
ICollection, IEnumerable
Chapter 17 - Data Access with ADO.NET
{
Part Five - Web Applications and XML Web Services
bool IsFixedSize { get; }
Chapter 18 - ASP.NET Web Pages and Web Controls bool IsReadOnly { get; }
Chapter 19 - ASP.NET Web Applications
object this[ int index ] { get; set; }
Chapter 20 - XML Web Services
int Add(object value); Index void Clear();
List of Figures
bool Contains(object value);
List of Tablesint IndexOf(object value);
void Insert(int index, object value); void Remove(object value);
void RemoveAt(int index);
}
The Class Types of System.Collections
Now that you understand the basic functionality provided by each interface, Table 6-3 provides a rundown of the core collection classes, including a list of implemented interfaces.
Table 6-3: Classes of System.Collections
System.CollectionsC# and the .NETMeaningPlatform,inSecondLife Edition
|
Class |
|
by Andrew Troelsen |
ISBN:1590590554 |
|||
|
|
|
Apress © 2003 (1200 pages) |
|
|||
|
|
|
|
|
|
|
|
|
ArrayList |
|
This comprehensive text starts with a brief overview of the |
||||
|
|
|
|
|
A dynamically sized array of objects. |
||
|
|
|
C# language and then quickly moves to key technical and |
||||
|
|
|
architectural issues for .NET developers. |
|
|||
|
|
|
|
|
|
||
|
|
|
|
|
|
||
|
Hashtable |
|
|
|
Represents a collection of objects identified |
||
Table of Contents |
|
|
|
by a numerical key. Types stored in a |
|||
C# and the .NET Platform, Second |
|
||||||
|
Edition |
|
|||||
Introduction |
|
|
|
Hashtable should always override |
|||
|
|
|
System.Object.GetHashCode(). |
||||
|
|
|
|
|
|
||
Part One - Introducing C# and the .NET Platform |
|
||||||
|
|||||||
ChapterQueue1 |
- The Philosophy of .NETRepresents a standard first-in-first-out |
||||||
Chapter 2 - Building C# Applications(FIFO) queue. |
|
||||||
Part Two - The C# Programming |
|
Language |
|
||||
|
|
|
|
|
|
||
|
Chapter 3 - C# Language Fundamentals |
|
|||||
|
SortedList |
|
|
|
Like a dictionary; however, the elements can |
||
|
Chapter 4 |
- Object-Oriented Programming with C# |
|
||||
|
|
|
|
|
|
also be accessed by ordinal position (e.g., |
|
|
Chapter 5 - Exceptions and Object Lifetime |
|
|||||
|
|
|
|
|
|
index). |
|
|
Chapter 6 - Interfaces and Collections |
|
|||||
|
|
|
|
|
|
||
Chapter 7 - Callback Interfaces, |
Delegates, and Events |
|
|||||
|
Stack |
|
|
|
|
A last-in, first-out (LIFO) queue providing |
|
Chapter 8 |
- Advanced C# Type Construction Techniques |
|
|||||
|
|
|
|
|
|
push, pop (and peek) functionality. |
Part Three - Programming with .NET Assemblies
Key
Implemented
Interfaces
IList, ICollection,
IEnumerable, and
ICloneable
IDictionary,
ICollection,
IEnumerable, and
ICloneable
ICollection,
ICloneable, and
IEnumerable
IDictionary,
ICollection,
IEnumerable, and
ICloneable
ICollection and
IEnumerable
Chapter 9 - Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
In addition to these key types, System.Collections defines some minor players (at least in terms of their
Chdaypter 11 - Type Reflection, Laste Binding, and Attribute-Based Programming
-to-day usefulness) such BitArray, CaseInsensitiveComparer, and PartCaseInsensitiveHashCodeProviderFour - Leveraging the .NET L braries. Furthermore, this namespace also defines a small set of abstract
Chbasepterclasses12 - Object(CollectionBase,Serialization ReadOnlyCollectionBase,and the .NET moting Layerand DictionaryBase) that can be used to build
Chapterstrongly13typed- Buildicontainersg Better. Window (Introducing Windows Forms)
Chapter 14 - A Better Painting Framework (GDI+)
As you begin to experiment with the System.Collections types, you will find they all tend to share common
Chapter 15 - Programming with Windows Forms Controls
functionality (that's the point of interface-based programming). Thus, rather than listing out the members
Chapter 16 - The System.IO Namespace
of each and every collection class, the next task of this chapter is to illustrate how to interact with three common collection types: ArrayList, Queue, and Stack. Once you understand the functionality of these types, gaining an understanding of the remaining collection classes should naturally follow (especially
since each of the types is fully documented within online help).
Chapter 19 - ASP.NET Web Applications
Chapter 20 - XML Web Services
Working with the ArrayList Type
Index
ListTheofArrayListFigures type is bound to be your most frequently used collection type in that it allows you to Listdynamicallyof Tables resize the contents at your whim (in stark contrast to a simple System.Array type). To illustrate the basics of this type, ponder the following code:
// Create ArrayList and fill with some initial values.
ArrayList carArList = new ArrayList(); carArList.AddRange(new Car[] { new Car("Fred", 90, 10),
new Car("Mary", 100, 50), new Car("MB", 190, 0)}); Console.WriteLine("Items in carArList: {0}", carArList.Count);
// Print out current values.
foreach(Car c in carArList)
{ Console.WriteLine("Car pet name: {0}", c.PetName); }
// Insert a new item.
carArList.Insert(2, new Car("TheNewCar", 0, 0)); Console.WriteLine("Items in carArList: {0}", carArList.Count);
// Get object array from ArrayList and print again.
object[] arrayOfCars = carArList.ToArray();
for(int i = 0; i < arrayOfCars.Length; i++)
C# and the .NET Platform, Second Edition
{
by Andrew Troelsen |
ISBN:1590590554 |
Console.WriteLine("Car pet name: {0}", |
|
Apress © 2003 (1200 pages) |
|
((Car)arrayOfCars[i]).PetName); |
|
}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.
Here you are making use of the AddRange() method to populate your ArrayList with a set of Car types (as
you can tell, this is basically a shorthand notation for calling Add() n number of times). Once you print out
Table of Contents
the number of items in the collection (as well as enumerate over each item to obtain the pet name), check
C# and the .NET Platform, Second Edition
out the call to Insert(). As you can see, Insert() allows you to plug a new item into the ArrayList at a
Introduction
specified index. Next, notice the call to the ToArray() method, which returns a generic array of
Part One - Introducing C# and the .NET Platform
System.Object types based on the contents of the original ArrayList. Figure 6-12 shows the output.
Chapter 1 - The Philosophy of .NET
Chapter 2 - Building C# Applications
Part
Chapter
Chapter
Chapter
Chapter
Chapter
Chapter
Part
Chapter |
|
Chapter |
|
Chapter |
Programming |
Part |
|
ChapterFigure12 - 6Object-12: FunSerializationwith System.Collections.ArrayListand the .NET Remoting Layer |
|
Chapter 13 - Building a Better Window (Introducing Windows Forms)
Chapter 14 - A Better Painting Framework (GDI+)
Working with the Queue Type
Chapter 15 - Programming with Windows Forms Controls
Chapter 16 - The System.IO Namespace
Queues are containers that ensure that items are accessed using a first-in, first-out manner. Sadly, we
Chumansapter 17are- DatasubjectA cessto queueswith ADOall.NETday long: lines at the bank, lines at the movie theater, and lines at the
PartmorningFive -coffeeWeb Applicationshouse. Whena dyouXMLareWebmodelingServicesa scenario in which items are handled on a first-come,
|
first-served basis, System.Collections.Queue is your type of choice. In addition to the functionality provided |
|||||
Chapter 18 - ASP.NET W b Pages and Web Controls |
||||||
Chapterby the supported19 - ASP.NETinterfaces,Web ApplicationsQueue defines the key members shown in Table 6-4. |
||||||
Chapter 20 - XML Web Services |
|
|
|
|
||
IndexTable 6-4: Members of the Queue Type |
|
|
|
|
||
|
|
|
|
|
|
|
List of Figures |
|
Meaning in Life |
|
|
||
|
|
Member of |
|
|
|
|
List of Tables |
|
|
|
|
||
|
|
System.Collection.Queue |
|
|
|
|
|
|
|
|
|
|
|
|
|
Dequeue() |
|
Removes and returns the object at the beginning of |
|
|
|
|
|
|
the Queue |
|
|
|
|
|
|
|
|
|
|
|
Enqueue() |
|
Adds an object to the end of the Queue |
|
|
|
|
|
|
|
|
|
|
|
Peek() |
|
Returns the object at the beginning of the Queue |
|
|
|
|
|
|
without removing it |
|
|
|
|
|
|
|
|
|
To illustrate these methods, we will leverage our automobile theme once again and build a Queue object that simulates a line of cars waiting to enter a car wash. First, assume the following static helper method:
public static void WashCar(Car c)
{
Console.WriteLine("Cleaning {0}", c.PetName);
}
C# and the .NET Platform, Second Edition
Now, ponder thebyfollowingAndrewcode:Troelsen |
ISBN:1590590554 |
Apress © 2003 (1200 pages)
// Make a Q withThis compthreehensiveitemstext. starts with a brief overview of the
C# language and then quickly moves to key technical and
Queue carWashQ = new Queue();
architectural issues for .NET developers. carWashQ.Enqueue(new Car("FirstCar", 0, 0));
carWashQ.Enqueue(new Car("SecondCar", 0, 0));
carWashQ.Enqueue(new Car("ThirdCar", 0, 0));
Table of Contents
// Peek at first car in Q.
C# and the .NET Platform, Second Edition
Console.WriteLine("First in Q is {0}",
Introduction
((Car)carWashQ.Peek()).PetName);
Part One - Introducing C# and the .NET Platform
// Remove each item from Q.
Chapter 1 - The Philosophy of .NET
WashCar((Car)carWashQ.Dequeue());
Chapter 2 - Building C# Applications
WashCar((Car)carWashQ.Dequeue());
Part Two - The C# Programming Language
WashCar((Car)carWashQ.Dequeue());
Chapter 3 - C# Language Fundamentals
// Try to de-Q again?
Chapter 4 - Object-Oriented Programming with C# try
Chapter 5 - Exceptions and Object Lifetime
{
Chapter WashCar((Car)carWashQ6 - Inte faces and Collections.Dequeue());
Chapter} 7 - Callback Interfaces, Delegates, and Events
Chcatch(Exceptionpter 8 - Advanced C#e) Type Construction Techniques
Part{ ConsoleThree - Prog.WriteLine("Error!!amming with .NET Assemblies{0}", e.Message);}
Chapter 9 - Understanding .NET Assemblies
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Here, you insert three items into the Queue type via its Enqueue() method. The call to Peek() allows you to view (but not remove) the first item currently in the Queue, which in this case is the car named FirstCar. Finally, the called to Dequeue() removes the item off the line and sends it into the WashCar() helper
function for processing. Do note that if you attempt to remove items from an empty queue, a runtime
Chapter 13 - Building a Better Window (Introducing Windows Forms) exception is thrown. Figure 6-13 shows the output of the queue example.
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
Chapter
Chapter
Part
Chapter
Chapter
Chapter
Index
List of
List of Tables
Figure 6-13: System.Collections.Queue at work
Working with the Stack Type
The System.Collections.Stack type represents a collection that maintains items using a last-in, first-out manner. As you would expect, Stack defines a member named Push() and Pop() (to place items onto or remove items from the stack), as well as a Peek() method. Due to the fact that I am hard-pressed to come up with a car-centric stack example (perhaps a junkyard automobile crusher?), the following stack example makes use of the standard System.String:
Stack stringStack = new Stack();
stringStack.Push("One");
stringStack.Push("Two");
stringStack.Push("Three");
// Now look at the top item, pop it and look again.
Console.WriteLine("Top item is: {0}", stringStack.Peek());
C# and the .NET Platform, Second Edition
Console.WriteLine("Popped off {0}", stringStack.Pop());
by Andrew Troelsen ISBN:1590590554
Console.WriteLine("Top item is: {0}", stringStack.Peek());
Apress © 2003 (1200 pages)
Console.WriteLine("Popped off {0}", stringStack.Pop());
WriteLine("TopTh s comprehensiveitemtext starts with a brief overview of the
Console. is: {0}", stringStack.Peek());
C# language and then quickly moves to key technical and
Console.WriteLine("Popped off {0}", stringStack.Pop()); architectural issues for .NET developers.
try
{
Console.WriteLine("Top item is: {0}", stringStack.Peek());
Table of Contents
Console.WriteLine("Popped off {0}", stringStack.Pop());
C# and the .NET Platform, Second Edition
}
Introduction catch(Exception e)
Part One - Introducing C# and the .NET Platform
{ Console.WriteLine("Error!! {0}", e.Message);}
Chapter 1 - The Philosophy of .NET
Chapter 2 - Building C# Applications
PartHere,Twoyou- ThebuildC#aProgrammingstack that containsLanguagethree string types (named according to their order of insertion). As Chapteryou peek3 onto- C#theLanguagestack, youFundamentalswill always see the item at the very top, and therefore the first call to Peek()
Chapterreveals4the- thirdObjectstring-Oriented. AfterProgrammingseries of Pop()with C#and Peek() calls, the stack is eventually empty, at which
Chaptertime additional5 - ExceptionsPeek()/Pop()and ObjectcallsLifetimeraise a system exception. The output can be seen in Figure 6-14.
Chapter 6 - Interfaces and Collections |
|
Chapter |
Events |
Chapter |
|
Part |
|
Chapter |
|
Chapter |
Threads |
Chapter |
-Based Programming |
Part |
|
Chapter |
Layer |
Chapter |
Windows Forms) |
Chapter |
|
Chapter |
Controls |
Chapter
Figure 6-14: System.Collections.Stack type at work
Chapter 17 - Data Access with ADO.NET
Part Five - Web Applications and XML Web Services
Chapter 18 - ASP.NET Web Pages and Web Controls
System.Collections.Specialized Namespace
Chapter 19 - ASP.NET Web Applications
Chapter 20 - XML Web Services
In addition to the types defined within the System.Collections namespace, you should also be aware that
Index
the .NET base class libraries provide the System.Collections.Specialized namespace that defines another
set of types that are more (pardon the redundancy) specialized. For example, the StringDictionary and
List of Tables
ListDictionary types each provide a stylized implementation of the IDictionary interface. Table 6-5 documents the key types.
Table 6-5: Types of the System.Collections.Specialized Namespace
|
|
|
|
|
|
|
Member of |
C# and the .NET Platform, SecondMeaningEd tionin Life |
|
||
|
System.Collections.by Andrew TroSpecializedlsen |
|
ISBN:1590590554 |
|
|
|
|
|
|
|
|
|
CollectionsUtil |
Apress © 2003 (1200 pages) |
|
Creates collections that ignore the case in strings. |
|
|
|
|
|
||
|
|
This comprehensive text starts with a brief overview of the |
|
||
|
|
|
|||
|
|
C# language and then quickly moves to key technical and |
|
||
|
HybridDictionary |
|
Implements IDictionary by using a ListDictionary |
|
|
|
|
architectural issues for .NET developers. |
|
||
|
|
|
|
while the collection is small, and then switching to |
|
|
|
|
|
a Hashtable when the collection gets large. |
|
|
|
|
|
|
|
Table of Contents |
|
|
Implements IDictionary using a singly linked list. |
|
|
|
ListDictionary |
|
|
|
|
C# and the .NET Platform, Second Edition |
|
Recommended for collections that typically |
|
||
Introduction |
|
|
contain 10 items or less. |
|
|
|
|
|
|
|
|
Part One - Introducing C# and the .NET Platform |
|
Provides the abstract (MustInherit in Visual Basic) |
|
||
|
NameObjectCollectionBase |
|
|
||
Chapter 1 - The Philosophy of .NET |
|
base class for a sorted collection of associated |
|
||
Chapter 2 - Building C# Applications |
|
|
|||
|
String keys and Object values that can be |
|
|||
Part Two - The C# Programming Language |
|
|
|||
|
accessed either with the key or with the index. |
|
|||
|
|
|
|
|
|
|
Chapter 3 - C# Language Fundamentals |
|
|
|
|
|
|
|
|
||
|
ChapterNameObjectCollectionBase.4 - Object-Oriented ProgrammingKeysCollectionwith C# |
|
Represents a collection of the String keys of a |
|
|
|
Chapter 5 - Exceptions and Object Lifetime |
|
collection. |
|
|
|
|
|
|
||
|
Chapter 6 - Interfaces and Collections |
|
Represents a sorted collection of associated |
|
|
|
NameValueCollection |
|
|
||
|
Chapter 7 - Callback Interfaces, Delegates, and Events |
|
|||
|
|
|
|
String keys and String values that can be |
|
|
Chapter 8 - Advanced C# Type Construction Techniques |
|
|||
|
|
|
|
accessed either with the key or with the index. |
|
|
|
|
|
|
|
Part Three - Programming with .NET Assemblies |
|
Represents a collection of strings. |
|
||
|
StringCollection |
|
|
||
|
Chapter 9 - Understanding .NET Assemblies |
|
|
|
|
|
|
|
|
||
|
Chapter 10 - Processes, AppDomains, Contexts, and |
|
Threads |
|
|
|
StringDictionary |
|
Implements a hashtable with the key strongly |
|
|
|
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based |
|
|||
|
|
|
|
typed to beProgrammingstring rather than an object. |
|
|
|
|
|
|
|
Part Four - Leveraging the .NET Libraries |
|
Supports a simple iteration over a |
|
||
|
StringEnumerator |
|
|
||
Chapter 12 - Object Serialization and the .NET Remoting Layer |
|
||||
|
|
|
|
StringCollection. |
|
|
Chapter 13 - Building a Better Window (Introducing |
|
Windows Forms) |
|
|
Chapter 14 - A Better Painting Framework (GDI+) |
|
|
|
||
Chapter 15 - Programming with Windows Forms Controls |
|||||
|
SOURCE |
The CollectionTypes project can be found under the Chapter 6 subdirectory. |
ChapterCODE16 - 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
Building a Custom# and the .ContainerNET Pl tform, Second(RetrofittingEdition the Cars Type)
by Andrew Troelsen |
ISBN:1590590554 |
To conclude this chapter, let's examine one possible way to build a stylized custom collection. As
Apress © 2003 (1200 pages)
mentioned, the System.Collections namespace supplies some abstract base types that allow you to build
This comprehensive text starts with a brief overview of the
strongly typed collectionsC# language. However,and thenratherquicklythanmovesdealingto keywithtechnicalthe implementationand of various abstract members, you arearchitablecturalto buildissuescustomfor .collectionsNET developersusing. simple containment/delegation techniques.
Previously in this chapter, you created the Cars type that was responsible for holding a number of Car
Tableobjectsof Conte. Internally,ts the set of Car objects was represented with an instance of System.Array, and because C#of andthis thefact,.NETyouPlatform,needed toSecondwrite aEditigoodn deal of extra code to allow the outside world to interact with your
subobjects. Furthermore, the Car array is defined with a fixed upper limit.
Introduction
Part One - Introducing C# and the .NET Platform
A more intelligent design would be to represent the internal set of Car objects as an instance of System.Collections.ArrayList. Given that this class already has a number of methods to insert, remove, and enumerate its contents, the only duty of the Cars type is to supply a set of public functions that
delegate to the inner ArrayList (in other words, the Cars type "has-a" ArrayList). As with any
Chapter 3 - C# Language Fundamentals
containment/delegation scenario, it is up to you to decide how much functionality of the inner object to
Chapter 4 - Object-Oriented Programming with C#
expose to the object user. Here, then, is one possible implementation of the updated Cars type:
Chapter 5 - Exceptions and Object Lifetime
Chapter 6 - Interfaces and Collections
// This time use an ArrayList, not System.Array.
Chapter 7 - Callback Interfaces, Delegates, and Events public class Cars : IEnumerable
Chapter 8 - Advanced C# Type Construction Techniques
{
Part Three - Programming with .NET Assemblies
// This class maintains an array of cars.
Chapter 9 - Understanding .NET Assemblies private ArrayList carList;
Chapter 10 - Processes, AppDomains, Contexts, and Threads
// Make the ArrayList.
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming public Cars() { carList = new ArrayList ();}
Part Four - Leveraging the .NET Libraries |
|
// Expose select methods of the ArrayList to the outside world. |
|
Chapter 12 - Obj ct |
and the .NET Remoting Layer |
// InsertSerializationcar. |
|
Chapter public13 - Buildingvoida BetterAddCar(CarWindow (Introducingc) Windows Forms)
Chapter {14 -carListA Better Painting.Add(c);}Framework (GDI+)
Chapter //15 -RemoveProgrammingcarwith. Windows Forms Controls
public void RemoveCar(int carToRemove)
Chapter 16 - The System.IO Namespace
{ carList.RemoveAt(carToRemove);}
Chapter 17 - Data Access with ADO.NET
// Return number of cars.
Part Five - Web Applications and XML Web Services
public int CarCount
Chapter 18 - ASP.NET Web Pages and Web Controls
{ get{ return carList.Count;} }
Chapter 19 - ASP.NET Web Applications
// Kill all cars.
Chapter 20 - XML Web Services
public void ClearAllCars()
Index
{carList.Clear(); }
List of Figures
// Determine if the incoming car is already in the list.
List of Tables
public bool CarIsPresent(Car c)
{return carList.Contains(c); }
// Simply return the IEnumerator of the ArrayList.
public IEnumerator GetEnumerator()
{ return carList.GetEnumerator();}
}
This new implementation also makes using the Cars type a bit less of a burden for the object user:
// Use the new Cars container class.
public static void Main()
{
Cars carLot = new Cars();
// Add some cars.
carLot.AddCar(new Car("Jasper", 200, 80));
carLot.AddCar(new Car("Mandy", 140, 0));
C# and the .NET Platform, Second Edition carLot.AddCar(new Car("Porker", 90, 90));
by Andrew Troelsen |
ISBN:1590590554 |
carLot.AddCar(new Car("Jimbo", 40, 4)); |
|
Apress © 2003 (1200 pages)
// Get each one and print out some stats.
This comprehensive text starts with a brief overview of the
Console.WriteLine("You have {0} in the lot:\n", carLot.CarCount);
C# language and then quickly moves to key technical and foreach (Car c in carLot)
architectural issues for .NET developers.
{
Console.WriteLine("Name: {0} ", c.PetName);
Console.WriteLine("Max speed: {0} \n", c.MaxSpeed);
Table of Contents
}
C# and the .NET Platform, Second Edition
// Kill the third car.
Introduction carLot.RemoveCar(3);
Part One - Introducing C# and the .NET Platform
Console.WriteLine("You have {0} in the lot.\n", carLot.CarCount);
Chapter 1 - The Philosophy of .NET
// Add another car and verify it is in the collection.
Chapter 2 - Building C# Applications
Car temp = new Car("Zippy", 90, 90);
Part Two - The C# Programming Language
carLot.AddCar(temp);
Chapter 3 - C# Language Fundamentals
if(carLot.CarIsPresent(temp))
Chapter 4 - Object-Oriented Programming with C#
Console.WriteLine("{0} is already in the lot.", temp.PetName);
Chapter 5 - Exceptions and Object Lifetime
// Kill 'em all.
Chapter carLot6 - In erfacClearAllCars();and Collections
.
Chapter Console7 - Ca lback.WriteLine("YouIn erfaces, Delegates,haveand{0}Eventsin the lot.\n", carLot.CarCount);
Chapter} 8 - Advanced C# Type Construction Techniques
Part Three - Programming with .NET Assemblies
Chapter 9 - Understanding .NET Assemblies
The output is shown in Figure 6-15.
Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Part |
|
Chapter |
NET Remoting Layer |
Chapter |
(Introducing Windows Forms) |
Chapter |
(GDI+) |
Chapter |
Forms Controls |
Chapter |
|
Chapter |
|
Part |
Services |
Chapter |
Controls |
Chapter |
|
Chapter
IndexFigure 6-15: The updated Cars container
List of Figures
ListYouofmayT blesbe wondering why you bothered to make the custom Cars type at all, given that the object user could create an ArrayList type directly. The reason is that ArrayList can contain any object reference. If you did not create a custom wrapper class such as Cars, the ArrayList instance could contain Cars, Boats, Airplanes, Strings, or any other type!
ArrayList ar = new ArrayList();
ar.Add(carLot);
ar.Add("Hello");
ar.Add(new JamesBondCar());
ar.Add(23);
Using the containment/delegation model, you are able to leverage the functionality of the ArrayList type, while maintaining control over what can be inserted into the container.
Note Also beC#awarend thatthe .manyNET Plaof theform,typesSecondof theEditionSystem.Collections namespace can function as base classesby Andrewto derivedTro lsentypes. Thus, as an alternative,ISBN:1590590554you are able to build strongly typed collectionsApressby©deriving2003 (1200frompages)the collection type of interest and overriding various virtual members.
SOURCE |
This comprehensive text starts with a brief overview of the |
can be found under the |
||
C#ThislanguageupdatedandCarsthencollectionquickly moves(ObjectEnumWithCollection)to key technical and |
||||
CODE |
|
Chapter 6 subdirectory. |
|
|
|
architec u al i sues for .NET developers. |
|
||
|
|
|
|
|
This concludes our formal investigation of interface-based programming techniques. Be painfully aware, Tablehowever,of Contentsthat you will encounter numerous .NET interfaces through the remainder of this text. As you will
see, interfaces are used during ASP .NET development, Windows Forms development, multithreaded
C# and the .NET Platform, Second Edition
applications, and so forth. Unlike other development frameworks (such as MFC), interfaces are
Introduction
unavoidable when exploring the .NET universe.
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