C# 4.0 in a Nutshell, 4th Edition

Book description

What people are saying about C# 4.0 in a Nutshell

"C# 4.0 in a Nutshell is one of the few books I keep on my desk as a quick reference. It is a book I recommend."--Scott Guthrie, Corporate Vice President, .NET Developer Platform, Microsoft Corporation

"A must-read for a concise but thorough examination of the parallel programming features in the .NET Framework 4."--Stephen Toub, Parallel Computing Platform Program Manager, Microsoft

"This wonderful book is a great reference for developers of all levels."-- Chris Burrows, C# Compiler Team, Microsoft

When you have questions about how to use C# 4.0 or the .NET CLR, this highly acclaimed bestseller has precisely the answers you need. Uniquely organized around concepts and use cases, this fourth edition includes in-depth coverage of new C# topics such as parallel programming, code contracts, dynamic programming, security, and COM interoperability. You'll also find updated information on LINQ, including examples that work with both LINQ to SQL and Entity Framework. This book has all the essential details to keep you on track with C# 4.0.

  • Get up to speed on C# language basics, including syntax, types, and variables
  • Explore advanced topics such as unsafe code and preprocessor directives
  • Learn C# 4.0 features such as dynamic binding, type parameter variance, and optional and named parameters
  • Work with .NET 4's rich set of features for parallel programming, code contracts, and the code security model
  • Learn .NET topics, including XML, collections, I/O and networking, memory management, reflection, attributes, security, and native interoperability

Publisher resources

View/Submit Errata

Table of contents

  1. C# 4.0 in a Nutshell
  2. A Note Regarding Supplemental Files
  3. Preface
    1. Intended Audience
    2. How This Book Is Organized
    3. What You Need to Use This Book
    4. Conventions Used in This Book
    5. Using Code Examples
    6. We’d Like to Hear from You
    7. Safari® Books Online
    8. Acknowledgments
      1. Joseph Albahari
      2. Ben Albahari
  4. 1. Introducing C# and the .NET Framework
    1. Object Orientation
    2. Type Safety
    3. Memory Management
    4. Platform Support
    5. C#’s Relationship with the CLR
    6. The CLR and .NET Framework
    7. What’s New in C# 4.0
  5. 2. C# Language Basics
    1. A First C# Program
      1. Compilation
    2. Syntax
      1. Identifiers and Keywords
        1. Avoiding conflicts
        2. Contextual keywords
      2. Literals, Punctuators, and Operators
      3. Comments
    3. Type Basics
      1. Predefined Type Examples
      2. Custom Type Examples
        1. Members of a type
        2. Symmetry of predefined types and custom types
        3. Constructors and instantiation
        4. Instance versus static members
        5. The public keyword
      3. Conversions
      4. Value Types Versus Reference Types
        1. Value types
        2. Reference types
        3. Null
        4. Storage overhead
      5. Predefined Type Taxonomy
    4. Numeric Types
      1. Numeric Literals
        1. Numeric literal type inference
        2. Numeric suffixes
      2. Numeric Conversions
        1. Integral to integral conversions
        2. Floating-point to floating-point conversions
        3. Floating-point to integral conversions
        4. Decimal conversions
      3. Arithmetic Operators
      4. Increment and Decrement Operators
      5. Specialized Integral Operations
        1. Integral division
        2. Integral overflow
        3. Integral arithmetic overflow check operators
        4. Overflow checking for constant expressions
        5. Bitwise operators
      6. 8- and 16-Bit Integrals
      7. Special Float and Double Values
      8. double Versus decimal
      9. Real Number Rounding Errors
    5. Boolean Type and Operators
      1. Bool Conversions
      2. Equality and Comparison Operators
      3. Conditional Operators
    6. Strings and Characters
      1. Char Conversions
      2. String Type
        1. String concatenation
        2. String comparisons
    7. Arrays
      1. Default Element Initialization
        1. Value types versus reference types
      2. Multidimensional Arrays
        1. Rectangular arrays
        2. Jagged arrays
      3. Simplified Array Initialization Expressions
      4. Bounds Checking
    8. Variables and Parameters
      1. The Stack and the Heap
        1. Stack
        2. Heap
      2. Definite Assignment
      3. Default Values
      4. Parameters
        1. Passing arguments by value
        2. The ref modifier
        3. The out modifier
        4. Implications of passing by reference
        5. The params modifier
        6. Optional parameters (C# 4.0)
        7. Named arguments (C# 4.0)
      5. var—Implicitly Typed Local Variables
    9. Expressions and Operators
      1. Primary Expressions
      2. Void Expressions
      3. Assignment Expressions
      4. Operator Precedence and Associativity
        1. Precedence
        2. Left-associative operators
        3. Right-associative operators
      5. Operator Table
    10. Statements
      1. Declaration Statements
        1. Local variables
      2. Expression Statements
      3. Selection Statements
        1. The if statement
        2. The else clause
        3. Changing the flow of execution with braces
        4. The switch statement
      4. Iteration Statements
        1. while and do-while loops
        2. for loops
        3. foreach loops
      5. Jump Statements
        1. The break statement
        2. The continue statement
        3. The goto statement
        4. The return statement
        5. The throw statement
      6. Miscellaneous Statements
    11. Namespaces
      1. The using Directive
      2. Rules Within a Namespace
        1. Name scoping
        2. Name hiding
        3. Repeated namespaces
        4. Nested using directive
      3. Aliasing Types and Namespaces
      4. Advanced Namespace Features
        1. Extern
        2. Namespace alias qualifiers
  6. 3. Creating Types in C#
    1. Classes
      1. Fields
        1. The readonly modifier
        2. Field initialization
        3. Declaring multiple fields together
      2. Methods
        1. Overloading methods
        2. Pass-by-value versus pass-by-reference
      3. Instance Constructors
        1. Overloading constructors
        2. Implicit parameterless constructors
        3. Constructor and field initialization order
        4. Nonpublic constructors
      4. Object Initializers
      5. The this Reference
      6. Properties
        1. Read-only and calculated properties
        2. Automatic properties
        3. get and set accessibility
        4. CLR property implementation
      7. Indexers
        1. Implementing an indexer
        2. CLR indexer implementation
      8. Constants
      9. Static Constructors
        1. Static constructors and field initialization order
      10. Static Classes
      11. Finalizers
      12. Partial Types and Methods
        1. Partial methods
    2. Inheritance
      1. Polymorphism
      2. Casting and Reference Conversions
        1. Upcasting
        2. Downcasting
        3. The as operator
        4. The is operator
      3. Virtual Function Members
      4. Abstract Classes and Abstract Members
      5. Hiding Inherited Members
        1. new versus override
      6. Sealing Functions and Classes
      7. The base Keyword
      8. Constructors and Inheritance
        1. Implicit calling of the parameterless base class constructor
        2. Constructor and field initialization order
      9. Overloading and Resolution
    3. The object Type
      1. Boxing and Unboxing
        1. Copying semantics of boxing and unboxing
      2. Static and Runtime Type Checking
      3. The GetType Method and typeof Operator
      4. The ToString Method
      5. Object Member Listing
    4. Structs
      1. Struct Construction Semantics
    5. Access Modifiers
      1. Examples
      2. Friend Assemblies
      3. Accessibility Capping
      4. Restrictions on Access Modifiers
    6. Interfaces
      1. Extending an Interface
      2. Explicit Interface Implementation
      3. Implementing Interface Members Virtually
      4. Reimplementing an Interface in a Subclass
        1. Alternatives to interface reimplementation
      5. Interfaces and Boxing
    7. Enums
      1. Enum Conversions
      2. Flags Enums
      3. Enum Operators
      4. Type-Safety Issues
    8. Nested Types
    9. Generics
      1. Generic Types
      2. Why Generics Exist
      3. Generic Methods
      4. Declaring Type Parameters
      5. typeof and Unbound Generic Types
      6. The default Generic Value
      7. Generic Constraints
      8. Subclassing Generic Types
      9. Self-Referencing Generic Declarations
      10. Static Data
      11. Type Parameters and Conversions
      12. Covariance
        1. Classes
        2. Arrays
        3. Interfaces
      13. Contravariance
      14. C# Generics Versus C++ Templates
  7. 4. Advanced C#
    1. Delegates
      1. Writing Plug-in Methods with Delegates
      2. Multicast Delegates
        1. Multicast delegate example
      3. Instance Versus Static Method Targets
      4. Generic Delegate Types
      5. The Func and Action Delegates
      6. Delegates Versus Interfaces
      7. Delegate Compatibility
        1. Type compatibility
        2. Parameter compatibility
        3. Return type compatibility
        4. Generic delegate type parameter variance (C# 4.0)
    2. Events
      1. Standard Event Pattern
      2. Event Accessors
      3. Event Modifiers
    3. Lambda Expressions
      1. Explicitly Specifying Lambda Parameter Types
      2. Capturing Outer Variables
        1. Capturing iteration variables
    4. Anonymous Methods
    5. try Statements and Exceptions
      1. The catch Clause
      2. The finally Block
        1. The using statement
      3. Throwing Exceptions
        1. Rethrowing an exception
      4. Key Properties of System.Exception
      5. Common Exception Types
      6. Common Patterns
        1. The TryXXX method pattern
        2. The atomicity pattern
        3. Alternatives to exceptions
    6. Enumeration and Iterators
      1. Enumeration
      2. Collection Initializers
      3. Iterators
      4. Iterator Semantics
        1. yield break
        2. Iterators and try/catch/finally blocks
      5. Composing Sequences
    7. Nullable Types
      1. Nullable<T> Struct
      2. Implicit and Explicit Nullable Conversions
      3. Boxing and Unboxing Nullable Values
      4. Operator Lifting
        1. Equality operators (==   !=)
        2. Relational operators (<   <=   >=   >)
        3. All other operators (+   −   *   /   %   &   |   ^   <<   >>   +   ++   --   !   ~)
        4. Mixing nullable and non-nullable operators
      5. bool? with & and | Operators
      6. Null Coalescing Operator
      7. Scenarios for Nullable Types
      8. Alternatives to Nullable Types
    8. Operator Overloading
      1. Operator Functions
      2. Overloading Equality and Comparison Operators
      3. Custom Implicit and Explicit Conversions
      4. Overloading true and false
    9. Extension Methods
      1. Extension Method Chaining
      2. Ambiguity and Resolution
        1. Namespaces
        2. Extension methods versus instance methods
        3. Extension methods versus extension methods
      3. Extension Methods on Interfaces
    10. Anonymous Types
    11. Dynamic Binding
      1. Static Binding Versus Dynamic Binding
      2. Custom Binding
      3. Language Binding
      4. RuntimeBinderException
      5. Runtime Representation of Dynamic
      6. Dynamic Conversions
      7. var Versus dynamic
      8. Dynamic Expressions
      9. Dynamic Calls Without Dynamic Receivers
      10. Static Types in Dynamic Expressions
      11. Uncallable Functions
    12. Attributes
      1. Attribute Classes
      2. Named and Positional Attribute Parameters
      3. Attribute Targets
      4. Specifying Multiple Attributes
    13. Unsafe Code and Pointers
      1. Pointer Basics
      2. Unsafe Code
      3. The fixed Statement
      4. The Pointer-to-Member Operator
      5. Arrays
        1. The stackalloc keyword
        2. Fixed-size buffers
      6. void*
      7. Pointers to Unmanaged Code
    14. Preprocessor Directives
      1. Conditional Attributes
      2. Pragma Warning
    15. XML Documentation
      1. Standard XML Documentation Tags
      2. User-Defined Tags
      3. Type or Member Cross-References
  8. 5. Framework Overview
    1. The CLR and Core Framework
      1. System Types
      2. Text Processing
      3. Collections
      4. Queries
      5. XML
      6. Diagnostics and Code Contracts
      7. Streams and I/O
      8. Networking
      9. Serialization
      10. Assemblies, Reflection, and Attributes
      11. Dynamic Programming
      12. Security
      13. Threading and Parallel Programming
      14. Application Domains
      15. Native and COM Interoperability
    2. Applied Technologies
      1. User Interface Technologies
        1. ASP.NET
        2. Silverlight
        3. Windows Presentation Foundation (WPF)
        4. Windows Forms
      2. Backend Technologies
        1. ADO.NET
        2. Windows Workflow
        3. COM+ and MSMQ
      3. Distributed System Technologies
        1. Windows Communication Foundation (WCF)
        2. Remoting and Web Services
        3. CardSpace
  9. 6. Framework Fundamentals
    1. String and Text Handling
      1. Char
      2. String
        1. Constructing strings
        2. Null and empty strings
        3. Accessing characters within a string
        4. Searching within strings
        5. Manipulating strings
        6. Splitting and joining strings
        7. String.Format and composite format strings
      3. Comparing Strings
        1. Ordinal versus culture comparison
        2. String equality comparison
        3. String order comparison
      4. StringBuilder
      5. Text Encodings and Unicode
        1. Obtaining an Encoding object
        2. Encoding for file and stream I/O
        3. Encoding to byte arrays
        4. UTF-16 and surrogate pairs
    2. Dates and Times
      1. TimeSpan
      2. DateTime and DateTimeOffset
        1. Choosing between DateTime and DateTimeOffset
        2. Constructing a DateTime
        3. Constructing a DateTimeOffset
        4. The current DateTime/DateTimeOffset
        5. Working with dates and times
        6. Formatting and parsing
        7. Null DateTime and DateTimeOffset values
    3. Dates and Time Zones
      1. DateTime and Time Zones
      2. DateTimeOffset and Time Zones
      3. TimeZone and TimeZoneInfo
        1. TimeZone
        2. TimeZoneInfo
      4. Daylight Saving Time and DateTime
    4. Formatting and Parsing
      1. ToString and Parse
      2. Format Providers
        1. Format providers and CultureInfo
        2. Using NumberFormatInfo or DateTimeFormatInfo
        3. Composite formatting
        4. Parsing with format providers
        5. IFormatProvider and ICustomFormatter
    5. Standard Format Strings and Parsing Flags
      1. Numeric Format Strings
      2. NumberStyles
      3. Date/Time Format Strings
        1. Parsing and misparsing DateTimes
      4. DateTimeStyles
      5. Enum Format Strings
    6. Other Conversion Mechanisms
      1. Convert
        1. Rounding real to integral conversions
        2. Parsing numbers in base 2, 8, and 16
        3. Dynamic conversions
        4. Base 64 conversions
      2. XmlConvert
      3. Type Converters
      4. BitConverter
    7. Globalization
      1. Globalization Checklist
      2. Testing
    8. Working with Numbers
      1. Conversions
      2. Math
      3. BigInteger
      4. Complex
      5. Random
    9. Enums
      1. Enum Conversions
        1. Enum to integral conversions
        2. Integral to enum conversions
        3. String conversions
      2. Enumerating Enum Values
      3. How Enums Work
    10. Tuples
      1. Comparing Tuples
    11. The Guid Struct
    12. Equality Comparison
      1. Value Versus Referential Equality
      2. Standard Equality Protocols
        1. == and !=
        2. The virtual Object.Equals method
        3. The static object.Equals method
        4. The static object.ReferenceEquals method
        5. The IEquatable<T> interface
        6. When Equals and == are not equal
      3. Equality and Custom Types
        1. Changing the meaning of equality
        2. Speeding up equality comparisons with structs
        3. How to override equality semantics
        4. Overriding GetHashCode
        5. Overriding Equals
        6. Overloading == and !=
        7. Implementing IEquatable<T>
        8. An example: The Area struct
        9. Pluggable equality comparers
    13. Order Comparison
      1. IComparable
        1. IComparable versus Equals
      2. < and >
      3. Implementing the IComparable Interfaces
    14. Utility Classes
      1. Console
      2. Environment
      3. Process
  10. 7. Collections
    1. Enumeration
      1. IEnumerable and IEnumerator
      2. IEnumerable<T> and IEnumerator<T>
        1. IEnumerable<T> and IDisposable
      3. Implementing the Enumeration Interfaces
    2. The ICollection and IList Interfaces
      1. ICollection<T> and ICollection
      2. IList<T> and IList
    3. The Array Class
      1. Construction and Indexing
      2. Enumeration
      3. Length and Rank
      4. Searching
      5. Sorting
      6. Reversing Elements
      7. Copying, Converting, and Resizing
    4. Lists, Queues, Stacks, and Sets
      1. List<T> and ArrayList
      2. LinkedList<T>
      3. Queue<T> and Queue
      4. Stack<T> and Stack
      5. BitArray
      6. HashSet<T> and SortedSet<T>
    5. Dictionaries
      1. IDictionary<TKey,TValue>
      2. IDictionary
      3. Dictionary<TKey,TValue> and Hashtable
      4. OrderedDictionary
      5. ListDictionary and HybridDictionary
      6. Sorted Dictionaries
    6. Customizable Collections and Proxies
      1. Collection<T> and CollectionBase
        1. CollectionBase
      2. KeyedCollection<TKey,TItem> and DictionaryBase
        1. DictionaryBase
      3. ReadOnlyCollection<T>
    7. Plugging in Equality and Order
      1. IEqualityComparer and EqualityComparer
        1. EqualityComparer<T>.Default
      2. IComparer and Comparer
      3. StringComparer
      4. IStructuralEquatable and IStructuralComparable
  11. 8. LINQ Queries
    1. Getting Started
    2. Fluent Syntax
      1. Chaining Query Operators
        1. Why extension methods are important
      2. Composing Lambda Expressions
        1. Lambda expressions and Func signatures
        2. Lambda expressions and element typing
      3. Natural Ordering
      4. Other Operators
    3. Query Expressions
      1. Range Variables
      2. Query Syntax Versus SQL Syntax
      3. Query Syntax Versus Fluent Syntax
      4. Mixed Syntax Queries
    4. Deferred Execution
      1. Reevaluation
      2. Captured Variables
      3. How Deferred Execution Works
      4. Chaining Decorators
      5. How Queries Are Executed
    5. Subqueries
      1. Subqueries and Deferred Execution
    6. Composition Strategies
      1. Progressive Query Building
      2. The into Keyword
        1. Scoping rules
      3. Wrapping Queries
    7. Projection Strategies
      1. Object Initializers
      2. Anonymous Types
      3. The let Keyword
    8. Interpreted Queries
      1. How Interpreted Queries Work
        1. Execution
      2. Combining Interpreted and Local Queries
      3. AsEnumerable
    9. LINQ to SQL and Entity Framework
      1. LINQ to SQL Entity Classes
      2. Entity Framework Entity Classes
      3. DataContext and ObjectContext
        1. Typed contexts
        2. Object tracking
      4. Associations
      5. Deferred Execution with L2S and EF
      6. DataLoadOptions
        1. Specifying a filter in advance
        2. Eager loading
      7. Eager Loading in Entity Framework
      8. Updates
      9. API Differences Between L2S and EF
    10. Building Query Expressions
      1. Delegates Versus Expression Trees
        1. Compiling expression trees
        2. AsQueryable
      2. Expression Trees
        1. The Expression DOM
  12. 9. LINQ Operators
    1. Overview
      1. Sequence→Sequence
        1. Filtering
        2. Projecting
        3. Joining
        4. Ordering
        5. Grouping
        6. Set operators
        7. Zip operator
        8. Conversion methods: Import
        9. Conversion methods: Export
      2. Sequence→Element or Scalar
        1. Element operators
        2. Aggregation methods
        3. Quantifiers
      3. Void→Sequence
        1. Generation methods
    2. Filtering
      1. Where
        1. Query syntax
        2. Enumerable.Where implementation
        3. Overview
        4. Indexed filtering
        5. SQL LIKE comparisons in LINQ to SQL and EF
        6. < and > string comparisons in LINQ to SQL and EF
        7. WHERE x IN (..., ..., ...) in LINQ to SQL and EF
      2. Take and Skip
      3. TakeWhile and SkipWhile
      4. Distinct
    3. Projecting
      1. Select
        1. Query syntax
        2. Enumerable implementation
        3. Overview
        4. Indexed projection
        5. Select subqueries and object hierarchies
        6. Subqueries and joins in LINQ to SQL and EF
        7. Projecting into concrete types
      2. SelectMany
        1. Query syntax
        2. Enumerable implementation
        3. Overview
        4. Outer range variables
        5. Thinking in query syntax
        6. Joining with SelectMany
        7. SelectMany in LINQ to SQL and EF
        8. Outer joins with SelectMany
    4. Joining
      1. Join and GroupJoin
        1. Join arguments
        2. GroupJoin arguments
        3. Query syntax
        4. Overview
        5. Join
        6. Joining on multiple keys
        7. Joining in fluent syntax
        8. GroupJoin
        9. Flat outer joins
        10. Joining with lookups
        11. Enumerable implementations
    5. Ordering
      1. OrderBy, OrderByDescending, ThenBy, and ThenByDescending
        1. OrderBy and OrderByDescending arguments
        2. ThenBy and ThenByDescending arguments
        3. Query syntax
        4. Overview
        5. Comparers and collations
        6. IOrderedEnumerable and IOrderedQueryable
    6. Grouping
      1. GroupBy
        1. Query syntax
        2. Overview
        3. GroupBy in LINQ to SQL and EF
        4. Grouping by multiple keys
        5. Custom equality comparers
    7. Set Operators
      1. Concat and Union
      2. Intersect and Except
    8. The Zip Operator
    9. Conversion Methods
      1. OfType and Cast
      2. ToArray, ToList, ToDictionary, and ToLookup
      3. AsEnumerable and AsQueryable
    10. Element Operators
      1. First, Last, and Single
      2. ElementAt
      3. DefaultIfEmpty
    11. Aggregation Methods
      1. Count and LongCount
      2. Min and Max
      3. Sum and Average
      4. Aggregate
        1. Unseeded aggregations
        2. Traps with unseeded aggregations
    12. Quantifiers
      1. Contains and Any
      2. All and SequenceEqual
    13. Generation Methods
      1. Empty
      2. Range and Repeat
  13. 10. LINQ to XML
    1. Architectural Overview
      1. What Is a DOM?
      2. The LINQ to XML DOM
    2. X-DOM Overview
      1. Loading and Parsing
      2. Saving and Serializing
    3. Instantiating an X-DOM
      1. Functional Construction
      2. Specifying Content
      3. Automatic Deep Cloning
    4. Navigating and Querying
      1. Child Node Navigation
        1. FirstNode, LastNode, and Nodes
        2. Retrieving elements
        3. Retrieving a single element
        4. Recursive functions
      2. Parent Navigation
      3. Peer Node Navigation
      4. Attribute Navigation
    5. Updating an X-DOM
      1. Simple Value Updates
      2. Updating Child Nodes and Attributes
      3. Updating Through the Parent
        1. Removing a sequence of nodes or attributes
    6. Working with Values
      1. Setting Values
      2. Getting Values
      3. Values and Mixed Content Nodes
      4. Automatic XText Concatenation
    7. Documents and Declarations
      1. XDocument
      2. XML Declarations
        1. Writing a declaration to a string
    8. Names and Namespaces
      1. Namespaces in XML
        1. Prefixes
        2. Attributes
      2. Specifying Namespaces in the X-DOM
      3. The X-DOM and Default Namespaces
      4. Prefixes
    9. Annotations
    10. Projecting into an X-DOM
      1. Eliminating Empty Elements
      2. Streaming a Projection
      3. Transforming an X-DOM
        1. Advanced transformations
  14. 11. Other XML Technologies
    1. XmlReader
      1. Reading Nodes
      2. Reading Elements
        1. Optional elements
        2. Random element order
        3. Empty elements
        4. Other ReadXXX methods
      3. Reading Attributes
        1. Attribute nodes
      4. Namespaces and Prefixes
    2. XmlWriter
      1. Writing Attributes
      2. Writing Other Node Types
      3. Namespaces and Prefixes
    3. Patterns for Using XmlReader/XmlWriter
      1. Working with Hierarchical Data
      2. Mixing XmlReader/XmlWriter with an X-DOM
        1. Using XmlReader with XElement
        2. Using XmlWriter with XElement
    4. XmlDocument
      1. Loading and Saving an XmlDocument
      2. Traversing an XmlDocument
      3. InnerText and InnerXml
      4. Creating and Manipulating Nodes
      5. Namespaces
    5. XPath
      1. Common XPath Operators
      2. XPathNavigator
      3. Querying with Namespaces
      4. XPathDocument
    6. XSD and Schema Validation
      1. Performing Schema Validation
        1. Validating with an XmlReader
        2. Validating an X-DOM or XmlDocument
    7. XSLT
  15. 12. Disposal and Garbage Collection
    1. IDisposable, Dispose, and Close
      1. Standard Disposal Semantics
        1. Close and Stop
      2. When to Dispose
      3. Opt-in Disposal
      4. Clearing Fields in Disposal
    2. Automatic Garbage Collection
      1. Roots
    3. Finalizers
      1. Calling Dispose from a Finalizer
      2. Resurrection
        1. GC.ReRegisterForFinalize
    4. How the Garbage Collector Works
      1. Optimization Techniques
        1. Generational collection
        2. The large object heap
        3. Concurrent and background collection
        4. GC notifications (server CLR)
      2. Forcing Garbage Collection
      3. Memory Pressure
    5. Managed Memory Leaks
      1. Timers
      2. Diagnosing Memory Leaks
    6. Weak References
      1. Weak References and Caching
      2. Weak References and Events
  16. 13. Diagnostics and Code Contracts
    1. Conditional Compilation
      1. Conditional Compilation Versus Static Variable Flags
      2. The Conditional Attribute
        1. Alternatives to the Conditional attribute
    2. Debug and Trace Classes
      1. Fail and Assert
      2. TraceListener
      3. Flushing and Closing Listeners
    3. Code Contracts Overview
      1. Why Use Code Contracts?
      2. Contract Principles
        1. Compilation
        2. The binary rewriter
        3. Asserting versus throwing on failure
        4. Purity
    4. Preconditions
      1. Contract.Requires
      2. Contract.Requires<TException>
      3. Contract.EndContractBlock
      4. Preconditions and Overridden Methods
    5. Postconditions
      1. Contract.Ensures
      2. Contract.EnsuresOnThrow<TException>
      3. Contract.Result<T> and Contract.ValueAtReturn<T>
      4. Contract.OldValue<T>
      5. Postconditions and Overridden Methods
    6. Assertions and Object Invariants
      1. Assertions
        1. Contract.Assert
        2. Contract.Assume
      2. Object Invariants
    7. Contracts on Interfaces and Abstract Methods
    8. Dealing with Contract Failure
      1. The ContractFailed Event
      2. Exceptions Within Contract Conditions
    9. Selectively Enforcing Contracts
      1. Contracts in Release Builds
      2. Call-Site Checking
    10. Static Contract Checking
      1. The ContractVerification Attribute
      2. Baselines
      3. The SuppressMessage Attribute
    11. Debugger Integration
      1. Attaching and Breaking
      2. Debugger Attributes
    12. Processes and Process Threads
      1. Examining Running Processes
      2. Examining Threads in a Process
    13. StackTrace and StackFrame
    14. Windows Event Logs
      1. Writing to the Event Log
      2. Reading the Event Log
      3. Monitoring the Event Log
    15. Performance Counters
      1. Enumerating the Available Counters
      2. Reading Performance Counter Data
      3. Creating Counters and Writing Performance Data
    16. The Stopwatch Class
  17. 14. Streams and I/O
    1. Stream Architecture
    2. Using Streams
      1. Reading and Writing
      2. Seeking
      3. Closing and Flushing
      4. Timeouts
      5. Thread Safety
      6. Backing Store Streams
      7. FileStream
        1. Constructing a FileStream
        2. Specifying a filename
        3. Specifying a FileMode
        4. Advanced FileStream features
      8. MemoryStream
      9. PipeStream
        1. Named pipes
        2. Anonymous pipes
      10. BufferedStream
    3. Stream Adapters
      1. Text Adapters
        1. StreamReader and StreamWriter
        2. Character encodings
        3. StringReader and StringWriter
      2. Binary Adapters
      3. Closing and Disposing Stream Adapters
    4. File and Directory Operations
      1. The File Class
        1. Compression and encryption attributes
        2. File security
      2. The Directory Class
      3. FileInfo and DirectoryInfo
      4. Path
      5. Special Folders
      6. Querying Volume Information
      7. Catching Filesystem Events
    5. Memory-Mapped Files
      1. Memory-Mapped Files and Random File I/O
      2. Memory-Mapped Files and Shared Memory
      3. Working with View Accessors
    6. Compression
      1. Compressing in Memory
    7. Isolated Storage
      1. Isolation Types
      2. Reading and Writing Isolated Storage
      3. Store Location
      4. Enumerating Isolated Storage
  18. 15. Networking
    1. Network Architecture
    2. Addresses and Ports
    3. URIs
    4. Request/Response Architecture
      1. WebClient
      2. WebRequest and WebResponse
      3. Proxies
      4. Authentication
        1. CredentialCache
      5. Concurrency
      6. Exception Handling
    5. HTTP-Specific Support
      1. Headers
      2. Query Strings
      3. Uploading Form Data
      4. Cookies
      5. Forms Authentication
      6. SSL
    6. Writing an HTTP Server
    7. Using FTP
    8. Using DNS
    9. Sending Mail with SmtpClient
    10. Using TCP
      1. Concurrency
    11. Receiving POP3 Mail with TCP
  19. 16. Serialization
    1. Serialization Concepts
      1. Serialization Engines
        1. Why three engines?
        2. The data contract serializer
        3. The binary serializer
        4. XmlSerializer
        5. IXmlSerializable
      2. Formatters
      3. Explicit Versus Implicit Serialization
    2. The Data Contract Serializer
      1. DataContractSerializer Versus NetDataContractSerializer
      2. Using the Serializers
        1. Specifying a binary formatter
      3. Serializing Subclasses
      4. Object References
        1. Preserving object references
      5. Version Tolerance
        1. Required members
      6. Member Ordering
      7. Null and Empty Values
    3. Data Contracts and Collections
      1. Subclassed Collection Elements
      2. Customizing Collection and Element Names
    4. Extending Data Contracts
      1. Serialization and Deserialization Hooks
      2. Interoperating with [Serializable]
      3. Interoperating with IXmlSerializable
    5. The Binary Serializer
      1. Getting Started
    6. Binary Serialization Attributes
      1. [NonSerialized]
      2. [OnDeserializing] and [OnDeserialized]
      3. [OnSerializing] and [OnSerialized]
      4. [OptionalField] and Versioning
    7. Binary Serialization with ISerializable
      1. Subclassing Serializable Classes
    8. XML Serialization
      1. Getting Started with Attribute-Based Serialization
        1. Attributes, names, and namespaces
        2. XML element order
      2. Subclasses and Child Objects
        1. Subclassing the root type
        2. Serializing child objects
        3. Subclassing child objects
      3. Serializing Collections
        1. Working with subclassed collection elements
      4. IXmlSerializable
  20. 17. Assemblies
    1. What’s in an Assembly?
      1. The Assembly Manifest
        1. Specifying assembly attributes
      2. The Application Manifest
        1. Deploying an application manifest
      3. Modules
      4. The Assembly Class
    2. Strong Names and Assembly Signing
      1. How to Strongly Name an Assembly
      2. Delay Signing
    3. Assembly Names
      1. Fully Qualified Names
      2. The AssemblyName Class
      3. Assembly Informational and File Versions
    4. Authenticode Signing
      1. How to Sign with Authenticode
        1. Obtaining and installing a certificate
        2. Signing with signtool.exe
        3. Time stamping
        4. Verifying that a program has been signed
      2. Authenticode Validation
    5. The Global Assembly Cache
      1. How to Install Assemblies to the GAC
      2. GAC and Versioning
    6. Resources and Satellite Assemblies
      1. Directly Embedding Resources
      2. .resources Files
      3. .resx Files
        1. Creating a .resx file at the command line
        2. Reading .resources files
        3. Creating a pack URI resource in Visual Studio
      4. Satellite Assemblies
        1. Building satellite assemblies
        2. Testing satellite assemblies
        3. Visual Studio designer support
      5. Cultures and Subcultures
    7. Resolving and Loading Assemblies
      1. Assembly and Type Resolution Rules
      2. AssemblyResolve
      3. Loading Assemblies
        1. Loading from a filename
    8. Deploying Assemblies Outside the Base Folder
    9. Packing a Single-File Executable
      1. Selective Patching
    10. Working with Unreferenced Assemblies
  21. 18. Reflection and Metadata
    1. Reflecting and Activating Types
      1. Obtaining a Type
        1. Obtaining array types
        2. Obtaining nested types
      2. Type Names
        1. Nested type names
        2. Generic type names
        3. Array and pointer type names
        4. ref and out parameter type names
      3. Base Types and Interfaces
      4. Instantiating Types
      5. Generic Types
    2. Reflecting and Invoking Members
      1. Member Types
      2. C# Members Versus CLR Members
      3. Generic Type Members
      4. Dynamically Invoking a Member
      5. Method Parameters
        1. Dealing with ref and out parameters
        2. Retrieving and invoking generic methods
      6. Using Delegates for Performance
      7. Accessing Nonpublic Members
        1. The BindingFlags enum
      8. Generic Methods
      9. Anonymously Calling Members of a Generic Interface
    3. Reflecting Assemblies
      1. Loading an Assembly into a Reflection-Only Context
      2. Modules
    4. Working with Attributes
      1. Attribute Basics
      2. The AttributeUsage Attribute
      3. Defining Your Own Attribute
      4. Retrieving Attributes at Runtime
      5. Retrieving Attributes in the Reflection-Only Context
    5. Dynamic Code Generation
      1. Generating IL with DynamicMethod
      2. The Evaluation Stack
      3. Passing Arguments to a Dynamic Method
      4. Generating Local Variables
      5. Branching
      6. Instantiating Objects and Calling Instance Methods
      7. Exception Handling
    6. Emitting Assemblies and Types
      1. Saving Emitted Assemblies
      2. The Reflection.Emit Object Model
    7. Emitting Type Members
      1. Emitting Methods
        1. Generating instance methods
        2. HideBySig
      2. Emitting Fields and Properties
      3. Emitting Constructors
        1. Calling base constructors
      4. Attaching Attributes
    8. Emitting Generic Methods and Types
      1. Defining Generic Methods
      2. Defining Generic Types
    9. Awkward Emission Targets
      1. Uncreated Closed Generics
      2. Circular Dependencies
    10. Parsing IL
      1. Writing a Disassembler
  22. 19. Dynamic Programming
    1. The Dynamic Language Runtime
    2. Numeric Type Unification
    3. Dynamic Member Overload Resolution
      1. Simplifying the Visitor Pattern
        1. Variations
      2. Anonymously Calling Members of a Generic Type
    4. Implementing Dynamic Objects
      1. DynamicObject
      2. ExpandoObject
    5. Interoperating with Dynamic Languages
      1. Passing State Between C# and a Script
  23. 20. Security
    1. Permissions
      1. CodeAccessPermission and PrincipalPermission
        1. IPermission
      2. PermissionSet
      3. Declarative Versus Imperative Security
    2. Code Access Security (CAS)
      1. How Code Access Security Is Applied
      2. Testing for Full Trust
    3. Allowing Partially Trusted Callers
      1. Elevation of Privilege
      2. APTCA and [SecurityTransparent]
    4. The Transparency Model in CLR 4.0
      1. How the Transparency Model Works
        1. Transparent code
        2. Settings the transparency default for an assembly
      2. How to Write APTCA Libraries with Transparency
        1. Securing unsafe methods
        2. P/Invokes and [SuppressUnmanagedSecurity]
      3. Transparency in Full-Trust Scenarios
    5. Sandboxing Another Assembly
      1. Asserting Permissions
    6. Operating System Security
      1. Running in a Standard User Account
      2. Administrative Elevation and Virtualization
    7. Identity and Role Security
      1. Assigning Users and Roles
    8. Cryptography Overview
    9. Windows Data Protection
    10. Hashing
    11. Symmetric Encryption
      1. Encrypting in Memory
      2. Chaining Encryption Streams
      3. Disposing Encryption Objects
      4. Key Management
    12. Public Key Encryption and Signing
      1. The RSA Class
      2. Digital Signing
  24. 21. Threading
    1. Threading’s Uses and Misuses
    2. Getting Started
      1. Passing Data to a Thread
        1. Lambda expressions and captured variables
      2. Sharing Data Between Threads
      3. Foreground and Background Threads
      4. Thread Priority
      5. Exception Handling
    3. Thread Pooling
      1. Entering the Thread Pool via TPL
      2. Entering the Thread Pool Without TPL
        1. QueueUserWorkItem
        2. Asynchronous delegates
      3. Optimizing the Thread Pool
    4. Synchronization
      1. Blocking
      2. Blocking Versus Spinning
    5. Locking
      1. Monitor.Enter and Monitor.Exit
        1. The lockTaken overloads
        2. TryEnter
      2. Choosing the Synchronization Object
      3. When to Lock
      4. Locking and Atomicity
      5. Nested Locking
      6. Deadlocks
      7. Performance
      8. Mutex
      9. Semaphore
    6. Thread Safety
      1. Thread Safety and .NET Framework Types
        1. Locking around thread-safe objects
        2. Static methods
        3. Read-only thread safety
      2. Thread Safety in Application Servers
      3. Rich Client Applications and Thread Affinity
        1. Worker threads versus UI threads
      4. Immutable Objects
    7. Nonblocking Synchronization
      1. Memory Barriers and Volatility
        1. Full fences
        2. The volatile keyword
        3. VolatileRead and VolatileWrite
        4. Memory barriers and locking
      2. Interlocked
    8. Signaling with Event Wait Handles
      1. AutoResetEvent
        1. Two-way signaling
      2. ManualResetEvent
      3. CountdownEvent
      4. Creating a Cross-Process EventWaitHandle
      5. Wait Handles and the Thread Pool
      6. WaitAny, WaitAll, and SignalAndWait
        1. Alternatives to WaitAll and SignalAndWait
    9. Signaling with Wait and Pulse
      1. How to Use Wait and Pulse
      2. Producer/Consumer Queue
      3. Wait Timeouts
      4. Simulating Wait Handles
    10. The Barrier Class
    11. The Event-Based Asynchronous Pattern
    12. BackgroundWorker
      1. Using BackgroundWorker
    13. Interrupt and Abort
      1. Interrupt
      2. Abort
    14. Safe Cancellation
      1. Cancellation Tokens
    15. Lazy Initialization
      1. Lazy<T>
      2. LazyInitializer
    16. Thread-Local Storage
      1. [ThreadStatic]
      2. ThreadLocal<T>
        1. ThreadLocal<T> and instance fields
      3. GetData and SetData
    17. Reader/Writer Locks
      1. Upgradeable Locks and Recursion
        1. Lock recursion
    18. Timers
      1. Multithreaded Timers
      2. Single-Threaded Timers
  25. 22. Parallel Programming
    1. Why PFX?
      1. PFX Concepts
      2. PFX Components
      3. When to Use PFX
    2. PLINQ
      1. Parallel Execution Ballistics
      2. PLINQ and Ordering
      3. PLINQ Limitations
      4. Example: Parallel Spellchecker
        1. Using ThreadLocal<T>
      5. Functional Purity
      6. Calling Blocking or I/O-Intensive Functions
        1. Changing the degree of parallelism
      7. Cancellation
      8. Optimizing PLINQ
        1. Output-side optimization
        2. Input-side optimization
        3. Optimizing custom aggregations
    3. The Parallel Class
      1. Parallel.Invoke
      2. Parallel.For and Parallel.ForEach
        1. Outer versus inner loops
        2. Indexed Parallel.ForEach
        3. ParallelLoopState: Breaking early out of loops
        4. Optimization with local values
    4. Task Parallelism
      1. Creating and Starting Tasks
        1. Specifying a state object
        2. TaskCreationOptions
        3. Child tasks
      2. Waiting on Tasks
      3. Exception-Handling Tasks
      4. Canceling Tasks
      5. Continuations
        1. Continuations and Task<TResult>
        2. Continuations and exceptions
        3. Continuations and child tasks
        4. Conditional continuations
        5. Continuations with multiple antecedents
        6. Multiple continuations on a single antecedent
      6. Task Schedulers and UIs
      7. TaskFactory
        1. Creating your own task factories
      8. TaskCompletionSource
    5. Working with AggregateException
      1. Flatten and Handle
        1. Flatten
        2. Handle
    6. Concurrent Collections
      1. IProducerConsumerCollection<T>
      2. ConcurrentBag<T>
      3. BlockingCollection<T>
        1. Leveraging TaskCompletionSource
    7. SpinLock and SpinWait
      1. SpinLock
      2. SpinWait
        1. Why we need SpinWait
        2. How to use SpinWait
        3. How SpinWait works
        4. Lock-free updates with SpinWait and Interlocked.CompareExchange
  26. 23. Asynchronous Methods
    1. Why Asynchronous Methods Exist
    2. Asynchronous Method Signatures
      1. IAsyncResult
    3. Asynchronous Methods Versus Asynchronous Delegates
    4. Using Asynchronous Methods
    5. Asynchronous Methods and Tasks
    6. Writing Asynchronous Methods
    7. Fake Asynchronous Methods
    8. Alternatives to Asynchronous Methods
  27. 24. Application Domains
    1. Application Domain Architecture
    2. Creating and Destroying Application Domains
    3. Using Multiple Application Domains
    4. Using DoCallBack
    5. Monitoring Application Domains
    6. Domains and Threads
    7. Sharing Data Between Domains
      1. Sharing Data via Slots
      2. Intra-Process Remoting
      3. Isolating Types and Assemblies
        1. Type discovery
  28. 25. Native and COM Interoperability
    1. Calling into Native DLLs
    2. Type Marshaling
      1. Marshaling Common Types
      2. Marshaling Classes and Structs
      3. In and Out Marshaling
    3. Callbacks from Unmanaged Code
    4. Simulating a C Union
    5. Shared Memory
    6. Mapping a Struct to Unmanaged Memory
      1. fixed and fixed {...}
    7. COM Interoperability
      1. The Purpose of COM
      2. The Basics of the COM Type System
        1. IUnknown and IDispatch
    8. Calling a COM Component from C#
      1. Optional Parameters and Named Arguments
      2. Implicit ref Parameters
      3. Indexers
      4. Dynamic Binding
    9. Embedding Interop Types
      1. Type Equivalence
    10. Primary Interop Assemblies
    11. Exposing C# Objects to COM
  29. 26. Regular Expressions
    1. Regular Expression Basics
      1. Compiled Regular Expressions
      2. RegexOptions
      3. Character Escapes
      4. Character Sets
    2. Quantifiers
      1. Greedy Versus Lazy Quantifiers
    3. Zero-Width Assertions
      1. Lookahead and Lookbehind
      2. Anchors
      3. Word Boundaries
    4. Groups
      1. Named Groups
    5. Replacing and Splitting Text
      1. MatchEvaluator Delegate
      2. Splitting Text
    6. Cookbook Regular Expressions
      1. Recipes
        1. Matching U.S. Social Security number/phone number
        2. Extracting “name = value” pairs (one per line)
        3. Strong password validation
        4. Lines of at least 80 characters
        5. Parsing dates/times (N/N/N H:M:S AM/PM)
        6. Matching Roman numerals
        7. Removing repeated words
        8. Word count
        9. Matching a Guid
        10. Parsing an XML/HTML tag
        11. Splitting a camel-cased word
        12. Obtaining a legal filename
        13. Escaping Unicode characters for HTML
        14. Unescaping characters in an HTTP query string
        15. Parsing Google search terms from a web stats log
    7. Regular Expressions Language Reference
  30. A. C# Keywords
  31. Index
  32. About the Authors
  33. Colophon
  34. Copyright

Product information

  • Title: C# 4.0 in a Nutshell, 4th Edition
  • Author(s): Joseph Albahari, Ben Albahari
  • Release date: February 2010
  • Publisher(s): O'Reilly Media, Inc.
  • ISBN: 9780596800956