C# 4.0 in a Nutshell: The Definitive Reference

This document was uploaded by one of our users. The uploader already confirmed that they had the permission to publish it. If you are author/publisher or own the copyright of this documents, please report to us by using this DMCA report form.

Simply click on the Download Book button.

Yes, Book downloads on Ebookily are 100% Free.

Sometimes the book is free on Amazon As well, so go ahead and hit "Search on Amazon"

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

Author(s): Joseph Albahari; Ben Albahari
Edition: 4
Publisher: O'Reilly Media
Year: 2010

Language: English
Pages: 1033

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