You are previewing Essential C# 3.0: For .NET Framework 3.5.
O'Reilly logo
Essential C# 3.0: For .NET Framework 3.5

Book Description

Essential C# 3.0 is an extremely well-written and well-organized “no-fluff” guide to C# 3.0, which will appeal to programmers at all levels of experience with C#. This fully updated edition dives deep into the new features that are revolutionizing programming, with brand new chapters covering query expressions, lambda expressions, extension methods, collection interface extensions, standard query operators, and LINQ as a whole.

Author Mark Michaelis covers the C# language in depth, and each importantconstruct is illustrated with succinct, relevant code examples. (Complete code examples are available online.) Graphical “mind maps” at the beginning of each chapter show what material is covered and how each topic relates to the whole. Topics intended for beginners and advanced readers are clearly marked.

Following an introduction to C#, readers learn about 

  • C# primitive data types, value types, reference types, type conversions, and arrays

  • Operators and control flow, loops, conditional logic, and sequential programming

  • Methods, parameters, exception handling, and structured programming

  • Classes, inheritance, structures, interfaces, and object-oriented programming

  • Well-formed types, operator overloading, namespaces, and garbage collection

  • Generics, collections, custom collections, and iterators

  • Delegates and lambda expressions

  • Standard query operators and query expressions

  • LINQ: language integrated query

  • Reflection, attributes, and declarative programming

  • Threading, synchronization, and multithreaded patterns

  • Interoperability and unsafe code

  • The Common Language Infrastructure that underlies C# 

  • Whether you are just starting out as a programmer, are an experienced developer looking to learn C#, or are a seasoned C# programmer interested in learning the new features of C# 3.0, Essential C# 3.0 gives you just what you need to quickly get up and running writing C# applications.

    Table of Contents

    1. Copyright
      1. Dedication
    2. Praise for Essential C# 3.0
      1. Praise for the First Edition
    3. Microsoft .NET Development Series
      1. Titles in the Series
    4. Figures
    5. Tables
    6. Foreword
    7. Preface
      1. Target Audience for This Book
      2. Features of This Book
        1. Code Samples
        2. Helpful Notes
        3. Mind Maps
      3. How This Book Is Organized
    8. Acknowledgments
    9. About the Author
    10. 1. Introducing C#
      1. Hello, World
        1. Compiling and Running the Application
      2. C# Syntax Fundamentals
        1. C# Keywords
        2. Type Definition
        3. Main
        4. Statements and Statement Delimiters
        5. Whitespace
      3. Working with Variables
        1. Data Types
        2. Declaring a Variable
        3. Assigning a Variable
        4. Using a Variable
      4. Console Input and Output
        1. Getting Input from the Console
        2. Writing Output to the Console
      5. Comments
      6. Managed Execution and the Common Language Infrastructure
      7. C# and .NET Versioning
      8. Common Intermediate Language and ILDASM
      9. Summary
    11. 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
          1. Literals
          2. String Methods
          3. New Line
          4. String Length
          5. Strings Are Immutable
          6. System.Text.StringBuilder
      3. null and void
        1. null
        2. The void Nontype
      4. Categories of Types
        1. Value Types
        2. Reference Types
      5. Nullable Modifier
      6. Conversions between Data Types
        1. Explicit Cast
        2. Implicit Cast
        3. Type Conversion without Casting
      7. Arrays
        1. Declaring an Array
        2. Instantiating and Assigning Arrays
        3. Using an Array
          1. Length
          2. More Array Methods
          3. Array Instance Methods
        4. Strings as Arrays
        5. Common Errors
      8. Summary
    12. 3. Operators and Control Flow
      1. Operators
        1. Plus and Minus Unary Operators (+, –)
        2. Arithmetic Binary Operators (+, –, *, /, %)
          1. Using the Plus Operator with Strings
          2. Using Characters in Arithmetic Operations
          3. Special Floating-Point Characteristics
        3. Parenthesis Operator
        4. Assignment Operators (+=, –=, *=, /=, %=)
        5. Increment and Decrement Operators (++, --)
        6. Constant Expressions (const)
      2. Introducing Flow Control
        1. if Statement
        2. Nested if
      3. Code Blocks ({})
      4. Scope
      5. Boolean Expressions
        1. Relational and Equality Operators
        2. Logical Boolean Operators
          1. OR Operator (||)
          2. AND Operator (&&)
          3. Exclusive OR Operator (^)
        3. Logical Negation Operator (!)
        4. Conditional Operator (?)
      6. Bitwise Operators (<<, >>, |, &, ^, ~)
        1. Shift Operators (<<, >>, <<=, >>=)
        2. Bitwise Operators (&, |, ^)
        3. Bitwise 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
    13. 4. Methods and Parameters
      1. Calling a Method
        1. Namespace
        2. Type Name
        3. Scope
        4. Method Name
        5. Parameters
        6. Method Return
        7. Statement versus Method Call
      2. Declaring a Method
        1. Parameter Declaration
        2. Method Return Declaration
      3. The using Directive
        1. Aliasing
      4. Returns and Parameters on Main()
      5. Parameters
        1. Value Parameters
        2. Reference Parameters (ref)
        3. Output Parameters (out)
        4. Parameter Arrays (params)
      6. Recursion
      7. Method Overloading
      8. Basic Error Handling with Exceptions
        1. Trapping Errors
        2. Reporting Errors Using a throw Statement
          1. Avoid Using Exception Handling to Deal with Expected Situations
      9. Summary
    14. 5. Classes
      1. Defining 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. Naming Conventions
        4. Using Properties with Validation
        5. Read-Only and Write-Only Properties
        6. Access Modifiers on Getters and Setters
        7. Properties as Virtual Fields
        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. Calling Another Constructor Using this
      8. Static
        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
    15. 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. Everything Ultimately Derives from System.Object
      5. Verifying the Underlying Type with the is Operator
      6. Conversion Using the as Operator
      7. Summary
    16. 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. Casting 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. Summary
    17. 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
    18. 9. Well-Formed Types
      1. Overriding object Members
        1. Overriding ToString()
        2. Overriding GetHashCode()
        3. Overriding Equals()
          1. Object Identity versus Equal Object Values
          2. Implementing Equals()
        4. Guidelines for Implementing Equality
      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
        3. Encapsulation of Types
      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 and Finalization
        4. Resource Utilization and Finalization Guidelines
      8. Summary
    19. 10. Exception Handling
      1. Multiple Exception Types
      2. Catching Exceptions
      3. General Catch Block
      4. Guidelines for Exception Handling
      5. Defining Custom Exceptions
      6. Summary
    20. 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. Nested Generic Types
        10. Type Compatibility between Generic Classes with Type-Compatible Type Parameters
      3. Constraints
        1. Interface Constraints
        2. Base Class Constraints
        3. struct/class Constraints
        4. Multiple Constraints
        5. Constructor Constraints
        6. Constraint Inheritance
      4. Generic Methods
        1. Type Inferencing
        2. Specifying Constraints
      5. Generic Internals
        1. Instantiating Generics Based on Value Types
        2. Instantiating Generics Based on Reference Types
      6. Summary
    21. 12. Delegates and Lambda Expressions
      1. Introducing Delegates
        1. Defining the Scenario
        2. Delegate Data Types
        3. Delegate Internals
        4. Defining a Delegate Type
        5. Instantiating a Delegate
      2. Anonymous Methods
      3. System-Defined Delegates: Func<>
      4. Lambda Expressions
        1. Statement Lambdas
        2. Expression Lambdas
        3. Outer Variables
        4. Expression Trees
          1. System.Linq.Enumerable versus System.Linq.Queryable
          2. Examining an Expression Tree
      5. Summary
    22. 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?
          1. Encapsulating the Subscription
          2. Encapsulating the Publication
        2. Declaring an Event
        3. Coding Conventions
        4. Generics and Delegates
        5. Customizing the Event Implementation
      3. Summary
    23. 14. Collection Interfaces with Standard Query Operators
      1. Anonymous Types and Implicit Local Variable Declaration
        1. Anonymous Types
        2. Implicitly Typed Local Variables
        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>
          1. State Is Shared
          2. Cleaning Up Following Iteration
        3. Do Not Modify Collections during foreach Iteration
      4. Standard Query Operators
        1. Filtering with Where()
        2. Projecting with Select()
        3. Deferred Execution
        4. Sorting with OrderBy() and ThenBy()
        5. Performing an Inner Join with Join()
        6. Implementing a One-to-Many Relationship with GroupJoin()
        7. Calling SelectMany()
        8. More Standard Query Operators
      5. Summary
    24. 15. Query Expressions
      1. Introducing Query Expressions
        1. Projection
        2. Filtering
        3. Sorting
        4. Let
        5. Grouping
      2. Query Expressions as Method Invocations
      3. Summary
    25. 16. Building Custom Collections
      1. More Collection Interfaces
        1. IList<T> versus IDictionary<TKey, TValue>
        2. IComparable<T>
        3. ICollection<T>
      2. Primary Collection Classes
        1. List Collections: List<T>
        2. Dictionary Collections: Dictionary<TKey, TValue>
        3. Sorted Collections: SortedDictionary<TKey, TValue> and SortedList<T>
        4. Stack Collections: Stack<T>
        5. Queue Collections: Queue<T>
        6. Linked Lists: LinkedList<T>
      3. Providing an Index Operator
      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 Characteristics
      6. Summary
    26. 17. Reflection and Attributes
      1. Reflection
        1. Accessing Metadata Using System.Type
          1. GetType()
          2. typeof()
        2. Member Invocation
        3. Reflection on Generic Types
          1. Determining the Type of Type Parameters
          2. Determining Whether a Class or Method Supports Generics
          3. Obtaining Type Parameters for a Generic Class or Method
      2. Attributes
        1. Custom Attributes
        2. Looking for Attributes
        3. Initializing an Attribute through a Constructor
        4. System.AttributeUsageAttribute
        5. Named Parameters
          1. Predefined Attributes
          2. System.ConditionalAttribute
          3. System.ObsoleteAttribute
          4. Serialization-Related Attributes
      3. Summary
    27. 18. Multithreading
      1. Running and Controlling a Separate Thread
        1. Starting a Thread
        2. Thread Management
          1. Join()
          2. IsBackGround
          3. Priority
          4. ThreadState
          5. Thread.Sleep()
          6. Abort()
      2. Passing Parameters to Threads
      3. Thread Pooling
      4. Unhandled Exceptions
      5. Synchronization
        1. Synchronization Using Monitor
        2. Using the lock Keyword
        3. Choosing a lock Object
        4. Why to Avoid Locking on this and typeof(type)
        5. Declaring Fields as volatile
        6. Using the System.Threading.Interlocked Class
        7. Event Notification with Multiple Threads
        8. Synchronization Design Best Practices
          1. Avoiding Deadlock
          2. When to Provide Synchronization
          3. Avoiding Unnecessary Locking
        9. More Synchronization Types
          1. System.Threading.Mutex
          2. Reset Events: ManualResetEvent and AutoResetEvent
          3. ThreadStaticAttribute
          4. Synchronizing a Method Using MethodImplAttribute
      6. Timers
      7. Summary
    28. 19. Multithreading Patterns
      1. Asynchronous Results Pattern
        1. Introducing the Asynchronous Results Pattern
        2. Passing Data to and from an Alternate Thread
        3. Receiving Notification of Thread Completion
        4. Passing Arbitrary State
        5. Asynchronous Results Conclusions
      2. Background Worker Pattern
        1. Establishing the Pattern
        2. Exception Handling
      3. Windows Forms
      4. Summary
    29. 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
          1. Fixing Data
          2. Allocating on the Stack
        4. Dereferencing a Pointer
        5. Accessing the Member of a Referent Type
      3. Summary
    30. 21. The Common Language Infrastructure
      1. Defining the Common Language Infrastructure (CLI)
      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 (CIL)
      8. Common Type System (CTS)
      9. Common Language Specification (CLS)
      10. Base Class Library (BCL)
      11. Metadata
      12. Summary
    31. A. Downloading and Installing the C# Compiler and the CLI Platform
      1. Microsoft’s .NET
        1. Setting Up the Compiler Path with Microsoft .NET
      2. Mono
    32. B. Full Source Code Listings
      1. Chapters 2 and 3
      2. Chapter 9
      3. Chapter 11
      4. Chapter 12
      5. Chapter 17
    33. C. C# 3.0 Topics
      1. C# 3.0 Topics by Page Number
      2. C# 3.0 Topics by Title