You are previewing C# 5.0 in a Nutshell, 5th Edition.

C# 5.0 in a Nutshell, 5th Edition

Cover of C# 5.0 in a Nutshell, 5th Edition by Joseph Albahari... Published by O'Reilly Media, Inc.
  1. C# 5.0 in a Nutshell
  2. 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. Safari® Books Online
    7. How to Contact Us
    8. Acknowledgments
      1. Joseph Albahari
      2. Ben Albahari
  3. 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. C# and Windows Runtime
    8. What’s New in C# 5.0
    9. What’s New in C# 4.0
    10. What’s New in C# 3.0
  4. 2. C# Language Basics
    1. A First C# Program
      1. Compilation
    2. Syntax
      1. Identifiers and Keywords
      2. Literals, Punctuators, and Operators
    3. Type Basics
      1. Predefined Type Examples
      2. Custom Type Examples
      3. Conversions
      4. Value Types Versus Reference Types
      5. Predefined Type Taxonomy
    4. Numeric Types
      1. Numeric Literals
      2. Numeric Conversions
      3. Arithmetic Operators
      4. Increment and Decrement Operators
      5. Specialized Integral Operations
      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
    7. Arrays
      1. Default Element Initialization
      2. Multidimensional Arrays
      3. Simplified Array Initialization Expressions
      4. Bounds Checking
    8. Variables and Parameters
      1. The Stack and the Heap
      2. Definite Assignment
      3. Default Values
      4. Parameters
      5. var—Implicitly Typed Local Variables
    9. Expressions and Operators
      1. Primary Expressions
      2. Void Expressions
      3. Assignment Expressions
      4. Operator Precedence and Associativity
      5. Operator Table
    10. Statements
      1. Declaration Statements
      2. Expression Statements
      3. Selection Statements
      4. Iteration Statements
      5. Jump Statements
      6. Miscellaneous Statements
    11. Namespaces
      1. The using Directive
      2. Rules Within a Namespace
      3. Aliasing Types and Namespaces
      4. Advanced Namespace Features
  5. 3. Creating Types in C#
    1. Classes
      1. Fields
      2. Methods
      3. Instance Constructors
      4. Object Initializers
      5. The this Reference
      6. Properties
      7. Indexers
      8. Constants
      9. Static Constructors
      10. Static Classes
      11. Finalizers
      12. Partial Types and Methods
    2. Inheritance
      1. Polymorphism
      2. Casting and Reference Conversions
      3. Virtual Function Members
      4. Abstract Classes and Abstract Members
      5. Hiding Inherited Members
      6. Sealing Functions and Classes
      7. The base Keyword
      8. Constructors and Inheritance
      9. Overloading and Resolution
    3. The object Type
      1. 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
      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
      13. Contravariance
      14. C# Generics Versus C++ Templates
  6. 4. Advanced C#
    1. Delegates
      1. Writing Plug-in Methods with Delegates
      2. Multicast Delegates
      3. Instance Versus Static Method Targets
      4. Generic Delegate Types
      5. The Func and Action Delegates
      6. Delegates Versus Interfaces
      7. Delegate Compatibility
    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
    4. Anonymous Methods
    5. try Statements and Exceptions
      1. The catch Clause
      2. The finally Block
      3. Throwing Exceptions
      4. Key Properties of System.Exception
      5. Common Exception Types
      6. The TryXXX Method Pattern
      7. Alternatives to Exceptions
    6. Enumeration and Iterators
      1. Enumeration
      2. Collection Initializers
      3. Iterators
      4. Iterator Semantics
      5. Composing Sequences
    7. Nullable Types
      1. Nullable <T> Struct
      2. Operator Lifting
      3. bool? with & and | Operators
      4. Null Coalescing Operator
      5. Scenarios for Nullable Types
      6. 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
    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. Caller Info Attributes (C# 5)
    14. Unsafe Code and Pointers
      1. Pointer Basics
      2. Unsafe Code
      3. The fixed Statement
      4. The Pointer-to-Member Operator
      5. Arrays
      6. void*
      7. Pointers to Unmanaged Code
    15. Preprocessor Directives
      1. Conditional Attributes
      2. Pragma Warning
    16. XML Documentation
      1. Standard XML Documentation Tags
      2. User-Defined Tags
      3. Type or Member Cross-References
  7. 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. Concurrency and Asynchrony
      8. Streams and I/O
      9. Networking
      10. Serialization
      11. Assemblies, Reflection, and Attributes
      12. Dynamic Programming
      13. Security
      14. Advanced Threading
      15. Parallel Programming
      16. Application Domains
      17. Native and COM Interoperability
    2. Applied Technologies
      1. User Interface Technologies
      2. Backend Technologies
      3. Distributed System Technologies
  8. 6. Framework Fundamentals
    1. String and Text Handling
      1. Char
      2. String
      3. Comparing Strings
      4. StringBuilder
      5. Text Encodings and Unicode
    2. Dates and Times
      1. TimeSpan
      2. DateTime and DateTimeOffset
    3. Dates and Time Zones
      1. DateTime and Time Zones
      2. DateTimeOffset and Time Zones
      3. TimeZone and TimeZoneInfo
      4. Daylight Saving Time and DateTime
    4. Formatting and Parsing
      1. ToString and Parse
      2. Format Providers
    5. Standard Format Strings and Parsing Flags
      1. Numeric Format Strings
      2. NumberStyles
      3. Date/Time Format Strings
      4. DateTimeStyles
      5. Enum Format Strings
    6. Other Conversion Mechanisms
      1. Convert
      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
      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
      3. Equality and Custom Types
    13. Order Comparison
      1. IComparable
      2. < and >
      3. Implementing the IComparable Interfaces
    14. Utility Classes
      1. Console
      2. Environment
      3. Process
  9. 7. Collections
    1. Enumeration
      1. IEnumerable and IEnumerator
      2. IEnumerable<T> and IEnumerator<T>
      3. Implementing the Enumeration Interfaces
    2. The ICollection and IList Interfaces
      1. ICollection<T> and ICollection
      2. IList<T> and IList
      3. IReadOnlyList<T>
    3. The Array Class
      1. Construction and Indexing
      2. Enumeration
      3. Length and Rank
      4. Searching
      5. Sorting
      6. Reversing Elements
      7. Copying
      8. 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
      2. KeyedCollection<TKey,TItem> and DictionaryBase
      3. ReadOnlyCollection<T>
    7. Plugging in Equality and Order
      1. IEqualityComparer and EqualityComparer
      2. IComparer and Comparer
      3. StringComparer
      4. IStructuralEquatable and IStructuralComparable
  10. 8. LINQ Queries
    1. Getting Started
    2. Fluent Syntax
      1. Chaining Query Operators
      2. Composing Lambda Expressions
      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
      3. Wrapping Queries
    7. Projection Strategies
      1. Object Initializers
      2. Anonymous Types
      3. The let Keyword
    8. Interpreted Queries
      1. How Interpreted Queries Work
      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
      4. Associations
      5. Deferred Execution with L2S and EF
      6. DataLoadOptions
      7. Eager Loading in Entity Framework
      8. Updates
      9. API Differences Between L2S and EF
    10. Building Query Expressions
      1. Delegates Versus Expression Trees
      2. Expression Trees
  11. 9. LINQ Operators
    1. Overview
      1. Sequence→Sequence
      2. Sequence→Element or Value
      3. Void→Sequence
    2. Filtering
      1. Where
      2. Take and Skip
      3. TakeWhile and SkipWhile
      4. Distinct
    3. Projecting
      1. Select
      2. SelectMany
    4. Joining
      1. Join and GroupJoin
      2. The Zip Operator
    5. Ordering
      1. OrderBy, OrderByDescending, ThenBy, and ThenByDescending
    6. Grouping
      1. GroupBy
    7. Set Operators
      1. Concat and Union
      2. Intersect and Except
    8. Conversion Methods
      1. OfType and Cast
      2. ToArray, ToList, ToDictionary, and ToLookup
      3. AsEnumerable and AsQueryable
    9. Element Operators
      1. First, Last, and Single
      2. ElementAt
      3. DefaultIfEmpty
    10. Aggregation Methods
      1. Count and LongCount
      2. Min and Max
      3. Sum and Average
      4. Aggregate
    11. Quantifiers
      1. Contains and Any
      2. All and SequenceEqual
    12. Generation Methods
      1. Empty
      2. Range and Repeat
  12. 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
      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
    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
    8. Names and Namespaces
      1. Namespaces in XML
      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
  13. 11. Other XML Technologies
    1. XmlReader
      1. Reading Nodes
      2. Reading Elements
      3. Reading Attributes
      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
    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
    7. XSLT
  14. 12. Disposal and Garbage Collection
    1. IDisposable, Dispose, and Close
      1. Standard Disposal Semantics
      2. When to Dispose
      3. Opt-in Disposal
      4. Clearing Fields in Disposal
    2. Automatic Garbage Collection
      1. Roots
      2. Garbage Collection and WinRT
    3. Finalizers
      1. Calling Dispose from a Finalizer
      2. Resurrection
    4. How the Garbage Collector Works
      1. Optimization Techniques
      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
  15. 13. Diagnostics and Code Contracts
    1. Conditional Compilation
      1. Conditional Compilation Versus Static Variable Flags
      2. 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
    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
      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
  16. 14. Concurrency & Asynchrony
    1. Introduction
    2. Threading
      1. Creating a Thread
      2. Join and Sleep
      3. Blocking
      4. Local Versus Shared State
      5. Locking and Thread Safety
      6. Passing Data to a Thread
      7. Exception Handling
      8. Foreground Versus Background Threads
      9. Thread Priority
      10. Signaling
      11. Threading in Rich Client Applications
      12. Synchronization Contexts
      13. The Thread Pool
    3. Tasks
      1. Starting a Task
      2. Returning values
      3. Exceptions
      4. Continuations
      5. TaskCompletionSource
      6. Task.Delay
    4. Principles of Asynchrony
      1. Synchronous Versus Asynchronous Operations
      2. What is Asynchronous Programming?
      3. Asynchronous Programming and Continuations
      4. Why Language Support is Important
    5. Asynchronous Functions in C# 5.0
      1. Awaiting
      2. Writing Asynchronous Functions
      3. Asynchronous Lambda Expressions
      4. Asynchronous Methods in WinRT
      5. Asynchrony and Synchronization Contexts
      6. Optimizations
    6. Asynchronous Patterns
      1. Cancellation
      2. Progress Reporting
      3. The Task-based Asynchronous Pattern (TAP)
      4. Task Combinators
    7. Obsolete Patterns
      1. Asynchronous Programming Model (APM)
      2. Event-Based Asynchronous Pattern (EAP)
      3. BackgroundWorker
  17. 15. 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
      8. MemoryStream
      9. PipeStream
      10. BufferedStream
    3. Stream Adapters
      1. Text Adapters
      2. Binary Adapters
      3. Closing and Disposing Stream Adapters
    4. Compression Streams
      1. Compressing in Memory
    5. Working with Zip Files
    6. File and Directory Operations
      1. The File Class
      2. The Directory Class
      3. FileInfo and DirectoryInfo
      4. Path
      5. Special Folders
      6. Querying Volume Information
      7. Catching Filesystem Events
    7. File I/O in Windows Runtime
      1. Working with Directories
      2. Working with Files
      3. Isolated Storage in Metro Apps
    8. Memory-Mapped Files
      1. Memory-Mapped Files and Random File I/O
      2. Memory-Mapped Files and Shared Memory
      3. Working with View Accessors
    9. Isolated Storage
      1. Isolation Types
      2. Reading and Writing Isolated Storage
      3. Store Location
      4. Enumerating Isolated Storage
  18. 16. Networking
    1. Network Architecture
    2. Addresses and Ports
    3. URIs
    4. Client-Side Classes
      1. WebClient
      2. WebRequest and WebResponse
      3. HttpClient
      4. Proxies
      5. Authentication
      6. Exception Handling
    5. Working with HTTP
      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 with TCP
    11. Receiving POP3 Mail with TCP
    12. TCP in Windows Runtime
  19. 17. Serialization
    1. Serialization Concepts
      1. Serialization Engines
      2. Formatters
      3. Explicit Versus Implicit Serialization
    2. The Data Contract Serializer
      1. DataContractSerializer Versus NetDataContractSerializer
      2. Using the Serializers
      3. Serializing Subclasses
      4. Object References
      5. Version Tolerance
      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
      2. Subclasses and Child Objects
      3. Serializing Collections
      4. IXmlSerializable
  20. 18. Assemblies
    1. What’s in an Assembly
      1. The Assembly Manifest
      2. The 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
      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
      4. Satellite Assemblies
      5. Cultures and Subcultures
    7. Resolving and Loading Assemblies
      1. Assembly and Type Resolution Rules
      2. AssemblyResolve
      3. Loading Assemblies
    8. Deploying Assemblies Outside the Base Folder
    9. Packing a Single-File Executable
      1. Selective Patching
    10. Working with Unreferenced Assemblies
  21. 19. Reflection and Metadata
    1. Reflecting and Activating Types
      1. Obtaining a Type
      2. 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
      6. Using Delegates for Performance
      7. Accessing Nonpublic Members
      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
      2. Emitting Fields and Properties
      3. Emitting 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. 20. Dynamic Programming
    1. The Dynamic Language Runtime
    2. Numeric Type Unification
    3. Dynamic Member Overload Resolution
      1. Simplifying the Visitor Pattern
      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. 21. Security
    1. Permissions
      1. CodeAccessPermission and PrincipalPermission
      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
      1. How the Transparency Model Works
      2. How to Write APTCA Libraries with Transparency
      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. 22. Advanced Threading
    1. Synchronization Overview
    2. Exclusive Locking
      1. The lock Statement
      2. Monitor.Enter and Monitor.Exit
      3. Choosing the Synchronization Object
      4. When to Lock
      5. Locking and Atomicity
      6. Nested Locking
      7. Deadlocks
      8. Performance
      9. Mutex
    3. Locking and Thread Safety
      1. Thread Safety and .NET Framework Types
      2. Thread Safety in Application Servers
      3. Immutable Objects
    4. Non-Exclusive Locking
      1. Semaphore
      2. Reader/Writer Locks
    5. Signaling with Event Wait Handles
      1. AutoResetEvent
      2. ManualResetEvent
      3. CountdownEvent
      4. Creating a Cross-Process EventWaitHandle
      5. Wait Handles and Continuations
      6. Converting Wait Handles to Tasks
      7. WaitAny, WaitAll, and SignalAndWait
    6. The Barrier Class
    7. Lazy Initialization
      1. Lazy<T>
      2. LazyInitializer
    8. Thread-Local Storage
      1. [ThreadStatic]
      2. ThreadLocal<T>
      3. GetData and SetData
    9. Interrupt and Abort
    10. Suspend and Resume
    11. Timers
      1. Multithreaded Timers
      2. Single-Threaded Timers
  25. 23. 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
      5. Functional Purity
      6. Setting the Degree of Parallelism
      7. Cancellation
      8. Optimizing PLINQ
    3. The Parallel Class
      1. Parallel.Invoke
      2. Parallel.For and Parallel.ForEach
    4. Task Parallelism
      1. Creating and Starting Tasks
      2. Waiting on Multiple Tasks
      3. Canceling Tasks
      4. Continuations
      5. Task Schedulers
      6. TaskFactory
    5. Working with AggregateException
      1. Flatten and Handle
    6. Concurrent Collections
      1. IProducerConsumerCollection<T>
      2. ConcurrentBag<T>
    7. BlockingCollection<T>
      1. Writing a Producer/Consumer Queue
  26. 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
  27. 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
    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
  28. 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
    7. Regular Expressions Language Reference
  29. Index
  30. About the Authors
  31. Colophon
  32. Copyright

Chapter 1. Introducing C# and the .NET Framework

C# is a general-purpose, type-safe, object-oriented programming language. The goal of the language is programmer productivity. To this end, the language balances simplicity, expressiveness, and performance. The chief architect of the language since its first version is Anders Hejlsberg (creator of Turbo Pascal and architect of Delphi). The C# language is platform-neutral, but it was written to work well with the Microsoft .NET Framework.

Object Orientation

C# is a rich implementation of the object-orientation paradigm, which includes encapsulation, inheritance, and polymorphism. Encapsulation means creating a boundary around an object, to separate its external (public) behavior from its internal (private) implementation details. The distinctive features of C# from an object-oriented perspective are:

Unified type system

The fundamental building block in C# is an encapsulated unit of data and functions called a type. C# has a unified type system, where all types ultimately share a common base type. This means that all types, whether they represent business objects or are primitive types such as numbers, share the same basic set of functionality. For example, an instance of any type can be converted to a string by calling its ToString method.

Classes and interfaces

In a traditional object-oriented paradigm, the only kind of type is a class. In C#, there are several other kinds of types, one of which is an interface. An interface is like a class, except that it only describes members. The implementation for those members comes from types that implement the interface. Interfaces are particularly useful in scenarios where multiple inheritance is required (unlike languages such as C++ and Eiffel, C# does not support multiple inheritance of classes).

Properties, methods, and events

In the pure object-oriented paradigm, all functions are methods (this is the case in Smalltalk). In C#, methods are only one kind of function member, which also includes properties and events (there are others, too). Properties are function members that encapsulate a piece of an object’s state, such as a button’s color or a label’s text. Events are function members that simplify acting on object state changes.

Type Safety

C# is primarily a type-safe language, meaning that instances of types can interact only through protocols they define, thereby ensuring each type’s internal consistency. For instance, C# prevents you from interacting with a string type as though it were an integer type.

More specifically, C# supports static typing, meaning that the language enforces type safety at compile time. This is in addition to type safety being enforced at runtime.

Static typing eliminates a large class of errors before a program is even run. It shifts the burden away from runtime unit tests onto the compiler to verify that all the types in a program fit together correctly. This makes large programs much easier to manage, more predictable, and more robust. Furthermore, static typing allows tools such as IntelliSense in Visual Studio to help you write a program, since it knows for a given variable what type it is, and hence what methods you can call on that variable.


C# also allows parts of your code to be dynamically typed via the dynamic keyword (introduced in C# 4). However, C# remains a predominantly statically typed language.

C# is also called a strongly typed language because its type rules (whether enforced statically or at runtime) are very strict. For instance, you cannot call a function that’s designed to accept an integer with a floating-point number, unless you first explicitly convert the floating-point number to an integer. This helps prevent mistakes.

Strong typing also plays a role in enabling C# code to run in a sandbox—an environment where every aspect of security is controlled by the host. In a sandbox, it is important that you cannot arbitrarily corrupt the state of an object by bypassing its type rules.

Memory Management

C# relies on the runtime to perform automatic memory management. The Common Language Runtime has a garbage collector that executes as part of your program, reclaiming memory for objects that are no longer referenced. This frees programmers from explicitly deallocating the memory for an object, eliminating the problem of incorrect pointers encountered in languages such as C++.

C# does not eliminate pointers: it merely makes them unnecessary for most programming tasks. For performance-critical hotspots and interoperability, pointers may be used, but they are permitted only in blocks that are explicitly marked unsafe.

Platform Support

C# is typically used for writing code that runs on Windows platforms. Although Microsoft standardized the C# language through ECMA, the total amount of resources (both inside and outside of Microsoft) dedicated to supporting C# on non-Windows platforms is relatively small. This means that languages such as Java are sensible choices when multiplatform support is of primary concern. Having said this, C# can be used to write cross-platform code in the following scenarios:

  • C# code may run on the server and dish up HTML that can run on any platform. This is precisely the case for ASP.NET.

  • C# code may run on a runtime other than the Microsoft Common Language Runtime. The most notable example is the Mono project, which has its own C# compiler and runtime, running on Linux, Solaris, Mac OS X, and Windows.

  • C# code may run on a host that supports Microsoft Silverlight (supported for Windows and Mac OS X). This technology is analogous to Adobe’s Flash Player.

C#’s Relationship with the CLR

C# depends on a runtime equipped with a host of features such as automatic memory management and exception handling. The design of C# closely maps to the design of Microsoft’s Common Language Runtime (CLR), which provides these runtime features (although C# is technically independent of the CLR). Furthermore, the C# type system maps closely to the CLR type system (e.g., both share the same definitions for predefined types).

The CLR and .NET Framework

The .NET Framework consists of the CLR plus a vast set of libraries. The libraries consist of core libraries (which this book is concerned with) and applied libraries, which depend on the core libraries. Figure 1-1 is a visual overview of those libraries (and also serves as a navigational aid to the book).

Topics covered in this book and the chapters in which they are found. Topics not covered are shown outside the large circle.

Figure 1-1. Topics covered in this book and the chapters in which they are found. Topics not covered are shown outside the large circle.

The CLR is the runtime for executing managed code. C# is one of several managed languages that get compiled into managed code. Managed code is packaged into an assembly, in the form of either an executable file (an .exe) or a library (a .dll), along with type information, or metadata.

Managed code is represented in Intermediate Language or IL. When the CLR loads an assembly, it converts the IL into the native code of the machine, such as x86. This conversion is done by the CLR’s JIT (Just-In-Time) compiler. An assembly retains almost all of the original source language constructs, which makes it easy to inspect and even generate code dynamically.


Red Gate’s .NET Reflector application is an invaluable tool for examining the contents of an assembly. You can also use it as a decompiler.

The CLR performs as a host for numerous runtime services. Examples of these services include memory management, the loading of libraries, and security services. The CLR is language-neutral, allowing developers to build applications in multiple languages (e.g., C#, Visual Basic .NET, Managed C++, Delphi.NET, Chrome .NET, and J#).

The .NET Framework contains libraries for writing just about any Windows- or web-based application. Chapter 5 gives an overview of the .NET Framework libraries.

C# and Windows Runtime

C# 5.0 also interoperates with Windows Runtime (WinRT) libraries. WinRT is an execution interface and runtime environment for accessing libraries in a language-neutral and object-oriented fashion. It ships with Windows 8 and is (in part) an enhanced version of Microsoft’s Component Object Model or COM (see Chapter 25).

Windows 8 ships with a set of unmanaged WinRT libraries which serve as a framework for touch-enabled Metro-style applications delivered through Microsoft’s application store. (The term WinRT also refers to these libraries.) Being WinRT, the libraries can easily be consumed not only from C# and VB, but C++ and JavaScript.


Some WinRT libraries can also be consumed in normal non-tablet applications. However, taking a dependency on WinRT gives your application a minimum OS requirement of Windows 8. (And into the future, taking a dependency on the next version of WinRT would give your program a minimum OS requirement of Windows 9.)

The WinRT libraries support the new Metro user interface (for writing immersive touch-first applications), mobile device-specific features (sensors, text messaging and so on), and a range of core functionality that overlaps with parts of the .NET Framework. Because of this overlap, Visual Studio includes a reference profile (a set of .NET reference assemblies) for Metro projects that hides the portions of the .NET Framework that overlap with WinRT. This profile also hides large portions of the .NET Framework considered unnecessary for tablet apps (such as accessing a database). Microsoft’s application store, which controls the distribution of software to consumer devices, rejects any program that attempts to access a hidden type.


A reference assembly exists purely to compile against and may have a restricted set of types and members. This allows developers to install the full .NET Framework on their machines while coding certain projects as though they had only a subset. The actual functionality comes at runtime from assemblies in the Global Assembly Cache (see Chapter 18) which may superset the reference assemblies.

Hiding most of the .NET Framework eases the learning curve for developers new to the Microsoft platform, although there are two more important goals:

  • It sandboxes applications (restricts functionality to reduce the impact of malware). For instance, arbitrary file access is forbidden, and there the ability to start or communicate with other programs on the computer is extremely restricted.

  • It allows low-powered Metro-only tablets to ship with a reduced .NET Framework (Metro profile), lowering the OS footprint.

What distinguishes WinRT from ordinary COM is that WinRT projects its libraries into a multitude of languages, namely C#, VB, C++ and JavaScript, so that each language sees WinRT types (almost) as though they were written especially for it. For example, WinRT will adapt capitalization rules to suit the standards of the target language, and will even remap some functions and interfaces. WinRT assemblies also ship with rich metadata in .winmd files which have the same format as .NET assembly files, allowing transparent consumption without special ritual. In fact, you might even be unaware that you’re using WinRT rather than .NET types, aside of namespace differences. (Another clue is that WinRT types are subject to COM-style restrictions; for instance, they offer limited support for inheritance and generics.)


WinRT/Metro does not supersede the full .NET Framework. The latter is still recommended (and necessary) for standard desktop and server-side development, and has the following advantages:

  • Programs are not restricted to running in a sandbox.

  • Programs can use the entire .NET Framework and any third-party library.

  • Application distribution does not rely on the Windows Store.

  • Applications can target the latest Framework version without requiring users to have the latest OS version.

What’s New in C# 5.0

C# 5.0’s big new feature is support for asynchronous functions via two new keywords, async and await. Asynchronous functions enable asynchronous continuations, which make it easier to write responsive and thread-safe rich-client applications. They also make it easy to write highly concurrent and efficient I/O-bound applications that don’t tie up a thread resource per operation.

We cover asynchronous functions in detail in Chapter 14.

What’s New in C# 4.0

The features new to C# 4.0 were:

  • Dynamic binding

  • Optional parameters and named arguments

  • Type variance with generic interfaces and delegates

  • COM interoperability improvements

Dynamic binding (Chapters 4 and 20) defers binding—the process of resolving types and members—from compile time to runtime and is useful in scenarios that would otherwise require complicated reflection code. Dynamic binding is also useful when interoperating with dynamic languages and COM components.

Optional parameters (Chapter 2) allow functions to specify default parameter values so that callers can omit arguments and named arguments allow a function caller to identify an argument by name rather than position.

Type variance rules were relaxed in C# 4.0 (Chapters 3 and 4), such that type parameters in generic interfaces and generic delegates can be marked as covariant or contravariant, allowing more natural type conversions.

COM interoperability (Chapter 25) was enhanced in C# 4.0 in three ways. First, arguments can be passed by reference without the ref keyword (particularly useful in conjunction with optional parameters). Second, assemblies that contain COM interop types can be linked rather than referenced. Linked interop types support type equivalence, avoiding the need for Primary Interop Assemblies and putting an end to versioning and deployment headaches. Third, functions that return COM-Variant types from linked interop types are mapped to dynamic rather than object, eliminating the need for casting.

What’s New in C# 3.0

The features added to C# 3.0 were mostly centered on Language Integrated Query capabilities or LINQ for short. LINQ enables queries to be written directly within a C# program and checked statically for correctness, and query both local collections (such as lists or XML documents) or remote data sources (such as a database). The C# 3.0 features added to support LINQ comprised implicitly typed local variables, anonymous types, object initializers, lambda expressions, extension methods, query expressions and expression trees.

Implicitly typed local variables (var keyword, Chapter 2) let you omit the variable type in a declaration statement, allowing the compiler to infer it. This reduces clutter as well as allowing anonymous types (Chapter 4), which are simple classes created on the fly that are commonly used in the final output of LINQ queries. Arrays can also be implicitly typed (Chapter 2).

Object initializers (Chapter 3) simplify object construction by allowing properties to be set inline after the constructor call. Object initializers work with both named and anonymous types.

Lambda expressions (Chapter 4) are miniature functions created by the compiler on the fly, and are particularly useful in “fluent” LINQ queries (Chapter 8).

Extension methods (Chapter 4) extend an existing type with new methods (without altering the type’s definition), making static methods feel like instance methods. LINQ’s query operators are implemented as extension methods.

Query expressions (Chapter 8) provide a higher-level syntax for writing LINQ queries that can be substantially simpler when working with multiple sequences or range variables.

Expression trees (Chapter 8) are miniature code DOMs (Document Object Models) that describe lambda expressions assigned to the special type Expression<TDelegate>. Expression trees make it possible for LINQ queries to execute remotely (e.g., on a database server) because they can be introspected and translated at runtime (e.g., into a SQL statement).

C# 3.0 also added automatic properties and partial methods.

Automatic properties (Chapter 3) cut the work in writing properties that simply get/set a private backing field by having the compiler do that work automatically. Partial methods (Chapter 3) let an auto-generated partial class provide customizable hooks for manual authoring which “melt away” if unused.

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