You are previewing Programming C# 4.0.
O'Reilly logo
Programming C# 4.0

Book Description

This bestselling tutorial for beginning to intermediate programmers teaches you how to use the new version of the C# language to build web, desktop, and rich Internet applications with the .NET 4.0 Framework. The sixth edition covers the latest enhancements to the language, as well as the fundamentals of both C# and .NET, and concurrent programming with C# 4.0. You'll also learn how to use C# with .NET tools such as the Entity Framework and the Silverlight platform.

Table of Contents

  1. Programming C# 4.0
    1. SPECIAL OFFER: Upgrade this ebook with O’Reilly
    2. A Note Regarding Supplemental Files
    3. Preface
      1. How This Book Is Organized
        1. Where to Find Features New in C# 4.0 and .NET 4
      2. Who This Book Is For
      3. What You Need to Use This Book
      4. Conventions Used in This Book
      5. Using Code Examples
      6. Safari® Books Online
      7. Acknowledgments
        1. From Ian Griffiths
        2. From Matthew Adams
    4. 1. Introducing C#
      1. Why C#? Why .NET?
      2. The .NET Framework Class Library
      3. Language Style
        1. Composability
        2. Managed Code
        3. Continuity and the Windows Ecosystem
      4. C# 4.0, .NET 4, and Visual Studio 2010
      5. Summary
    5. 2. Basic Programming Techniques
      1. Getting Started
      2. Namespaces and Types
      3. Projects and Solutions
      4. Comments, Regions, and Readability
        1. Bad Comments
        2. XML Documentation Comments
      5. Variables
        1. Variable Types
          1. Integers
          2. Floating point
          3. Decimal floating point
      6. Expressions and Statements
        1. Assignment Statements
        2. Increment and Decrement Operators
      7. Flow Control with Selection Statements
        1. if Statements
          1. if...else
        2. switch and case Statements
      8. Iteration Statements
        1. foreach Statements
        2. for Statements
        3. while and do Statements
        4. Breaking Out of a Loop
      9. Methods
      10. Summary
    6. 3. Abstracting Ideas with Classes and Structs
      1. Divide and Conquer
        1. Abstracting Ideas with Methods
        2. Abstracting Ideas with Objects and Classes
          1. Object-oriented analysis
      2. Defining Classes
        1. Representing State with Properties
        2. Protection Levels
        3. Initializing with a Constructor
        4. Fields: A Place to Put Data
        5. Fields Can Be Fickle, but const Is Forever
        6. Read-only Fields and Properties
      3. Related Constants with enum
      4. Value Types and Reference Types
      5. Too Many Constructors, Mr. Mozart
      6. Overloading
        1. Overloaded Methods and Default Named Parameters
      7. Object Initializers
      8. Defining Methods
        1. Declaring Static Methods
      9. Static Fields and Properties
        1. Static Constructors
      10. Summary
    7. 4. Extensibility and Polymorphism
      1. Association Through Composition and Aggregation
      2. Inheritance and Polymorphism
      3. Replacing Methods in Derived Classes
        1. Hiding Base Members with new
        2. Replacing Methods with virtual and override
      4. Inheritance and Protection
      5. Calling Base Class Methods
      6. Thus Far and No Farther: sealed
      7. Requiring Overrides with abstract
      8. All Types Are Derived from Object
        1. Boxing and Unboxing Value Types
      9. C# Does Not Support Multiple Inheritance of Implementation
      10. C# Supports Multiple Inheritance of Interface
      11. Deriving Interfaces from Other Interfaces
        1. Explicit Interface Implementation
      12. The Last Resort: Checking Types at Runtime
      13. Summary
    8. 5. Composability and Extensibility with Delegates
      1. Functional Composition with delegate
      2. Generic Actions with Action<T>
      3. Generic Predicates with Predicate<T>
      4. Using Anonymous Methods
      5. Creating Delegates with Lambda Expressions
      6. Delegates in Properties
      7. Generic Delegates for Functions
      8. Notifying Clients with Events
        1. Exposing Large Numbers of Events
      9. Summary
    9. 6. Dealing with Errors
      1. When and How to Fail
      2. Returning Error Values
        1. Debugging with Return Values
      3. Exceptions
        1. Handling Exceptions
        2. When Do finally Blocks Run?
        3. Deciding What to Catch
        4. Custom Exceptions
      4. Summary
    10. 7. Arrays and Lists
      1. Arrays
        1. Construction and Initialization
          1. Array arguments and the params keyword
        2. Custom Types in Arrays
        3. Array Members
          1. Finding elements
          2. Ordering elements
          3. Moving or copying elements
        4. Array Size
          1. Arrays of arrays (or jagged arrays)
          2. Rectangular arrays
      2. List<T>
        1. Custom Indexers
          1. Immutability and List<T>
        2. Finding and Sorting
      3. Collections and Polymorphism
        1. Creating Your Own IEnumerable<T>
          1. Lazy collections
      4. Summary
    11. 8. LINQ
      1. Query Expressions
        1. Query Expressions Versus Method Calls
        2. Extension Methods and LINQ
        3. let Clauses
      2. LINQ Concepts and Techniques
        1. Delegates and Lambdas
        2. Functional Style and Composition
        3. Deferred Execution
      3. LINQ Operators
        1. Filtering
        2. Ordering
        3. Concatenation
        4. Grouping
        5. Projections
          1. Anonymous types
          2. Using multiple sources
          3. Numbering items
        6. Zipping
        7. Getting Selective
        8. Testing the Whole Collection
        9. Aggregation
        10. Set Operations
        11. Joining
        12. Conversions
      4. Summary
    12. 9. Collection Classes
      1. Dictionaries
        1. Common Dictionary Uses
          1. Looking up values
          2. Caching
          3. Dynamic properties
          4. Sparse arrays
        2. IDictionary<TKey, TValue>
        3. Dictionaries and LINQ
      2. HashSet and SortedSet
      3. Queues
      4. Linked Lists
      5. Stacks
      6. Summary
    13. 10. Strings
      1. What Is a String?
      2. The String and Char Types
      3. Literal Strings and Chars
        1. Escaping Special Characters
      4. Formatting Data for Output
        1. Standard Numeric Format Strings
          1. Currency
          2. Decimal
          3. Hexadecimal
          4. Exponential form
          5. Fixed point
          6. General
          7. Numeric
          8. Percent
          9. Round trip
        2. Custom Numeric Format Strings
        3. Dates and Times
        4. Going the Other Way: Converting Strings to Other Types
        5. Composite Formatting with String.Format
      5. Culture Sensitivity
        1. Exploring Formatting Rules
      6. Accessing Characters by Index
      7. Strings Are Immutable
      8. Getting a Range of Characters
      9. Composing Strings
        1. Splitting It Up Again
        2. Upper- and Lowercase
      10. Manipulating Text
        1. Mutable Strings with StringBuilder
      11. Finding and Replacing Content
      12. All Sorts of “Empty” Strings
      13. Trimming Whitespace
      14. Checking Character Types
      15. Encoding Characters
        1. Why Encodings Matter
        2. Encoding and Decoding
        3. Why Represent Strings As Byte Sequences?
      16. Summary
    14. 11. Files and Streams
      1. Inspecting Directories and Files
      2. Examining Directories
      3. Manipulating File Paths
        1. Path and the Current Working Directory
      4. Examining File Information
      5. Creating Temporary Files
      6. Deleting Files
      7. Well-Known Folders
      8. Concatenating Path Elements Safely
      9. Creating and Securing Directory Hierarchies
      10. Deleting a Directory
      11. Writing Text Files
        1. Writing a Whole Text File at Once
        2. Writing Text with a StreamWriter
      12. When Files Go Bad: Dealing with Exceptions
        1. Finding and Modifying Permissions
      13. Reading Files into Memory
      14. Streams
        1. Moving Around in a Stream
        2. Writing Data with Streams
      15. Reading, Writing, and Locking Files
      16. FileStream Constructors
        1. Stream Buffers
        2. Setting Permissions During Construction
        3. Setting Advanced Options
      17. Asynchronous File Operations
      18. Isolated Storage
        1. Stores
        2. Reading and Writing Text
        3. Defining “Isolated”
          1. Isolation by user and assembly
          2. Isolation by user, domain, and assembly
          3. Isolation by user and application
          4. Machine isolation
        4. Managing User Storage with Quotas
        5. Managing Isolated Storage
      19. Streams That Aren’t Files
        1. An Adapting Stream: CryptoStream
        2. In Memory Alone: The MemoryStream
        3. Representing Binary As Text with Base64 Encoding
      20. Summary
    15. 12. XML
      1. XML Basics (A Quick Review)
        1. Elements
        2. XHTML
      2. X Stands for eXtensible
      3. Creating XML Documents
        1. XML Elements
        2. XML Attributes
        3. Putting the LINQ in LINQ to XML
      4. Searching in XML with LINQ
        1. Searching for a Single Node
        2. Search Axes
        3. Where Clauses
      5. XML Serialization
        1. Customizing XML Serialization Using Attributes
      6. Summary
    16. 13. Networking
      1. Choosing a Networking Technology
        1. Web Application with Client-Side Code
        2. .NET Client and .NET Server
          1. Tightly controlled deployment
          2. Weakly controlled deployment
        3. .NET Client and External Party Web Service
        4. External Client and .NET Web Service
      2. WCF
        1. Creating a WCF Project
        2. WCF Contracts
        3. WCF Test Client and Host
        4. Hosting a WCF Service
          1. WCF configuration
        5. Writing a WCF Client
          1. Sharing contracts
          2. Proxy
        6. Bidirectional Communication with Duplex Contracts
          1. Session-based communication
          2. Calling the client from the server
          3. Server configuration for duplex and sessions
          4. Duplex client
      3. HTTP
        1. WebClient
          1. Downloading resources
          2. Uploading resources
          3. Stream-based uploads and downloads
        2. WebRequest and WebResponse
          1. Authentication
          2. Working with proxies
          3. Controlling cache behavior
          4. Using cookies
      4. Sockets
        1. IP, IPv6, and TCP
        2. Connecting to Services with the Socket Class
        3. Implementing Services with the Socket Class
      5. Other Networking Features
      6. Summary
    17. 14. Databases
      1. The .NET Data Access Landscape
        1. Classic ADO.NET
          1. IDataReader and friends
          2. ADO.NET data sets
        2. LINQ and Databases
        3. Non-Microsoft Data Access Technologies
        4. WCF Data Services
        5. Silverlight and Data Access
        6. Databases
          1. Getting up and running with SQL Server 2008 Express
      2. The Entity Data Model
        1. Generated Code
        2. Changing the Mapping
        3. Relationships
          1. Navigation properties
          2. Multiplicity
        4. Inheritance
      3. Queries
        1. LINQ to Entities
        2. Entity SQL
        3. Mixing ESQL and LINQ
        4. The EntityClient ADO.NET Provider
      4. Object Context
        1. Connection Handling
        2. Creating, Updating, and Deleting
        3. Transactions
        4. Optimistic Concurrency
        5. Context and Entity Lifetime
      5. WCF Data Services
      6. Summary
    18. 15. Assemblies
      1. .NET Components: Assemblies
        1. References
        2. Writing Libraries
        3. Protection
          1. Internal protection
      2. Naming
        1. Signing and Strong Names
      3. Loading
        1. Loading from the Application Folder
        2. Loading from the GAC
        3. Loading from a Silverlight .xap File
        4. Explicit Loading
          1. Unloading
      4. Summary
    19. 16. Threads and Asynchronous Code
      1. Threads
        1. Threads and the OS Scheduler
        2. The Stack
        3. The Thread Pool
        4. Thread Affinity and Context
        5. Common Thread Misconceptions
          1. Myth: Threads are necessary to get work done
          2. Myth: Multiple logical processors will necessarily make things faster
          3. Myth: Maxing the CPU must mean we’re going really fast
        6. Multithreaded Coding Is Hard
          1. Race conditions
          2. Deadlocks and livelocks
        7. Multithreading Survival Strategies
          1. Abstinence
          2. Isolation
          3. Immutability
          4. Synchronization
      2. Synchronization Primitives
        1. Monitor
          1. Notification
        2. Other Lock Types
          1. SpinLock
          2. Reader/writer locks
          3. Mutexes
        3. Other Coordination Mechanisms
        4. Events
        5. Countdown
        6. BlockingCollection
      3. Asynchronous Programming
        1. The Asynchronous Programming Model
        2. The Event-Based Asynchronous Pattern
        3. Ad Hoc Asynchrony
      4. The Task Parallel Library
        1. Tasks
          1. Parent-child relationships
          2. Fine-grained concurrency
          3. Tasks with results
          4. Continuations
          5. Schedulers
          6. Tasks and the Asynchronous Programming Model
        2. Cancellation
        3. Error Handling
      5. Data Parallelism
        1. Parallel For and ForEach
        2. PLINQ: Parallel LINQ
      6. Summary
    20. 17. Attributes and Reflection
      1. Attributes
        1. Types of Attributes
          1. Attribute targets
          2. Applying attributes
        2. Custom Attributes
          1. Defining a custom attribute
          2. Naming an attribute
          3. Constructing an attribute
          4. Using an attribute
      2. Reflection
        1. Inspecting Metadata
        2. Type Discovery
        3. Reflecting on a Specific Type
          1. Finding all type members
          2. Finding type methods
        4. Late Binding
      3. Summary
    21. 18. Dynamic
      1. Static Versus Dynamic
        1. The Dynamic Style and COM Automation
      2. The dynamic Type
        1. Object Types and dynamic
          1. COM objects
          2. Silverlight script objects
          3. Ordinary .NET objects
          4. Objects from other dynamic languages
          5. ExpandoObject
          6. Custom dynamic objects
      3. dynamic in Noninterop Scenarios?
      4. Summary
    22. 19. Interop with COM and Win32
      1. Importing ActiveX Controls
        1. Importing a Control in .NET
      2. Interop Assemblies
        1. No PIA
      3. 64-bit Versus 32-bit
      4. P/Invoke
      5. Pointers
      6. C# 4.0 Interop Syntax Enhancements
        1. Indexed Properties
        2. Optional ref
      7. Summary
    23. 20. WPF and Silverlight
      1. Xaml and Code Behind
        1. Xaml and Objects
      2. Elements and Controls
        1. Layout Panels
          1. General-purpose layout properties
          2. Transforms
        2. Graphical Elements
          1. Shapes
          2. Images
          3. Media
          4. Animation
          5. 3D graphics
        3. Controls
          1. Content controls
          2. Items controls
        4. User Controls
      3. Control Templates
        1. Styles
        2. The Visual State Manager
      4. Data Binding
        1. Data Templates
      5. Summary
    24. 21. Programming ASP.NET Applications
      1. Web Forms Fundamentals
        1. Web Forms Events
          1. Postback versus nonpostback events
          2. View state
        2. Web Forms Life Cycle
      2. Creating a Web Application
        1. Code-Behind Files
        2. Adding Controls
        3. Server Controls
      3. Data Binding
        1. Examining the Code
        2. Adding Controls and Events
      4. Summary
    25. 22. Windows Forms
      1. Creating the Application
        1. Adding a Binding Source
      2. Controls
        1. Docking and Anchoring
      3. Data Binding
      4. Event Handling
      5. Summary
    26. Index
    27. About the Authors
    28. Colophon
    29. SPECIAL OFFER: Upgrade this ebook with O’Reilly