You are previewing CLR via C#, Fourth Edition.
O'Reilly logo
CLR via C#, Fourth Edition

Book Description

Dig deep and master the intricacies of the common language runtime, C#, and .NET development. Led by programming expert Jeffrey Richter, a longtime consultant to the Microsoft .NET team - you’ll gain pragmatic insights for building robust, reliable, and responsive apps and components.

  • Fully updated for .NET Framework 4.5 and Visual Studio 2012

  • Delivers a thorough grounding in the .NET Framework architecture, runtime environment, and other key topics, including asynchronous programming and the new Windows Runtime

  • Provides extensive code samples in Visual C# 2012

  • Features authoritative, pragmatic guidance on difficult development concepts such as generics and threading

  • Table of Contents

    1. CLR via C#, Fourth Edition
    2. Dedication
    3. Foreword
    4. Introduction
      1. Who This Book Is For
      2. Acknowledgments
      3. Errata & Book Support
      4. We Want to Hear from You
      5. Stay in Touch
    5. 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
    6. 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 Run Time
      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
        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 Arguments
          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. Generics Infrastructure
          1. Open and Closed Types
          2. Generic Types and Inheritance
          3. Generic Type Identity
          4. Code Explosion
        3. Generic Interfaces
        4. Generic Delegates
        5. Delegate and Interface Contra-variant and Covariant Generic Type Arguments
        6. Generic Methods
          1. Generic Methods and Type Inference
        7. Generics and Other Members
        8. 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?
    7. 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 Internals
        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 (Lambda Expressions)
          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
    8. 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. The Managed Heap and Garbage Collection
        1. Managed Heap Basics
          1. Allocating Resources from the Managed Heap
          2. The Garbage Collection Algorithm
          3. Garbage Collections and Debugging
        2. Generations: Improving Performance
          1. Garbage Collection Triggers
          2. Large Objects
          3. Garbage Collection Modes
          4. Forcing Garbage Collections
          5. Monitoring Your Application’s Memory Usage
        3. Working with Types Requiring Special Cleanup
          1. Using a Type That Wraps a Native Resource
          2. An Interesting Dependency Issue
          3. Other GC Features for Use with Native Resources
          4. Finalization Internals
        4. Monitoring and Controlling the Lifetime of Objects Manually
      3. 22. CLR Hosting and AppDomains
        1. CLR Hosting
        2. AppDomains
          1. Accessing Objects Across AppDomain Boundaries
            1. Demo #1: Cross-AppDomain Communication Using 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 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. Invoking a Type’s Members
          3. 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
      6. 25. Interoperating with WinRT Components
        1. CLR Projections and WinRT Component Type System Rules
          1. WinRT Type System Core Concepts
        2. Framework Projections
          1. Calling Asynchronous WinRT APIs from .NET Code
          2. Interoperating Between WinRT Streams and .NET Streams
          3. Passing Blocks of Data Between the CLR and WinRT
        3. Defining WinRT Components in C#
    9. V. Threading
      1. 26. Thread Basics
        1. Why Does Windows Support Threads?
        2. Thread Overhead
        3. Stop the Madness
        4. CPU Trends
        5. CLR Threads and Windows Threads
        6. Using a Dedicated Thread to Perform an Asynchronous Compute-Bound Operation
        7. Reasons to Use Threads
        8. Thread Scheduling and Priorities
        9. Foreground Threads vs. Background Threads
        10. What Now?
      2. 27. Compute-Bound Asynchronous Operations
        1. Introducing the CLR’s Thread Pool
        2. Performing a Simple Compute-Bound Operation
        3. Execution Contexts
        4. Cooperative Cancellation and Timeout
        5. Tasks
          1. Waiting for a Task to Complete and Getting Its Result
          2. Canceling 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
      3. 28. I/O-Bound Asynchronous Operations
        1. How Windows Performs I/O Operations
        2. C#’s Asynchronous Functions
        3. How the Compiler Transforms an Async Function into a State Machine
        4. Async Function Extensibility
        5. Async Functions and Event Handlers
        6. Async Functions in the Framework Class Library
        7. Async Functions and Exception Handling
        8. Other Async Function Features
        9. Applications and Their Threading Models
        10. Implementing a Server Asynchronously
        11. Canceling I/O Operations
        12. Some I/O Operations Must Be Done Synchronously
          1. FileStream-Specific Issues
        13. I/O Request Priorities
      4. 29. 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
      5. 30. Hybrid Thread Synchronization Constructs
        1. A Simple Hybrid Lock
        2. Spinning, Thread Ownership, and Recursion
        3. Hybrid Constructs in the Framework Class Library
          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. Asynchronous Synchronization
        7. The Concurrent Collection Classes
    10. Index
    11. About the Author
    12. Copyright