You are previewing Essential C# 6.0.
O'Reilly logo
Essential C# 6.0

Book Description

“ Welcome to one of the greatest collaborations you could dream of in the world of C# books—and probably far beyond!”

—From the Foreword by Mads Torgersen, C# Program Manager, Microsoft

Essential C# 6.0 is a well-organized, no-fluff guide to the latest versions of C# for programmers at all levels of experience. Fully updated to reflect new C# 6.0 and .NET 4.6 features and patterns, it will help you write C# code that’s simple, powerful, robust, secure, and maintainable.

This book’s authors are world-class C# experts: long-time Microsoft MVP and Regional Director Mark Michaelis and Eric Lippert, formerly principal developer on Microsoft’s C# compiler team. Together, they cover the entire language, illustrating key constructs with succinct examples and offering a complete foundation for successful C# development.

Essential C# 6.0 makes it easy to program with any version of C#, whether you’re creating new code or maintaining existing systems. Separate indexes for C# versions 4, 5, and 6 help you quickly find version-specific answers with accompanying visual indicators that help you identify which language innovations will work when. This edition also includes a set of best-practice C# Coding Guidelines updated to leverage C# 6.0 constructs.

Coverage includes

  • Mastering C# data types, operators, control flow, methods, and parameters

  • Using C# object-oriented constructs, including classes, inheritance, interfaces, and more—all with the significantly simplified syntax of C# 6.0

  • Working with well-formed value and reference types

  • Implementing reliable, effective exception handling

  • Reducing code complexity with generics, delegates, lambda expressions, and events (including a simplified C# 6.0 syntax for triggering events)

  • Learning dynamic programming with reflection and attributes

  • Querying diverse data collections using LINQ with query expressions

  • Creating custom collections that operate against business objects

  • Using collection interfaces and standard query operators to access .NET collections

  • Understanding the Common Language Infrastructure and C# in the context of .NET 4.6

  • Taking advantage of declarative programming, embedded metadata, reflection, and attributes

  • Mastering multithreading and synchronization, including the new async/await paradigm

  • Using P/Invoke, pointers, and direct memory manipulation to interoperate with other languages

  • Understanding how C# programs relate to the underlying runtime

  • For Qualified Instructors

    An instructor’s guide, exercises, and a slide deck are available to support your courses.

    Table of Contents

    1. About This eBook
    2. Title Page
    3. Copyright Page
    4. Dedication Page
    5. Contents at a Glance
    6. Contents
    7. Figures
    8. Tables
    9. Foreword
    10. Preface
      1. Target Audience for This Book
      2. Features of This Book
        1. C# Coding Guidelines
        2. Code Samples
        3. Mind Maps
        4. Helpful Notes
      3. How This Book Is Organized
    11. Acknowledgments
    12. About the Authors
    13. 1. Introducing C#
      1. Hello, World
        1. Compiling and Running the Application
      2. C# Syntax Fundamentals
        1. C# Keywords
        2. Identifiers
        3. Type Definition
        4. Main
        5. Statements and Statement Delimiters
        6. Whitespace
        7. Working with Variables
        8. Data Types
        9. Declaring a Variable
        10. Assigning a Variable
        11. Using a Variable
      3. Console Input and Output
        1. Getting Input from the Console
        2. Writing Output to the Console
        3. Comments
        4. Application Programming Interface
        5. Managed Execution and the Common Language Infrastructure
        6. C# and .NET Versioning
        7. Common Intermediate Language and ILDASM
      4. Summary
    14. 2. Data Types
      1. Fundamental Numeric Types
        1. Integer Types
        2. Floating-Point Types (float, double)
        3. Decimal Type
        4. Literal Values
      2. More Fundamental Types
        1. Boolean Type (bool)
        2. Character Type (char)
        3. Strings
      3. null and void
        1. null
        2. The void “Type”
      4. Categories of Types
        1. Value Types
        2. Reference Types
      5. Nullable Modifier
      6. Conversions between Data Types
        1. Explicit Cast
        2. Implicit Conversion
        3. Type Conversion without Casting
      7. Arrays
        1. Declaring an Array
        2. Instantiating and Assigning Arrays
        3. Using an Array
        4. Strings As Arrays
        5. Common Array Errors
      8. Summary
    15. 3. Operators and Control Flow
      1. Operators
        1. Plus and Minus Unary Operators (+, -)
        2. Arithmetic Binary Operators (+, -, *, /, %)
        3. Compound Assignment Operators (+=, -=, *=, /=, %=)
        4. Increment and Decrement Operators (++, --)
        5. Constant Expressions and Constant Locals
      2. Introducing Flow Control
        1. if Statement
        2. Nested if
      3. Code Blocks ({})
      4. Code Blocks, Scopes, and Declaration Spaces
      5. Boolean Expressions
        1. Relational and Equality Operators
        2. Logical Boolean Operators
        3. Logical Negation Operator (!)
        4. Conditional Operator (?:)
        5. Null-Coalescing Operator (??)
        6. Null-Conditional Operator (?.)
      6. Bitwise Operators (<<, >>, |, &, ^, ~)
        1. Shift Operators (<<, >>, <<=, >>=)
        2. Bitwise Operators (&, |, ^)
        3. Bitwise Compound Assignment Operators (&=, |=, ^=)
        4. Bitwise Complement Operator (~)
      7. Control Flow Statements, Continued
        1. The while and do/while Loops
        2. The for Loop
        3. The foreach Loop
        4. The switch Statement
      8. Jump Statements
        1. The break Statement
        2. The continue Statement
        3. The goto Statement
      9. C# Preprocessor Directives
        1. Excluding and Including Code (#if, #elif, #else, #endif)
        2. Defining Preprocessor Symbols (#define, #undef)
        3. Emitting Errors and Warnings (#error, #warning)
        4. Turning Off Warning Messages (#pragma)
        5. nowarn:<warn list> Option
        6. Specifying Line Numbers (#line)
        7. Hints for Visual Editors (#region, #endregion)
      10. Summary
    16. 4. Methods and Parameters
      1. Calling a Method
        1. Namespaces
        2. Type Name
        3. Scope
        4. Method Name
        5. Parameters and Arguments
        6. Method Return Values
        7. Statement versus Method Call
      2. Declaring a Method
        1. Formal Parameter Declaration
        2. Method Return Type Declaration
        3. Expression Bodied Methods
      3. The using Directive
        1. The using static Directive
        2. Aliasing
      4. Returns and Parameters on Main()
      5. Advanced Method Parameters
        1. Value Parameters
        2. Reference Parameters (ref)
        3. Output Parameters (out)
        4. Parameter Arrays (params)
      6. Recursion
      7. Method Overloading
      8. Optional Parameters
      9. Basic Error Handling with Exceptions
        1. Trapping Errors
        2. Reporting Errors Using a throw Statement
      10. Summary
    17. 5. Classes
      1. Declaring and Instantiating a Class
      2. Instance Fields
        1. Declaring an Instance Field
        2. Accessing an Instance Field
      3. Instance Methods
      4. Using the this Keyword
      5. Access Modifiers
      6. Properties
        1. Declaring a Property
        2. Automatically Implemented Properties
        3. Property and Field Guidelines
        4. Using Properties with Validation
        5. Read-Only and Write-Only Properties
        6. Properties As Virtual Fields
        7. Access Modifiers on Getters and Setters
        8. Properties and Method Calls Not Allowed As ref or out Parameter Values
      7. Constructors
        1. Declaring a Constructor
        2. Default Constructors
        3. Object Initializers
        4. Overloading Constructors
        5. Constructor Chaining: Calling Another Constructor Using this
      8. Static Members
        1. Static Fields
        2. Static Methods
        3. Static Constructors
        4. Static Properties
        5. Static Classes
      9. Extension Methods
      10. Encapsulating the Data
        1. const
        2. readonly
      11. Nested Classes
      12. Partial Classes
        1. Defining a Partial Class
        2. Partial Methods
      13. Summary
    18. 6. Inheritance
      1. Derivation
        1. Casting between Base and Derived Types
        2. private Access Modifier
        3. protected Access Modifier
        4. Extension Methods
        5. Single Inheritance
        6. Sealed Classes
      2. Overriding the Base Class
        1. virtual Modifier
        2. new Modifier
        3. sealed Modifier
        4. base Member
        5. Constructors
      3. Abstract Classes
      4. All Classes Derive from System.Object
      5. Verifying the Underlying Type with the is Operator
      6. Conversion Using the as Operator
      7. Summary
    19. 7. Interfaces
      1. Introducing Interfaces
      2. Polymorphism through Interfaces
      3. Interface Implementation
        1. Explicit Member Implementation
        2. Implicit Member Implementation
        3. Explicit versus Implicit Interface Implementation
      4. Converting between the Implementing Class and Its Interfaces
      5. Interface Inheritance
      6. Multiple Interface Inheritance
      7. Extension Methods on Interfaces
      8. Implementing Multiple Inheritance via Interfaces
      9. Versioning
      10. Interfaces Compared with Classes
      11. Interfaces Compared with Attributes
      12. Summary
    20. 8. Value Types
      1. Structs
        1. Initializing Structs
        2. Using the default Operator
        3. Inheritance and Interfaces with Value Types
      2. Boxing
      3. Enums
        1. Type Compatibility between Enums
        2. Converting between Enums and Strings
        3. Enums As Flags
      4. Summary
    21. 9. Well-Formed Types
      1. Overriding object Members
        1. Overriding ToString()
        2. Overriding GetHashCode()
        3. Overriding Equals()
      2. Operator Overloading
        1. Comparison Operators (==, !=, <, >, <=, >=)
        2. Binary Operators (+, -, *, /, %, &, |, ^, <<, >>)
        3. Combining Assignment with Binary Operators (+=, -=, *=, /=, %=, &=, ...)
        4. Conditional Logical Operators (&&, ||)
        5. Unary Operators (+, -, !, ~, ++, --, true, false)
        6. Conversion Operators
        7. Guidelines for Conversion Operators
      3. Referencing Other Assemblies
        1. Changing the Assembly Target
        2. Referencing an Assembly
      4. Defining Namespaces
        1. Namespace Alias Qualifier
      5. XML Comments
        1. Associating XML Comments with Programming Constructs
        2. Generating an XML Documentation File
      6. Garbage Collection
        1. Weak References
      7. Resource Cleanup
        1. Finalizers
        2. Deterministic Finalization with the using Statement
        3. Garbage Collection, Finalization, and IDisposable
      8. Lazy Initialization
      9. Summary
    22. 10. Exception Handling
      1. Multiple Exception Types
      2. Catching Exceptions
        1. Rethrowing an Existing Exception
      3. General Catch Block
      4. Guidelines for Exception Handling
      5. Defining Custom Exceptions
      6. Rethrowing a Wrapped Exception
      7. Summary
    23. 11. Generics
      1. C# without Generics
      2. Introducing Generic Types
        1. Using a Generic Class
        2. Defining a Simple Generic Class
        3. Benefits of Generics
        4. Type Parameter Naming Guidelines
        5. Generic Interfaces and Structs
        6. Defining a Constructor and a Finalizer
        7. Specifying a Default Value
        8. Multiple Type Parameters
        9. Arity in Abundance
        10. Nested Generic Types
      3. Constraints
        1. Interface Constraints
        2. Class Type Constraints
        3. struct/class Constraints
        4. Multiple Constraints
        5. Constructor Constraints
        6. Constraint Inheritance
      4. Generic Methods
        1. Generic Method Type Inference
        2. Specifying Constraints
      5. Covariance and Contravariance
        1. Enabling Covariance with the out Type Parameter Modifier in C# 4.0
        2. Enabling Contravariance with the in Type Parameter Modifier in C# 4.0
        3. Support for Unsafe Covariance in Arrays
      6. Generic Internals
      7. Summary
    24. 12. Delegates and Lambda Expressions
      1. Introducing Delegates
        1. Defining the Scenario
        2. Delegate Data Types
        3. Declaring a Delegate Type
        4. Instantiating a Delegate
      2. Lambda Expressions
        1. Statement Lambdas
        2. Expression Lambdas
      3. Anonymous Methods
      4. General-Purpose Delegates: System.Func and System.Action
        1. Delegates Do Not Have Structural Equality
        2. Outer Variables
        3. Expression Trees
      5. Summary
    25. 13. Events
      1. Coding the Observer Pattern with Multicast Delegates
        1. Defining Subscriber Methods
        2. Defining the Publisher
        3. Hooking up the Publisher and Subscribers
        4. Invoking a Delegate
        5. Check for null
        6. Delegate Operators
        7. Sequential Invocation
        8. Error Handling
        9. Method Returns and Pass-by-Reference
      2. Events
        1. Why Events?
        2. Declaring an Event
        3. Coding Conventions
        4. Generics and Delegates
        5. Customizing the Event Implementation
      3. Summary
    26. 14. Collection Interfaces with Standard Query Operators
      1. Anonymous Types and Implicitly Typed Local Variables
        1. Anonymous Types
        2. Implicitly Typed Local Variables (var)
        3. More about Anonymous Types and Implicit Local Variables
      2. Collection Initializers
      3. What Makes a Class a Collection: IEnumerable<T>
        1. foreach with Arrays
        2. foreach with IEnumerable<T>
        3. Do Not Modify Collections during foreach Iteration
      4. Standard Query Operators
        1. Filtering with Where()
        2. Projecting with Select()
        3. Counting Elements with Count()
        4. Deferred Execution
        5. Sorting with OrderBy() and ThenBy()
        6. Performing an Inner Join with Join()
        7. Grouping Results with GroupBy()
        8. Implementing a One-to-Many Relationship with GroupJoin()
        9. Calling SelectMany()
        10. More Standard Query Operators
      5. Summary
    27. 15. LINQ with Query Expressions
      1. Introducing Query Expressions
        1. Projection
        2. Filtering
        3. Sorting
        4. The let Clause
        5. Grouping
        6. Query Continuation with into
        7. “Flattening” Sequences of Sequences with Multiple from Clauses
      2. Query Expressions Are Just Method Invocations
      3. Summary
    28. 16. Building Custom Collections
      1. More Collection Interfaces
        1. IList<T> versus IDictionary<TKey, TValue>
        2. ICollection<T>
      2. Primary Collection Classes
        1. List Collections: List<T>
        2. Total Ordering
        3. Searching a List<T>
        4. Dictionary Collections: Dictionary<TKey, TValue>
        5. Sorted Collections: SortedDictionary<TKey, TValue> and SortedList<T>
        6. Stack Collections: Stack<T>
        7. Queue Collections: Queue<T>
        8. Linked Lists: LinkedList<T>
      3. Providing an Indexer
      4. Returning Null or an Empty Collection
      5. Iterators
        1. Defining an Iterator
        2. Iterator Syntax
        3. Yielding Values from an Iterator
        4. Iterators and State
        5. More Iterator Examples
        6. Placing a yield return within a Loop
        7. Canceling Further Iteration: yield break
        8. Creating Multiple Iterators in a Single Class
        9. yield Statement Requirements
      6. Summary
    29. 17. Reflection, Attributes, and Dynamic Programming
      1. Reflection
        1. Accessing Metadata Using System.Type
        2. Member Invocation
        3. Reflection on Generic Types
      2. nameof Operator
      3. Attributes
        1. Custom Attributes
        2. Looking for Attributes
        3. Initializing an Attribute through a Constructor
        4. System.AttributeUsageAttribute
        5. Named Parameters
      4. Programming with Dynamic Objects
        1. Invoking Reflection Using dynamic
        2. dynamic Principles and Behaviors
        3. Why Dynamic Binding?
        4. Static Compilation versus Dynamic Programming
        5. Implementing a Custom Dynamic Object
      5. Summary
    30. 18. Multithreading
      1. Multithreading Basics
      2. Working with System.Threading
        1. Asynchronous Operations with System.Threading.Thread
        2. Thread Management
        3. Do Not Put Threads to Sleep in Production Code
        4. Do Not Abort Threads in Production Code
        5. Thread Pooling
      3. Asynchronous Tasks
        1. From Thread to Task
        2. Introducing Asynchronous Tasks
        3. Task Continuation
        4. Unhandled Exception Handling on Task with AggregateException
      4. Canceling a Task
        1. Task.Run(): A Shortcut and Simplification to Task.Factory.StartNew()
        2. Long-Running Tasks
        3. Tasks Are Disposable
      5. The Task-Based Asynchronous Pattern
        1. Synchronously Invoking a High-Latency Operation
        2. Asynchronously Invoking a High-Latency Operation Using the TPL
        3. The Task-Based Asynchronous Pattern with async and await
        4. Asynchronous Lambdas
        5. Task Schedulers and the Synchronization Context
        6. async/await with the Windows UI
        7. await Operators
      6. Executing Loop Iterations in Parallel
        1. Canceling a Parallel Loop
      7. Running LINQ Queries in Parallel
        1. Canceling a PLINQ Query
      8. Summary
    31. 19. Thread Synchronization
      1. Why Synchronization?
        1. Synchronization Using Monitor
        2. Using the lock Keyword
        3. Choosing a lock Object
        4. Why to Avoid Locking on this, typeof(type), and string
        5. Declaring Fields As volatile
        6. Using the System.Threading.Interlocked Class
        7. Event Notification with Multiple Threads
        8. Synchronization Design Best Practices
        9. More Synchronization Types
        10. Thread Local Storage
      2. Timers
      3. Summary
    32. 20. Platform Interoperability and Unsafe Code
      1. Platform Invoke
        1. Declaring External Functions
        2. Parameter Data Types
        3. Using ref Rather Than Pointers
        4. Using StructLayoutAttribute for Sequential Layout
        5. Error Handling
        6. Using SafeHandle
        7. Calling External Functions
        8. Simplifying API Calls with Wrappers
        9. Function Pointers Map to Delegates
        10. Guidelines
      2. Pointers and Addresses
        1. Unsafe Code
        2. Pointer Declaration
        3. Assigning a Pointer
        4. Dereferencing a Pointer
        5. Accessing the Member of a Referent Type
      3. Executing Unsafe Code via a Delegate
      4. Using the Windows Runtime Libraries from C#
        1. WinRT Events with Custom Add and Remove Handlers
        2. Automatically Shimmed Interfaces
        3. Task-Based Asynchrony
      5. Summary
    33. 21. The Common Language Infrastructure
      1. Defining the Common Language Infrastructure
      2. CLI Implementations
      3. C# Compilation to Machine Code
      4. Runtime
        1. Garbage Collection
        2. Garbage Collection on .NET
        3. Type Safety
        4. Code Access Security
        5. Platform Portability
        6. Performance
      5. Application Domains
      6. Assemblies, Manifests, and Modules
      7. Common Intermediate Language
      8. Common Type System
      9. Common Language Specification
      10. Base Class Library
      11. Metadata
      12. Summary
    34. A. Downloading and Installing the C# Compiler and CLI Platform
      1. Microsoft .NET for Windows
        1. Visual Studio Compilation
        2. Setting up the Compiler Path for Command-Line Compilation
      2. .NET on OS X and Linux
        1. .NET Core
        2. Mono
    35. B. Tic-Tac-Toe Source Code Listing
    36. Index
    37. Index of 6.0 Topics
    38. Index of 5.0 Topics
    39. Index of 4.0 Topics
    40. Index of 3.0 Topics
    41. C. Interfacing with Multithreading Patterns prior to the TPL and C# 6.0
      1. Asynchronous Programming Model
        1. Using the APM Pattern
        2. Calling APM Methods Using the TPL
      2. Asynchronous Delegate Invocation
      3. The Event-Based Asynchronous Pattern
      4. Background Worker Pattern
        1. Establishing the Pattern
        2. Exception Handling
      5. Dispatching to the Windows UI
        1. Windows Forms
        2. Windows Presentation Foundation
    42. D. Timers Prior to the Async/Await Pattern of C# 5.0