After a dozen years of incremental changes, C# has become one of the most versatile programming languages available. With this comprehensive guide, you’ll learn just how powerful the combination of C# 5.0 and .NET 4.5 can be. Author Ian Griffiths guides you through C# 5.0 fundamentals and teaches you techniques for building web and desktop applications, including Windows 8-style apps.
Completely rewritten for experienced programmers, this book provides many code examples to help you work with the nuts and bolts of C# code, such as generics, dynamic typing, and the new asynchronous programming features. You’ll also get up to speed on XAML, ASP.NET, LINQ, and other .NET tools.
Discover how C# supports fundamental coding features such as classes, other custom types, collections, and error handling
Understand the differences between dynamic and static typing in C#
Query and process diverse data sources such as in-memory object models, databases, and XML documents with LINQ
Use .NET’s multithreading features to exploit your computer’s parallel processing capabilities
Learn how the new asynchronous language features can help improve application responsiveness and scalability
Use XAML to create Windows 8-style, phone, and classic desktop applications
Author(s): Ian Griffiths
Publisher: O'Reilly Media
Year: 2012
Language: English
Pages: 886
Copyright
Table of Contents
Preface
Who This Book Is For
Conventions Used in This Book
Using Code Examples
Safari® Books Online
How to Contact Us
Acknowledgments
Chapter 1. Introducing C#
Why C#?
Why Not C#?
C#’s Defining Features
Managed Code and the CLR
Generality Trumps Specialization
Asynchronous Programming
Visual Studio
Anatomy of a Simple Program
Adding a Project to an Existing Solution
Referencing One Project from Another
Writing a Unit Test
Namespaces
Classes
Program Entry Point
Unit Tests
Summary
Chapter 2. Basic Coding in C#
Local Variables
Scope
Statements and Expressions
Statements
Expressions
Comments and Whitespace
Preprocessing Directives
Compilation Symbols
#error and #warning
#line
#pragma
#region and #endregion
Intrinsic Data Types
Numeric Types
Booleans
Strings and Characters
Object
Operators
Flow Control
Boolean Decisions with if Statements
Multiple Choice with switch Statements
Loops: while and do
C-Style for Loops
Collection Iteration with foreach Loops
Summary
Chapter 3. Types
Classes
Static Members
Static Classes
Reference Types
Structs
When to Write a Value Type
Members
Fields
Constructors
Methods
Properties
Indexers
Operators
Events
Nested Types
Interfaces
Enums
Other Types
Anonymous Types
Partial Types and Methods
Summary
Chapter 4. Generics
Generic Types
Constraints
Type Constraints
Reference Type Constraints
Value Type Constraints
Multiple Constraints
Zero-Like Values
Generic Methods
Type Inference
Inside Generics
Summary
Chapter 5. Collections
Arrays
Array Initialization
Variable Argument Count with the params Keyword
Searching and Sorting
Multidimensional Arrays
Copying and Resizing
List
List and Sequence Interfaces
Implementing Lists and Sequences
Iterators
Collection
ReadOnlyCollection
Dictionaries
Sorted Dictionaries
Sets
Queues and Stacks
Linked Lists
Concurrent Collections
Tuples
Summary
Chapter 6. Inheritance
Inheritance and Conversions
Interface Inheritance
Generics
Covariance and Contravariance
System.Object
The Ubiquitous Methods of object
Accessibility and Inheritance
Virtual Methods
Abstract Methods
Sealed Methods and Classes
Accessing Base Members
Inheritance and Construction
Special Base Types
Summary
Chapter 7. Object Lifetime
Garbage Collection
Determining Reachability
Accidentally Defeating the Garbage Collector
Weak References
Reclaiming Memory
Garbage Collector Modes
Accidentally Defeating Compaction
Forcing Garbage Collections
Destructors and Finalization
Critical Finalizers
IDisposable
Optional Disposal
Boxing
Boxing Nullable
Summary
Chapter 8. Exceptions
Exception Sources
Exceptions from APIs
Exceptions from Your Code
Failures Detected by the Runtime
Handling Exceptions
Exception Objects
Multiple catch Blocks
Nested try Blocks
finally Blocks
Throwing Exceptions
Rethrowing Exceptions
Failing Fast
Exception Types
Custom Exceptions
Unhandled Exceptions
Debugging and Exceptions
Asynchronous Exceptions
Summary
Chapter 9. Delegates, Lambdas, and Events
Delegate Types
Creating a Delegate
Multicast Delegates
Invoking a Delegate
Common Delegate Types
Type Compatibility
Behind the Syntax
Inline Methods
Captured Variables
Lambdas and Expression Trees
Events
Standard Event Delegate Pattern
Custom Add and Remove Methods
Events and the Garbage Collector
Events Versus Delegates
Delegates Versus Interfaces
Summary
Chapter 10. LINQ
Query Expressions
How Query Expressions Expand
Supporting Query Expressions
Deferred Evaluation
LINQ, Generics, and IQueryable
Standard LINQ Operators
Filtering
Select
SelectMany
Ordering
Containment Tests
Specific Items and Subranges
Aggregation
Set Operations
Whole-Sequence, Order-Preserving Operations
Grouping
Joins
Conversion
Sequence Generation
Other LINQ Implementations
Entity Framework
LINQ to SQL
WCF Data Services Client
Parallel LINQ (PLINQ)
LINQ to XML
Reactive Extensions
Summary
Chapter 11. Reactive Extensions
Rx and .NET Versions
Fundamental Interfaces
IObserver
IObservable
Publishing and Subscribing with Delegates
Creating an Observable Source with Delegates
Subscribing to an Observable Source with Delegates
Sequence Builders
Empty
Never
Return
Throw
Range
Repeat
Generate
LINQ Queries
Grouping Operators
Join Operators
SelectMany Operator
Aggregation and Other Single-Value Operators
Concat Operator
Rx Query Operators
Merge
Windowing Operators
The Scan Operator
The Amb Operator
DistinctUntilChanged
Schedulers
Specifying Schedulers
Built-in Schedulers
Subjects
Subject
BehaviorSubject
ReplaySubject
AsyncSubject
Adaptation
IEnumerable
.NET Events
Asynchronous APIs
Timed Operations
Interval
Timer
Timestamp
TimeInterval
Throttle
Sample
Timeout
Windowing Operators
Delay
DelaySubscription
Summary
Chapter 12. Assemblies
Visual Studio and Assemblies
Anatomy of an Assembly
.NET Metadata
Resources
Multifile Assemblies
Other PE Features
Type Identity
Loading Assemblies
Explicit Loading
The Global Assembly Cache
Assembly Names
Strong Names
Version
Culture
Processor Architecture
Portable Class Libraries
Packaged Deployment
Windows 8 UI–Style Apps
ClickOnce and XBAP
Silverlight and Windows Phone Apps
Protection
Summary
Chapter 13. Reflection
Reflection Types
Assembly
Module
MemberInfo
Type and TypeInfo
MethodBase, ConstructorInfo, and MethodInfo
ParameterInfo
FieldInfo
PropertyInfo
EventInfo
Reflection Contexts
Summary
Chapter 14. Dynamic Typing
The dynamic Type
dynamic and Interoperability
Silverlight and Scriptable Objects
Dynamic .NET Languages
Inside Dynamic
Restrictions on the dynamic Type
Custom Dynamic Objects
ExpandoObject
Limitations of dynamic
Summary
Chapter 15. Attributes
Applying Attributes
Attribute Targets
Compiler-Handled Attributes
CLR-Handled Attributes
Defining and Consuming Custom Attributes
Attribute Type
Retrieving Attributes
Summary
Chapter 16. Files and Streams
The Stream Class
Position and Seeking
Flushing
Copying
Length
Disposal
Asynchronous Operation
Concrete Stream Types
Windows 8 and IRandomAccessStream
Text-Oriented Types
TextReader and TextWriter
Concrete Reader and Writer Types
Encoding
Files and Directories
FileStream Class
File Class
Directory Class
Path Class
FileInfo, DirectoryInfo, and FileSystemInfo
Known Folders
Serialization
BinaryReader and BinaryWriter
CLR Serialization
Data Contract Serialization
XmlSerializer
Summary
Chapter 17. Multithreading
Threads
Threads, Variables, and Shared State
The Thread Class
The Thread Pool
Thread Affinity and SynchronizationContext
Synchronization
Monitors and the lock Keyword
SpinLock
Reader/Writer Locks
Event Objects
Barrier
CountdownEvent
Semaphores
Mutex
Interlocked
Lazy Initialization
Other Class Library Concurrency Support
Tasks
The Task and Task Classes
Continuations
Schedulers
Error Handling
Custom Threadless Tasks
Parent/Child Relationships
Composite Tasks
Other Asynchronous Patterns
Cancellation
Parallelism
The Parallel Class
Parallel LINQ
TPL Dataflow
Summary
Chapter 18. Asynchronous Language Features
Asynchronous Keywords: async and await
Execution and Synchronization Contexts
Multiple Operations and Loops
Returning a Task
Applying async to Nested Methods
The await Pattern
Error Handling
Validating Arguments
Singular and Multiple Exceptions
Concurrent Operations and Missed Exceptions
Summary
Chapter 19. XAML
XAML-Based Frameworks
WPF
Silverlight
Windows Phone 7
Windows Runtime and Windows 8 UI–Style Apps
XAML Basics
XAML and XML Namespaces
Generated Classes and Codebehind
Child Elements
Property Elements
Event Handling
Threading
Layout
Properties
Panels
ScrollViewer
Layout Events
Controls
Content Controls
Slider and ScrollBar Controls
Progress Controls
List Controls
Control Templates
UserControls
Text
Displaying Text
Editing Text
Data Binding
Data Templates
Graphics
Shapes
Bitmaps
Media
Styles
Summary
Chapter 20. ASP.NET
Razor
Expressions
Flow Control
Code Blocks
Explicitly Indicated Content
Page Classes and Objects
Using Other Components
Layout Pages
Start Pages
Web Forms
Server-Side Controls
Expressions
Code Blocks
Standard Page Objects
Page Classes and Objects
Using Other Components
Master Pages
MVC
Typical MVC Project Layout
Writing Models
Writing Views
Writing Controllers
Handling Additional Input
Generating Action Links
Routing
Summary
Chapter 21. Interoperability
Calling Native Code
Marshaling
32-bit and 64-bit
Safe Handles
Security
Platform Invoke
Calling Convention
Text Handling
Entry Point Name
COM-Style Return Values
Win32 Error Handling
COM
RCW Lifetime
Metadata
Scripting
Windows Runtime
Metadata
Windows Runtime Types
Buffers
Unsafe Code
C++/CLI and the Component Extensions
Summary
Index
About the Author