You are previewing Programming C# 5.0.

Programming C# 5.0

Cover of Programming C# 5.0 by Ian Griffiths Published by O'Reilly Media, Inc.
  1. Programming C# 5.0
  2. Dedication
  3. SPECIAL OFFER: Upgrade this ebook with O’Reilly
  4. Preface
    1. Who This Book Is For
    2. Conventions Used in This Book
    3. Using Code Examples
    4. Safari® Books Online
    5. How to Contact Us
    6. Acknowledgments
  5. 1. Introducing C#
    1. Why C#?
    2. Why Not C#?
    3. C#’s Defining Features
      1. Managed Code and the CLR
      2. Generality Trumps Specialization
      3. Asynchronous Programming
    4. Visual Studio
    5. Anatomy of a Simple Program
      1. Adding a Project to an Existing Solution
      2. Referencing One Project from Another
      3. Writing a Unit Test
      4. Namespaces
      5. Classes
      6. Program Entry Point
      7. Unit Tests
    6. Summary
  6. 2. Basic Coding in C#
    1. Local Variables
      1. Scope
    2. Statements and Expressions
      1. Statements
      2. Expressions
    3. Comments and Whitespace
    4. Preprocessing Directives
      1. Compilation Symbols
      2. #error and #warning
      3. #line
      4. #pragma
      5. #region and #endregion
    5. Intrinsic Data Types
      1. Numeric Types
      2. Booleans
      3. Strings and Characters
      4. Object
    6. Operators
    7. Flow Control
      1. Boolean Decisions with if Statements
      2. Multiple Choice with switch Statements
      3. Loops: while and do
      4. C-Style for Loops
      5. Collection Iteration with foreach Loops
    8. Summary
  7. 3. Types
    1. Classes
      1. Static Members
      2. Static Classes
      3. Reference Types
    2. Structs
      1. When to Write a Value Type
    3. Members
      1. Fields
      2. Constructors
      3. Methods
      4. Properties
      5. Indexers
      6. Operators
      7. Events
      8. Nested Types
    4. Interfaces
    5. Enums
    6. Other Types
      1. Anonymous Types
    7. Partial Types and Methods
    8. Summary
  8. 4. Generics
    1. Generic Types
    2. Constraints
      1. Type Constraints
      2. Reference Type Constraints
      3. Value Type Constraints
      4. Multiple Constraints
    3. Zero-Like Values
    4. Generic Methods
      1. Type Inference
    5. Inside Generics
    6. Summary
  9. 5. Collections
    1. Arrays
      1. Array Initialization
      2. Variable Argument Count with the params Keyword
      3. Searching and Sorting
      4. Multidimensional Arrays
      5. Copying and Resizing
    2. List<T>
    3. List and Sequence Interfaces
    4. Implementing Lists and Sequences
      1. Iterators
      2. Collection<T>
      3. ReadOnlyCollection<T>
    5. Dictionaries
      1. Sorted Dictionaries
    6. Sets
    7. Queues and Stacks
    8. Linked Lists
    9. Concurrent Collections
    10. Tuples
    11. Summary
  10. 6. Inheritance
    1. Inheritance and Conversions
    2. Interface Inheritance
    3. Generics
      1. Covariance and Contravariance
    4. System.Object
      1. The Ubiquitous Methods of object
    5. Accessibility and Inheritance
    6. Virtual Methods
      1. Abstract Methods
    7. Sealed Methods and Classes
    8. Accessing Base Members
    9. Inheritance and Construction
    10. Special Base Types
    11. Summary
  11. 7. Object Lifetime
    1. Garbage Collection
      1. Determining Reachability
      2. Accidentally Defeating the Garbage Collector
      3. Weak References
      4. Reclaiming Memory
      5. Garbage Collector Modes
      6. Accidentally Defeating Compaction
      7. Forcing Garbage Collections
    2. Destructors and Finalization
      1. Critical Finalizers
    3. IDisposable
      1. Optional Disposal
    4. Boxing
      1. Boxing Nullable<T>
    5. Summary
  12. 8. Exceptions
    1. Exception Sources
      1. Exceptions from APIs
      2. Exceptions from Your Code
      3. Failures Detected by the Runtime
    2. Handling Exceptions
      1. Exception Objects
      2. Multiple catch Blocks
      3. Nested try Blocks
      4. finally Blocks
    3. Throwing Exceptions
      1. Rethrowing Exceptions
      2. Failing Fast
    4. Exception Types
      1. Custom Exceptions
    5. Unhandled Exceptions
      1. Debugging and Exceptions
    6. Asynchronous Exceptions
    7. Summary
  13. 9. Delegates, Lambdas, and Events
    1. Delegate Types
      1. Creating a Delegate
      2. Multicast Delegates
      3. Invoking a Delegate
      4. Common Delegate Types
      5. Type Compatibility
      6. Behind the Syntax
    2. Inline Methods
      1. Captured Variables
      2. Lambdas and Expression Trees
    3. Events
      1. Standard Event Delegate Pattern
      2. Custom Add and Remove Methods
      3. Events and the Garbage Collector
      4. Events Versus Delegates
    4. Delegates Versus Interfaces
    5. Summary
  14. 10. LINQ
    1. Query Expressions
      1. How Query Expressions Expand
      2. Supporting Query Expressions
    2. Deferred Evaluation
    3. LINQ, Generics, and IQueryable<T>
    4. Standard LINQ Operators
      1. Filtering
      2. Select
      3. SelectMany
      4. Ordering
      5. Containment Tests
      6. Specific Items and Subranges
      7. Aggregation
      8. Set Operations
      9. Whole-Sequence, Order-Preserving Operations
      10. Grouping
      11. Joins
      12. Conversion
    5. Sequence Generation
    6. Other LINQ Implementations
      1. Entity Framework
      2. LINQ to SQL
      3. WCF Data Services Client
      4. Parallel LINQ (PLINQ)
      5. LINQ to XML
      6. Reactive Extensions
    7. Summary
  15. 11. Reactive Extensions
    1. Rx and .NET Versions
    2. Fundamental Interfaces
      1. IObserver<T>
      2. IObservable<T>
    3. Publishing and Subscribing with Delegates
      1. Creating an Observable Source with Delegates
      2. Subscribing to an Observable Source with Delegates
    4. Sequence Builders
      1. Empty
      2. Never
      3. Return
      4. Throw
      5. Range
      6. Repeat
      7. Generate
    5. LINQ Queries
      1. Grouping Operators
      2. Join Operators
      3. SelectMany Operator
      4. Aggregation and Other Single-Value Operators
      5. Concat Operator
    6. Rx Query Operators
      1. Merge
      2. Windowing Operators
      3. The Scan Operator
      4. The Amb Operator
      5. DistinctUntilChanged
    7. Schedulers
      1. Specifying Schedulers
      2. Built-in Schedulers
    8. Subjects
      1. Subject<T>
      2. BehaviorSubject<T>
      3. ReplaySubject<T>
      4. AsyncSubject<T>
    9. Adaptation
      1. IEnumerable<T>
      2. .NET Events
      3. Asynchronous APIs
    10. Timed Operations
      1. Interval
      2. Timer
      3. Timestamp
      4. TimeInterval
      5. Throttle
      6. Sample
      7. Timeout
      8. Windowing Operators
      9. Delay
      10. DelaySubscription
    11. Summary
  16. 12. Assemblies
    1. Visual Studio and Assemblies
    2. Anatomy of an Assembly
      1. .NET Metadata
      2. Resources
      3. Multifile Assemblies
      4. Other PE Features
    3. Type Identity
    4. Loading Assemblies
      1. Explicit Loading
      2. The Global Assembly Cache
    5. Assembly Names
      1. Strong Names
      2. Version
      3. Culture
      4. Processor Architecture
    6. Portable Class Libraries
    7. Packaged Deployment
      1. Windows 8 UI–Style Apps
      2. ClickOnce and XBAP
      3. Silverlight and Windows Phone Apps
    8. Protection
    9. Summary
  17. 13. Reflection
    1. Reflection Types
      1. Assembly
      2. Module
      3. MemberInfo
      4. Type and TypeInfo
      5. MethodBase, ConstructorInfo, and MethodInfo
      6. ParameterInfo
      7. FieldInfo
      8. PropertyInfo
      9. EventInfo
    2. Reflection Contexts
    3. Summary
  18. 14. Dynamic Typing
    1. The dynamic Type
    2. dynamic and Interoperability
      1. Silverlight and Scriptable Objects
      2. Dynamic .NET Languages
    3. Inside Dynamic
      1. Restrictions on the dynamic Type
      2. Custom Dynamic Objects
      3. ExpandoObject
    4. Limitations of dynamic
    5. Summary
  19. 15. Attributes
    1. Applying Attributes
      1. Attribute Targets
      2. Compiler-Handled Attributes
      3. CLR-Handled Attributes
    2. Defining and Consuming Custom Attributes
      1. Attribute Type
      2. Retrieving Attributes
    3. Summary
  20. 16. Files and Streams
    1. The Stream Class
      1. Position and Seeking
      2. Flushing
      3. Copying
      4. Length
      5. Disposal
      6. Asynchronous Operation
      7. Concrete Stream Types
    2. Windows 8 and IRandomAccessStream
    3. Text-Oriented Types
      1. TextReader and TextWriter
      2. Concrete Reader and Writer Types
      3. Encoding
    4. Files and Directories
      1. FileStream Class
      2. File Class
      3. Directory Class
      4. Path Class
      5. FileInfo, DirectoryInfo, and FileSystemInfo
      6. Known Folders
    5. Serialization
      1. BinaryReader and BinaryWriter
      2. CLR Serialization
      3. Data Contract Serialization
      4. XmlSerializer
    6. Summary
  21. 17. Multithreading
    1. Threads
      1. Threads, Variables, and Shared State
      2. The Thread Class
      3. The Thread Pool
      4. Thread Affinity and SynchronizationContext
    2. Synchronization
      1. Monitors and the lock Keyword
      2. SpinLock
      3. Reader/Writer Locks
      4. Event Objects
      5. Barrier
      6. CountdownEvent
      7. Semaphores
      8. Mutex
      9. Interlocked
      10. Lazy Initialization
      11. Other Class Library Concurrency Support
    3. Tasks
      1. The Task and Task<T> Classes
      2. Continuations
      3. Schedulers
      4. Error Handling
      5. Custom Threadless Tasks
      6. Parent/Child Relationships
      7. Composite Tasks
    4. Other Asynchronous Patterns
    5. Cancellation
    6. Parallelism
      1. The Parallel Class
      2. Parallel LINQ
      3. TPL Dataflow
    7. Summary
  22. 18. Asynchronous Language Features
    1. Asynchronous Keywords: async and await
      1. Execution and Synchronization Contexts
      2. Multiple Operations and Loops
      3. Returning a Task
      4. Applying async to Nested Methods
    2. The await Pattern
    3. Error Handling
      1. Validating Arguments
      2. Singular and Multiple Exceptions
      3. Concurrent Operations and Missed Exceptions
    4. Summary
  23. 19. XAML
    1. XAML-Based Frameworks
      1. WPF
      2. Silverlight
      3. Windows Phone 7
      4. Windows Runtime and Windows 8 UI–Style Apps
    2. XAML Basics
      1. XAML and XML Namespaces
      2. Generated Classes and Codebehind
      3. Child Elements
      4. Property Elements
      5. Event Handling
      6. Threading
    3. Layout
      1. Properties
      2. Panels
      3. ScrollViewer
      4. Layout Events
    4. Controls
      1. Content Controls
      2. Slider and ScrollBar Controls
      3. Progress Controls
      4. List Controls
      5. Control Templates
      6. UserControls
    5. Text
      1. Displaying Text
      2. Editing Text
    6. Data Binding
      1. Data Templates
    7. Graphics
      1. Shapes
      2. Bitmaps
      3. Media
    8. Styles
    9. Summary
  24. 20. ASP.NET
    1. Razor
      1. Expressions
      2. Flow Control
      3. Code Blocks
      4. Explicitly Indicated Content
      5. Page Classes and Objects
      6. Using Other Components
      7. Layout Pages
      8. Start Pages
    2. Web Forms
      1. Server-Side Controls
      2. Expressions
      3. Code Blocks
      4. Standard Page Objects
      5. Page Classes and Objects
      6. Using Other Components
      7. Master Pages
    3. MVC
      1. Typical MVC Project Layout
      2. Writing Models
      3. Writing Views
      4. Writing Controllers
      5. Handling Additional Input
      6. Generating Action Links
    4. Routing
    5. Summary
  25. 21. Interoperability
    1. Calling Native Code
      1. Marshaling
      2. 32-bit and 64-bit
      3. Safe Handles
      4. Security
    2. Platform Invoke
      1. Calling Convention
      2. Text Handling
      3. Entry Point Name
      4. COM-Style Return Values
      5. Win32 Error Handling
    3. COM
      1. RCW Lifetime
      2. Metadata
      3. Scripting
    4. Windows Runtime
      1. Metadata
      2. Windows Runtime Types
      3. Buffers
    5. Unsafe Code
    6. C++/CLI and the Component Extensions
    7. Summary
  26. Index
  27. About the Author
  28. Colophon
  29. SPECIAL OFFER: Upgrade this ebook with O’Reilly
  30. Copyright
O'Reilly logo

Chapter 5. Collections

Most programs need to deal with multiple pieces of data. Your code might have to iterate through some transactions to calculate the balance of an account, or display recent messages in a social networking web application, or update the positions of characters in a game.

C# offers a simple kind of collection called an array. The CLR’s type system supports arrays intrinsically, so they are efficient, but for some scenarios they can be too basic. Fortunately, the class library builds on the fundamental services provided by arrays to provide more powerful and flexible collection types. I’ll start with arrays, because they are the foundation of most of the collection classes.

Arrays

An array is an object that contains multiple elements of a particular type. Each element is a storage location similar to a field, but whereas with fields we give each storage slot a name, array elements are simply numbered. The number of elements is fixed for the lifetime of the array, so you must specify the size when you create it. Example 5-1 shows the syntax for creating new arrays.

Example 5-1. Creating arrays

int[] numbers = new int[10];
string[] strings = new string[numbers.Length];

As with all objects, we construct an array with the new keyword followed by the type name, but instead of parentheses with constructor arguments, we put square brackets containing the array size. As the example shows, the expression defining the size can be a constant, but it doesn’t have to be—the second ...

The best content for your career. Discover unlimited learning on demand for around $1/day.