A Programmer's Guide to C# 5.0

This document was uploaded by one of our users. The uploader already confirmed that they had the permission to publish it. If you are author/publisher or own the copyright of this documents, please report to us by using this DMCA report form.

Simply click on the Download Book button.

Yes, Book downloads on Ebookily are 100% Free.

Sometimes the book is free on Amazon As well, so go ahead and hit "Search on Amazon"

A Programmer’s Guide to C# 5.0 is a book for software developers who want to truly understand C#. Whether you’ve worked with C# before or with another general-purpose programming language, each fast-paced, focused chapter will take you straight to the heart of a feature of C# and show you why it works the way it does. Written by one-time C# Test Lead, Program Manager, and member of the original C# language design team, this book is an ideal companion to the C# Language Specification, and works both as a tutorial and as a reference guide. Now in its fourth edition, you will find up-to-date coverage of all the latest C# features, including Linq, covariance and contravariance, and async support. You’ll learn how to: Use C# features effectively, in the way they were intended Apply the newest C# features to your coding problems Streamline your database code using LINQ Use async support and the task parallel library to improve performance. Program more efficiently, effectively, and with real insight into this mature and exciting language, with A Programmer’s Guide to C# 5.0.

Author(s): Eric Gunnerson; Nick Wienholt
Edition: 4
Publisher: Apress
Year: 2012

Language: English
Pages: 472

A Programmer’s Guide to C# 5.0
Contents at a Glance
Contents
Preface
About the Authors
About the Technical Reviewer
Acknowledgments
Introduction
Chapter 1: C# and the .NET Runtime and Libraries
Chapter 2: C# QuickStart and Developing in C#
Hello, Universe
Namespace and Using Statements
Namespaces and Assemblies
Basic Data Types
Classes , Structs, and Interfaces
Statements
Enums
Delegates and Events
Properties and Indexers
Attributes
Developing in C#
Tools of Note
ILDASM
Decompilers
Obfuscators
NGEN
Chapter 3: Classes 101
A Simple Class
Member Functions
ref and out Parameters
Overloading
Chapter 4: Base Classes and Inheritance
The Engineer Class
Simple Inheritance
Arrays of Engineers
Virtual Functions
Abstract Classes
Sealed Classes and Methods
Chapter 5: Exception Handling
What’s Wrong with Return Codes?
Trying and Catching
Choosing the Catch Block
Passing Exceptions on to the Caller
Caller Beware
Caller Confuse
Caller Inform
User-Defined Exception Classes
Finally
Top-Level Exception Handlers
Efficiency and Overhead
Design Guidelines
Exceptions Are Exceptional
Choosing the Right Exception for Wrapping
Exceptions Should be as Specific as Possible
Retry Logic
Rethrowing
Catch Only if You Have Something Useful to Do
Chapter 6: Member Accessibility and Overloading
Class Accessibility
Using Internal on Members
Expanding Internal Accessibility
Protected
Internal Protected
The Interaction of Class and Member Accessibility
Accessability Summary
Method Overloading
Method Hiding
Better Conversions
Variable-Length Parameter Lists
Default Arguments
Named Arguments
Chapter 7: Other Class Details
Nested Classes
Other Nesting
Anonymous Types
Creation, Initialization, Destruction
Constructors
Private Constructors
Initialization
Destructors
Managing Nonmemory Resources
IDisposable and the Using Statement
IDisposable and Longer-Lived Objects
Static Fields
Static Member Functions
Static Constructors
Constants
Read-Only Fields
Extension Methods
Usage Guidelines
Object Initializers
Static Classes
Partial Classes and Methods
Chapter 8: Structs (Value Types)
A Point Struct
Boxing and Unboxing
Structs and Constructors
Mutable Structs
Design Guidelines
Immutable Classes
Chapter 9: Interfaces
A Simple Example
Working with Interfaces
The as Operator
Interfaces and Inheritance
Design Guidelines
Multiple Implementation
Explicit Interface Implementation
Implementation Hiding
Interfaces Based on Interfaces
Interfaces and Structs
Chapter 10: Versioning and Aliases
A Versioning Example
Coding for Versioning
Type Aliases
External Assembly Aliases
Chapter 11: Statements and Flow of Execution
Selection Statements
If
Switch
Iteration Statements
While
Do
For
Foreach
Jump Statements
Break
Continue
Goto
Return
Other Statements
lock
using
try, catch, and finally
checked and unchecked
yield
Chapter 12: Variable Scoping and Definite Assignment
Definite Assignment
Definite Assignment and Class Members
Definite Assignment and Arrays
Chapter 13: Operators and Expressions
Operator Precedence
Built-in Operators
User-Defined Operators
Numeric Promotions
Arithmetic Operators
Unary Plus (+)
Unary Minus (−)
Bitwise Complement (~)
Addition (+)
Numeric Addition
String Concatenation
Subtraction (−)
Multiplication (*)
Division (/)
Remainder (%)
Shift (<< and >>)
Increment and Decrement (++ and --)
Relational and Logical Operators
Logical Negation (!)
Relational Operators over
Logical Operators
Conditional Operator (?:)
Null Coalescing Operator (??)
Assignment Operators
Simple Assignment
Compound Assignment
Type Operators
typeof
is
as
Checked and Unchecked Expressions
Type Inference (var)
Best Practices
Chapter 14: Conversions
Numeric Types
Conversions and Member Lookup
Explicit Numeric Conversions
Checked Conversions
Conversions of Classes (Reference Types)
From an Object to the Base Class of an Object
From an Object to an Interface the Object Implements
From an Object to an Interface the Object Might Implement
From One Interface Type to Another
Conversions of Structs (Value Types)
Chapter 15: Arrays
Array Initialization
Multidimensional and Jagged Arrays
Multidimensional Arrays
Jagged Arrays
Arrays of Reference Types
Array Conversions
The System.Array Type
Sorting and Searching
Reverse
Chapter 16: Properties
Accessors
Properties and Inheritance
Using Properties
Side Effects When Setting Values
Static Properties
Property Efficiency
Property Accessibility
Virtual Properties
Automatic Properties
Properties vs. Fields
Chapter 17: Generic Types
A List of Integers
Constraints
Interface Constraints
Base Class Constraints
Class and Struct Constraints
Multiple Constraints
The Default Value of a Type
Generic Interfaces and Inheritance
Generic Methods
Generic Delegates
Covariance and Contravariance
Contravariance
Generics and Efficiency
Generic Naming Guidelines
Chapter 18: Indexers , Enumerators, and Iterators
Indexing with an Integer Index
Indexing with a String Index
Indexing with Multiple Parameters
Design Guidelines for Indexers
Object Enumeration
Enumerators and Foreach
Enabling Enumeration
Iterators
Named Iterators
Iterators and Generic Types
Iterators and Resource Management
Chapter 19: Strings
Operations
String Literals
String Encodings and Conversions
Converting Objects to Strings
An Example
StringBuilder
Regular Expressions
Regular Expression Options
More Complex Parsing
Chapter 20: Enumerations
A Line-Style Enumeration
Enumeration Base Types
Initialization
Bit Flag Enums
Conversions
The System.Enum Type
Chapter 21: Attributes
Using Attributes
A Few More Details
An Attribute of Your Own
Attribute Usage
Attribute Parameters
Attribute Parameter Types
Fetching Attribute Values
Chapter 22: Delegates , Anonymous Methods, and Lambdas
Using Delegates
Delegates to Instance Members
Multicasting
Delegates As Static Members
Anonymous Methods
Lambdas
Implementation
Variable Capturing
Guidelines
Parameter Naming
Method, Anonymous Delegate, or Lambda?
Chapter 23: Events
A Simple Example Using Delegates
Add and Remove Functions
Safe Event Invocation
EventHandler
Custom Add and Remove
Chapter 24: Dynamic Typing
The dynamic Keyword
Dynamic Failure
Generic Arithmetic with dynamic
Usage Guidelines
Chapter 25: User-Defined Conversions
A Simple Example
Pre- and Post-Conversions
Conversions Between Structs
Classes and Pre- and Post-Conversions
Design Guidelines
Implicit Conversions Are Safe Conversions
Define the Conversion in the More Complex Type
One Conversion to and from a Hierarchy
Add Conversions Only As Needed
Conversions That Operate in Other Languages
How It Works
Conversion Lookup
Chapter 26: Operator Overloading
Unary Operators
Binary Operators
An Example
Restrictions
Guidelines
A Complex Number Class
Chapter 27: Nullable Types
A Simple Example
Using Nullable Types
Null Coalescing
Nullable Types and Equality
Chapter 28: Linq to Objects
Getting Started with Linq to Objects
Filtering Data
Transforming Data
Stringing Sequences Together
Behind the Curtain
Query Expressions
A Sequence Method of Your Own
Sequence Method Reference
Aggregate Methods
Transformational Methods
Select()
SelectMany()
Cast()
ToArray()
ToDictionary()
ToList()
ToLookup()
Extraction Methods
Subset Methods
Ordering Methods
Whole Sequence Methods
Conditional Methods
Generator Methods
Join()
GroupBy()
Chapter 29: Linq to XML
Rockin’ It “Old School”
Linq to XML
Creating XML
Namespaces
Namespace Prefixes
Comments
XText
XDocument
Parsing XML
Loading the XML
The XElement Representation
Node Expressions
Finding Nodes in the Tree
XPathy Goodness
Namespaces and Parsing
Accessing Element Values
Chapter 30: Linq to SQL
Connecting by Hand
Query and Class Generation
Linq to SQL
Joining Tables
How It Works
Modifying Data
Stored Procedures
Linq to Entities
Chapter 31: Other Language Details
The Main Function
Returning an Int Status
Command-Line Parameters
Multiple Mains
Preprocessing
Preprocessing Directives
Preprocessor Expressions
Inline Warning Control
Other Preprocessor Functions
#warning and #error
#line
#region
Lexical Details
Identifiers
Keywords
Literals
Boolean
Integer
Real
Character
String
Verbatim Strings
Comments
Expanding Internal Accessibility
Chapter 32: Making Friends with the .NET Framework
ToString( )
Object Equality
Hashes and GetHashCode( )
Design Guidelines
Value Type Guidelines
Reference Type Guidelines
Chapter 33: System.Array and the Collection Classes
Sorting and Searching
Specifying a Sort Order
Multiple Sort Orders
Ad Hoc Sorting Orders
Overloading Relational Operators
Advanced Use of Hash Codes
Synchronized Collections
Case-Insensitive Collections
Collection Classes
Design Guidelines
Chapter 34: Threading
Data Protection and Synchronization
A Slightly Broken Example
Protection Techniques
Don’t Share Data
Immutable Objects
Exclusion Primitives
The lock Statement
Interlocked Operations
Mutexes
Access Reordering and Volatile
Singletons
Threads
Joining
Waiting with WaitHandle
Chapter 35: Asynchronous and Parallel Programming
History
Thread Pools
Introducing Tasks
Tasks with Return Values
The async and await Keywords
Tasks and Completion Ports
Tasks and Parallel Operations
Data Parallelism
PLinq
Design Guidelines
Chapter 36: Execution-Time Code Generation
Loading Assemblies
Making It Dynamic
Code Generation at Runtime
Expressing the Algorithm in Code
Translating and Loading the Code
Calling the Code
Design Guidelines
The C# Compiler As a Service
Chapter 37: Interop
COM Objects
Calling Native DLL Functions
Pointers and Declarative Pinning
A Safe Version
Structure Layout
Calling a Function with a Structure Parameter
Fixed-Size Buffers
Hooking Up to a Windows Callback
The Marshal Class
Design Guidelines
C# or C++?
Marshaling Best Practices
Chapter 38: .NET Base Class Library Overview
Numeric Formatting
Standard Format Strings
Currency
Decimal
Scientific (Exponential)
Fixed-Point
General
Number
Round-Trip
Hexadecimal
NumberFormatInfo
Custom Format Strings
Digit or Zero Placeholder
Digit or Space Placeholder
Decimal Point
Group Separator
Number Prescaler
Percent Notation
Exponential Notation
Section Separator
Escapes and Literals
Date and Time Formatting
Custom DateTime Format
Custom Object Formatting
Numeric Parsing
Using TryParse to Avoid Exceptions
Input and Output
Binary
Text
XML
Serial Ports
Writing Files
Reading Files
Traversing Directories
Starting Processes
Redirecting Process Output
Detecting Process Completion
Serialization
Custom Serialization
XML Serialization
XmlSerializer or XElement?
Reading Web Pages
Accessing Environment Settings
Chapter 39: Deeper into C#
C# Style
Naming
Guidelines for the Library Author
Class Naming
Unsafe Context
XML Documentation
Compiler Support Tags
Generating Real Documentation
XML Documentation Tags
XML Include Files
Garbage Collection in the .NET Runtime
Allocation
Mark and Compact
Generations
Finalization
Controlling GC Behavior
Forcing a Collection
Suppressing Finalization
Deeper Reflection
Listing All the Types in an Assembly
Finding Members
Invoking Functions
Dealing with Generics
Optimizations
Chapter 40: Logging and Debugging Techniques
Conditional Methods
Asserts
Changing the Assert Behavior
Adding Other Messages to Debug or Trace Output
Using Switches to Control Debug and Trace
BooleanSwitch
TraceSwitch
User-Defined Switch
Capturing Process Metadata
Improving Your Debugger Experience
The DebuggerDisplay Attribute
Changing the Display of Existing Types
Changing the Detail Display for a Type
Full Customization of the Detail Display
Debugger Visualizers
Debugging into the .NET Framework
Chapter 41: IDEs and Utilities
IDEs
Unit Testing and TDD
Test Utilities/Runners
Disassemblers and Decompilers
Obfuscators
General Productivity
Regular Expressions
Profilers
Answering Your Questions
Index