O'Reilly logo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

CLR via C#, 3rd Edition

Book Description

Your essential guide to developing applications with the common language runtime (CLR) and Microsoft® .NET Framework 4.0, with examples in Microsoft® Visual C#® 2010.

Table of Contents

  1. CLR via C#
  2. Foreword
  3. Introduction
    1. Who This Book Is For
    2. Dedication
    3. Acknowledgments
    4. Support for This Book
    5. We Want to Hear from You
  4. I. CLR Basics
    1. 1. The CLR's Execution Model
      1. Compiling Source Code into Managed Modules
      2. Combining Managed Modules into Assemblies
      3. Loading the Common Language Runtime
      4. Executing your Assembly's Code
        1. IL and Verification
        2. Unsafe Code
      5. The Native Code Generator Tool: NGen.exe
      6. The Framework Class Library
      7. The Common Type System
      8. The Common Language Specification
      9. Interoperability with Unmanaged Code
    2. 2. Building, Packaging, Deploying, and Administering Applications and Types
      1. .NET Framework Deployment Goals
      2. Building Types into a Module
        1. Response Files
      3. A Brief Look at Metadata
      4. Combining Modules to Form an Assembly
        1. Adding Assemblies to a Project by Using the Visual Studio IDE
        2. Using the Assembly Linker
        3. Adding Resource Files to an Assembly
      5. Assembly Version Resource Information
        1. Version Numbers
      6. Culture
      7. Simple Application Deployment (Privately Deployed Assemblies)
      8. Simple Administrative Control (Configuration)
    3. 3. Shared Assemblies and Strongly Named Assemblies
      1. Two Kinds of Assemblies, Two Kinds of Deployment
      2. Giving an Assembly a Strong Name
      3. The Global Assembly Cache
      4. Building an Assembly That References a Strongly Named Assembly
      5. Strongly Named Assemblies Are Tamper-Resistant
      6. Delayed Signing
      7. Privately Deploying Strongly Named Assemblies
      8. How the Runtime Resolves Type References
      9. Advanced Administrative Control (Configuration)
        1. Publisher Policy Control
  5. II. Designing Types
    1. 4. Type Fundamentals
      1. All Types Are Derived from System.Object
      2. Casting Between Types
        1. Casting with the C# is and as Operators
      3. Namespaces and Assemblies
      4. How Things Relate at Runtime
    2. 5. Primitive, Reference, and Value Types
      1. Programming Language Primitive Types
        1. Checked and Unchecked Primitive Type Operations
      2. Reference Types and Value Types
      3. Boxing and Unboxing Value Types
        1. Changing Fields in a Boxed Value Type by Using Interfaces (and Why You Shouldn't Do This)
        2. Object Equality and Identity
      4. Object Hash Codes
      5. The dynamic Primitive Type
    3. 6. Type and Member Basics
      1. The Different Kinds of Type Members
      2. Type Visibility
        1. Friend Assemblies
      3. Member Accessibility
      4. Static Classes
      5. Partial Classes, Structures, and Interfaces
      6. Components, Polymorphism, and Versioning
        1. How the CLR Calls Virtual Methods, Properties, and Events
        2. Using Type Visibility and Member Accessibility Intelligently
        3. Dealing with Virtual Methods When Versioning Types
    4. 7. Constants and Fields
      1. Constants
      2. Fields
    5. 8. Methods
      1. Instance Constructors and Classes (Reference Types)
      2. Instance Constructors and Structures (Value Types)
      3. Type Constructors
        1. Type Constructor Performance
      4. Operator Overload Methods
        1. Operators and Programming Language Interoperability
      5. Conversion Operator Methods
      6. Extension Methods
        1. Rules and Guidelines
        2. Extending Various Types with Extension Methods
        3. The Extension Attribute
      7. Partial Methods
        1. Rules and Guidelines
    6. 9. Parameters
      1. Optional and Named Parameters
        1. Rules and Guidelines
        2. The DefaultParameterValue and Optional Attributes
      2. Implicitly Typed Local Variables
      3. Passing Parameters by Reference to a Method
      4. Passing a Variable Number of Arguments to a Method
      5. Parameter and Return Type Guidelines
      6. Const-ness
    7. 10. Properties
      1. Parameterless Properties
        1. Automatically Implemented Properties
        2. Defining Properties Intelligently
        3. Object and Collection Initializers
        4. Anonymous Types
        5. The System.Tuple Type
      2. Parameterful Properties
      3. The Performance of Calling Property Accessor Methods
      4. Property Accessor Accessibility
      5. Generic Property Accessor Methods
    8. 11. Events
      1. Designing a Type That Exposes an Event
        1. Step #1: Define a type that will hold any additional information that should be sent to receivers of the event notification
        2. Step #2: Define the event member
        3. Step #3: Define a method responsible for raising the event to notify registered objects that the event has occurred
        4. Step #4: Define a method that translates the input into the desired event
      2. How the Compiler Implements an Event
      3. Designing a Type That Listens for an Event
      4. Explicitly Implementing an Event
    9. 12. Generics
      1. Generics in the Framework Class Library
      2. Wintellect's Power Collections Library
      3. Generics Infrastructure
        1. Open and Closed Types
        2. Generic Types and Inheritance
        3. Generic Type Identity
        4. Code Explosion
      4. Generic Interfaces
      5. Generic Delegates
      6. Delegate and Interface Contravariant and Covariant Generic Type Arguments
      7. Generic Methods
        1. Generic Methods and Type Inference
      8. Generics and Other Members
      9. Verifiability and Constraints
        1. Primary Constraints
        2. Secondary Constraints
        3. Constructor Constraints
        4. Other Verifiability Issues
          1. Casting a Generic Type Variable
          2. Setting a Generic Type Variable to a Default Value
          3. Comparing a Generic Type Variable with null
          4. Comparing Two Generic Type Variables with Each Other
          5. Using Generic Type Variables as Operands
    10. 13. Interfaces
      1. Class and Interface Inheritance
      2. Defining an Interface
      3. Inheriting an Interface
      4. More About Calling Interface Methods
      5. Implicit and Explicit Interface Method Implementations (What's Happening Behind the Scenes)
      6. Generic Interfaces
      7. Generics and Interface Constraints
      8. Implementing Multiple Interfaces That Have the Same Method Name and Signature
      9. Improving Compile-Time Type Safety with Explicit Interface Method Implementations
      10. Be Careful with Explicit Interface Method Implementations
      11. Design: Base Class or Interface?
  6. III. Essential Types
    1. 14. Chars, Strings, and Working with Text
      1. Characters
      2. The System.String Type
        1. Constructing Strings
        2. Strings Are Immutable
        3. Comparing Strings
        4. String Interning
        5. String Pooling
        6. Examining a String's Characters and Text Elements
        7. Other String Operations
      3. Constructing a String Efficiently
        1. Constructing a StringBuilder Object
        2. StringBuilder Members
      4. Obtaining a String Representation of an Object: ToString
        1. Specific Formats and Cultures
        2. Formatting Multiple Objects into a Single String
        3. Providing Your Own Custom Formatter
      5. Parsing a String to Obtain an Object: Parse
      6. Encodings: Converting Between Characters and Bytes
        1. Encoding and Decoding Streams of Characters and Bytes
        2. Base-64 String Encoding and Decoding
      7. Secure Strings
    2. 15. Enumerated Types and Bit Flags
      1. Enumerated Types
      2. Bit Flags
      3. Adding Methods to Enumerated Types
    3. 16. Arrays
      1. Initializing Array Elements
      2. Casting Arrays
      3. All Arrays Are Implicitly Derived from System.Array
      4. All Arrays Implicitly Implement IEnumerable, ICollection, and IList
      5. Passing and Returning Arrays
      6. Creating Non-Zero–Lower Bound Arrays
      7. Array Access Performance
      8. Unsafe Array Access and Fixed-Size Array
    4. 17. Delegates
      1. A First Look at Delegates
      2. Using Delegates to Call Back Static Methods
      3. Using Delegates to Call Back Instance Methods
      4. Demystifying Delegates
      5. Using Delegates to Call Back Many Methods (Chaining)
        1. C#'s Support for Delegate Chains
        2. Having More Control over Delegate Chain Invocation
      6. Enough with the Delegate Definitions Already (Generic Delegates)
      7. C#'s Syntactical Sugar for Delegates
        1. Syntactical Shortcut #1: No Need to Construct a Delegate Object
        2. Syntactical Shortcut #2: No Need to Define a Callback Method
        3. Syntactical Shortcut #3: No Need to Wrap Local Variables in a Class Manually to Pass Them to a Callback Method
      8. Delegates and Reflection
    5. 18. Custom Attributes
      1. Using Custom Attributes
      2. Defining Your Own Attribute Class
      3. Attribute Constructor and Field/Property Data Types
      4. Detecting the Use of a Custom Attribute
      5. Matching Two Attribute Instances Against Each Other
      6. Detecting the Use of a Custom Attribute Without Creating Attribute-Derived Objects
      7. Conditional Attribute Classes
    6. 19. Nullable Value Types
      1. C#'s Support for Nullable Value Types
      2. C#'s Null-Coalescing Operator
      3. The CLR Has Special Support for Nullable Value Types
        1. Boxing Nullable Value Types
        2. Unboxing Nullable Value Types
        3. Calling GetType via a Nullable Value Type
        4. Calling Interface Methods via a Nullable Value Type
  7. IV. Core Facilities
    1. 20. Exceptions and State Management
      1. Defining "Exception"
      2. Exception-Handling Mechanics
        1. The try Block
        2. The catch Block
        3. The finally Block
      3. The System.Exception Class
      4. FCL-Defined Exception Classes
      5. Throwing an Exception
      6. Defining Your Own Exception Class
      7. Trading Reliability for Productivity
      8. Guidelines and Best Practices
        1. Use finally Blocks Liberally
        2. Don't Catch Everything
        3. Recovering Gracefully from an Exception
        4. Backing Out of a Partially Completed Operation When an Unrecoverable Exception Occurs—Maintaining State
        5. Hiding an Implementation Detail to Maintain a "Contract"
      9. Unhandled Exceptions
      10. Debugging Exceptions
      11. Exception-Handling Performance Considerations
      12. Constrained Execution Regions (CERs)
      13. Code Contracts
    2. 21. Automatic Memory Management (Garbage Collection)
      1. Understanding the Basics of Working in a Garbage-Collected Platform
        1. Allocating Resources from the Managed Heap
      2. The Garbage Collection Algorithm
      3. Garbage Collections and Debugging
      4. Using Finalization to Release Native Resources
        1. Guaranteed Finalization Using CriticalFinalizerObject Types
          1. SafeHandle and Its Derived Types
        2. Interoperating with Unmanaged Code by Using SafeHandle Types
      5. Using Finalization with Managed Resources
      6. What Causes Finalize Methods to Be Called?
      7. Finalization Internals
      8. The Dispose Pattern: Forcing an Object to Clean Up
      9. Using a Type That Implements the Dispose Pattern
      10. C#'s using Statement
      11. An Interesting Dependency Issue
      12. Monitoring and Controlling the Lifetime of Objects Manually
      13. Resurrection
      14. Generations
      15. Other Garbage Collection Features for Use with Native Resources
      16. Predicting the Success of an Operation that Requires a Lot of Memory
      17. Programmatic Control of the Garbage Collector
      18. Thread Hijacking
      19. Garbage Collection Modes
      20. Large Objects
      21. Monitoring Garbage Collections
    3. 22. CLR Hosting and AppDomains
      1. CLR Hosting
      2. AppDomains
        1. Accessing Objects Across AppDomain Boundaries
          1. Demo #1: Cross-AppDomain Communication that Uses Marshal-by-Reference
          2. Demo #2: Cross-AppDomain Communication Using Marshal-by-Value
          3. Demo #3: Cross-AppDomain Communication Using Non-Marshalable Types
      3. AppDomain Unloading
      4. AppDomain Monitoring
      5. AppDomain First-Chance Exception Notifications
      6. How Hosts Use AppDomains
        1. Executable Applications
        2. Microsoft Silverlight Rich Internet Applications
        3. Microsoft ASP.NET Web Forms and XML Web Services Applications
        4. Microsoft SQL Server
        5. Your Own Imagination
      7. Advanced Host Control
        1. Managing the CLR by Using Managed Code
        2. Writing a Robust Host Application
        3. How a Host Gets Its Thread Back
    4. 23. Assembly Loading and Reflection
      1. Assembly Loading
      2. Using Reflection to Build a Dynamically Extensible Application
      3. Reflection Performance
        1. Discovering Types Defined in an Assembly
        2. What Exactly Is a Type Object?
        3. Building a Hierarchy of Exception-Derived Types
        4. Constructing an Instance of a Type
      4. Designing an Application That Supports Add-Ins
      5. Using Reflection to Discover a Type's Members
        1. Discovering a Type's Members
        2. BindingFlags: Filtering the Kinds of Members That Are Returned
        3. Discovering a Type's Interfaces
        4. Invoking a Type's Members
        5. Bind Once, Invoke Multiple Times
        6. Using Binding Handles to Reduce Your Process's Memory Consumption
    5. 24. Runtime Serialization
      1. Serialization/Deserialization Quick Start
      2. Making a Type Serializable
      3. Controlling Serialization and Deserialization
      4. How Formatters Serialize Type Instances
      5. Controlling the Serialized/Deserialized Data
        1. How to Define a Type That Implements ISerializable when the Base Type Doesn't Implement This Interface
      6. Streaming Contexts
      7. Serializing a Type as a Different Type and Deserializing an Object as a Different Object
      8. Serialization Surrogates
        1. Surrogate Selector Chains
      9. Overriding the Assembly and/or Type When Deserializing an Object
  8. V. Threading
    1. 25. Thread Basics
      1. Why Does Windows Support Threads?
      2. Thread Overhead
      3. Stop the Madness
      4. CPU Trends
      5. NUMA Architecture Machines
      6. CLR Threads and Windows Threads
      7. Using a Dedicated Thread to Perform an Asynchronous Compute-Bound Operation
      8. Reasons to Use Threads
      9. Thread Scheduling and Priorities
      10. Foreground Threads versus Background Threads
      11. What Now?
    2. 26. Compute-Bound Asynchronous Operations
      1. Introducing the CLR's Thread Pool
      2. Performing a Simple Compute-Bound Operation
      3. Execution Contexts
      4. Cooperative Cancellation
      5. Tasks
        1. Waiting for a Task to Complete and Getting Its Result
        2. Cancelling a Task
        3. Starting a New Task Automatically When Another Task Completes
        4. A Task May Start Child Tasks
        5. Inside a Task
        6. Task Factories
        7. Task Schedulers
      6. Parallel's Static For, ForEach, and Invoke Methods
      7. Parallel Language Integrated Query
      8. Performing a Periodic Compute-Bound Operation
        1. So Many Timers, So Little Time
      9. How the Thread Pool Manages Its Threads
        1. Setting Thread Pool Limits
        2. How Worker Threads Are Managed
      10. Cache Lines and False Sharing
    3. 27. I/O-Bound Asynchronous Operations
      1. How Windows Performs I/O Operations
      2. The CLR's Asynchronous Programming Model (APM)
      3. The AsyncEnumerator Class
      4. The APM and Exceptions
      5. Applications and Their Threading Models
      6. Implementing a Server Asynchronously
      7. The APM and Compute-Bound Operations
      8. APM Considerations
        1. Using the APM Without the Thread Pool
        2. Always Call the EndXxx Method, and Call It Only Once
        3. Always Use the Same Object When Calling the EndXxx Method
        4. Using ref, out, and params Arguments with BeginXxx and EndXxx Methods
        5. You Can't Cancel an Asynchronous I/O-Bound Operation
        6. Memory Consumption
        7. Some I/O Operations Must Be Done Synchronously
        8. FileStream-Specific Issues
      9. I/O Request Priorities
      10. Converting the IAsyncResult APM to a Task
      11. The Event-Based Asynchronous Pattern
        1. Converting the EAP to a Task
        2. Comparing the APM and the EAP
      12. Programming Model Soup
    4. 28. Primitive Thread Synchronization Constructs
      1. Class Libraries and Thread Safety
      2. Primitive User-Mode and Kernel-Mode Constructs
      3. User-Mode Constructs
        1. Volatile Constructs
          1. C#'s Support for Volatile Fields
        2. Interlocked Constructs
        3. Implementing a Simple Spin Lock
        4. The Interlocked Anything Pattern
      4. Kernel-Mode Constructs
        1. Event Constructs
        2. Semaphore Constructs
        3. Mutex Constructs
        4. Calling a Method When a Single Kernel Construct Becomes Available
    5. 29. Hybrid Thread Synchronization Constructs
      1. A Simple Hybrid Lock
      2. Spinning, Thread Ownership, and Recursion
      3. A Potpourri of Hybrid Constructs
        1. The ManualResetEventSlim and SemaphoreSlim Classes
        2. The Monitor Class and Sync Blocks
        3. The ReaderWriterLockSlim Class
        4. The OneManyLock Class
        5. The CountdownEvent Class
        6. The Barrier Class
        7. Thread Synchronization Construct Summary
      4. The Famous Double-Check Locking Technique
      5. The Condition Variable Pattern
      6. Using Collections to Avoid Holding a Lock for a Long Time
      7. The Concurrent Collection Classes
  9. Index
  10. About the Author
  11. Copyright