**__**Essential C# 4.0**__** is a well-organized,“no-fluff” guide to all versions of C# for programmers at all levels of C# experience. This fully updated edition shows how to make the most of C# 4.0’s new features and programming patterns to write code that is simple, yet powerful. This edition contains two new chapters on parallel programming, multithreading, and concurrency, as well as extensive coverage of new C# 4.0 features: dynamic typing, variance, optional/named parameters, and many other new topics. Mark Michaelis covers the C# language in depth, illustrating key constructs with succinct, downloadable code examples. Graphical “mind maps” at the beginning of each chapter show what material is covered and how individual topics interrelate. Topics intended for beginners and advanced readers are clearly marked, and the book includes indexes of C# versions (2.0, 3.0, and 4.0), which make it easy for readers to reference topics specific to a given release of C#. Following an introduction to C#, readers learn about * Best practices for object-oriented programming in C# * C# primitive data types, value and reference types, implicitly typed variables, anonymous types, plus dynamic typing in C# 4.0 * Methods and parameters–including extension methods, partial methods, and C# 4.0’s optional and named parameters * Generics, concurrent collections, and custom collections with iterators * Delegates, events, and lambda expressions * Collection interfaces and standard query operators * Query expressions and the tree expressions on which LINQ providers are based * Reflection, attributes, and dynamic programming * Parallel Query Processing with PLINQ * Multithreaded programming with the Task Parallel Library * Platform interoperability and unsafe code * The Common Language Infrastructure that underlies C# Whether you’re just starting out, are an experienced developer moving to C#, or are a seasoned C# programmer seeking to master C# 4.0’s most valuable enhancements, Essential C# 4.0 will help you write high-quality, highly effective code. Essential C# 4.0 Contents Figures Tables Foreword Preface Acknowledgments About the Author 1 Introducing C# Hello, World Compiling and Running the Application C# Syntax Fundamentals Type Definition Main Statements and Statement Delimiters Whitespace Working with Variables Data Types Declaring a Variable Assigning a Variable Using a Variable Console Input and Output Getting Input from the Console Writing Output to the Console Comments Managed Execution and the Common Language Infrastructure C# and .NET Versioning Common Intermediate Language and ILDASM Summary 2 Data Types Fundamental Numeric Types Integer Types Floating-Point Types (float, double) Decimal Type Literal Values More Fundamental Types Boolean Type (bool) Character Type (char) Strings null and void null The void Nontype Categories of Types Value Types Reference Types Nullable Modifier Conversions between Data Types Explicit Cast Implicit Conversion Type Conversion without Casting Arrays Declaring an Array Instantiating and Assigning Arrays Using an Array Strings as Arrays Common Errors Summary 3 Operators and Control Flow Operators Plus and Minus Unary Operators (+, -) Arithmetic Binary Operators (+, -, *, /, %) Parenthesis Operator Assignment Operators (+=, -=, *=, /=, %=) Increment and Decrement Operators (++, --) Constant Expressions (const) Introducing Flow Control if Statement Nested if Code Blocks ({}) Scope and Declaration Space Boolean Expressions Relational and Equality Operators Logical Boolean Operators Logical Negation Operator (!) Conditional Operator (?) Null Coalescing Operator (??) Bitwise Operators (< >, |, &, ^, ~) Shift Operators (< >, < >=) Bitwise Operators (&, |, ^) Bitwise Assignment Operators (&=, |=, ^=) Bitwise Complement Operator (~) Control Flow Statements, Continued The while and do/while Loops The for Loop The foreach Loop The switch Statement Jump Statements The break Statement The continue Statement The goto Statement C# Preprocessor Directives Excluding and Including Code (#if, #elif, #else, #endif) Defining Preprocessor Symbols (#define, #undef) Emitting Errors and Warnings (#error, #warning) Turning Off Warning Messages (#pragma) nowarn: Option Specifying Line Numbers (#line) Hints for Visual Editors (#region, #endregion) Summary 4 Methods and Parameters Calling a Method Namespace Type Name Scope Method Name Parameters Method Return Statement versus Method Call Declaring a Method Parameter Declaration Method Return Declaration The using Directive Aliasing Returns and Parameters on Main() Parameters Value Parameters Reference Parameters (ref) Output Parameters (out) Parameter Arrays (params) Recursion Method Overloading Optional Parameters Basic Error Handling with Exceptions Trapping Errors Reporting Errors Using a throw Statement Summary 5 Classes Declaring and Instantiating a Class Instance Fields Declaring an Instance Field Accessing an Instance Field Instance Methods Using the this Keyword Access Modifiers Properties Declaring a Property Automatically Implemented Properties Naming Conventions Using Properties with Validation Read-Only and Write-Only Properties Access Modifiers on Getters and Setters Properties as Virtual Fields Properties and Method Calls Not Allowed as ref or out Parameter Values Constructors Declaring a Constructor Default Constructors Object Initializers Overloading Constructors Constructor Chaining: Calling another Constructor Using this Static Members Static Fields Static Methods Static Constructors Static Properties Static Classes Extension Methods Encapsulating the Data const readonly Nested Classes Partial Classes Defining a Partial Class Partial Methods Summary 6 Inheritance Derivation Casting between Base and Derived Types private Access Modifier protected Access Modifier Extension Methods Single Inheritance Sealed Classes Overriding the Base Class virtual Modifier new Modifier sealed Modifier base Member Constructors Abstract Classes All Classes Derive from System.Object Verifying the Underlying Type with the is Operator Conversion Using the as Operator Summary 7 Interfaces Introducing Interfaces Polymorphism through Interfaces Interface Implementation Explicit Member Implementation Implicit Member Implementation Explicit versus Implicit Interface Implementation Converting between the Implementing Class and Its Interfaces Interface Inheritance Multiple Interface Inheritance Extension Methods on Interfaces Implementing Multiple Inheritance via Interfaces Versioning Interfaces Compared with Classes Summary 8 Value Types Structs Initializing structs Using the default Operator Inheritance and Interfaces with Value Types Boxing Enums Type Compatibility between Enums Converting between Enums and Strings Enums as Flags Summary 9 Well-Formed Types Overriding object Members Overriding ToString() Overriding GetHashCode() Overriding Equals() Guidelines for Implementing Equality Operator Overloading Comparison Operators (==, !=, , =) Binary Operators (+, -, *, /, %, &, |, ^, < >) Combining Assignment with Binary Operators (+=, -=, *=, /=, %=, &=...) Conditional Logical Operators (&&, ||) Unary Operators (+, -, !, ~, ++, --, true, false) Conversion Operators Guidelines for Conversion Operators Referencing Other Assemblies Changing the Assembly Target Referencing an Assembly Encapsulation of Types Defining Namespaces Namespace Alias Qualifier XML Comments Associating XML Comments with Programming Constructs Generating an XML Documentation File Garbage Collection Weak References Resource Cleanup Finalizers Deterministic Finalization with the using Statement Garbage Collection and Finalization Resource Utilization and Finalization Guidelines Lazy Initialization Summary 10 Exception Handling Multiple Exception Types Catching Exceptions General Catch Block Guidelines for Exception Handling Defining Custom Exceptions Summary 11 Generics C# without Generics Introducing Generic Types Using a Generic Class Defining a Simple Generic Class Benefits of Generics Type Parameter Naming Guidelines Generic Interfaces and Structs Defining a Constructor and a Finalizer Specifying a Default Value Multiple Type Parameters Arity in Abundance Nested Generic Types Constraints Interface Constraints Base Class Constraints struct/class Constraints Multiple Constraints Constructor Constraints Constraint Inheritance Generic Methods Type Inferencing Specifying Constraints Covariance and Contravariance Enabling Covariance with the out Type Parameter Modifier in C# 4.0 Enabling Contravariance with the in Type Parameter Modifier in C# 4.0 Support for Parameter Covariance and Contravariance in Arrays Generic Internals Instantiating Generics Based on Value Types Instantiating Generics Based on Reference Types Summary 12 Delegates and Lambda Expressions Introducing Delegates Defining the Scenario Delegate Data Types Delegate Internals Defining a Delegate Type Instantiating a Delegate Anonymous Methods System-Defined Delegates: Func Lambda Expressions Statement Lambdas Expression Lambdas Outer Variables Expression Trees Summary 13 Events Coding the Observer Pattern with Multicast Delegates Defining Subscriber Methods Defining the Publisher Hooking Up the Publisher and Subscribers Invoking a Delegate Check for null Delegate Operators Sequential Invocation Error Handling Method Returns and Pass-by-Reference Events Why Events? Declaring an Event Coding Conventions Generics and Delegates Customizing the Event Implementation Summary 14 Collection Interfaces with Standard Query Operators Anonymous Types and Implicitly Typed Local Variables Anonymous Types Implicitly Typed Local Variables (var) More about Anonymous Types and Implicit Local Variables Collection Initializers What Makes a Class a Collection: I Enumerable foreach with Arrays foreach with I Enumerable Do Not Modify Collections during foreach Iteration Standard Query Operators Filtering with Where() Projecting with Select() Counting Elements with Count() Deferred Execution Sorting with OrderBy() and ThenBy() Performing an Inner Join with Join() Grouping Results with GroupBy() Implementing a One-to-Many Relationship with GroupJoin() Calling SelectMany() More Standard Query Operators Summary 15 LINQ with Query Expressions Introducing Query Expressions Projection Filtering Sorting The Let Clause Grouping Query Continuation with into Query Expressions as Method Invocations Summary 16 Building Custom Collections More Collection Interfaces Ilist versus IDictionary IComparable ICollection Primary Collection Classes List Collections: List Dictionary Collections: Dictionary Sorted Collections: SortedDictionary and SortedList Stack Collections: Stack Queue Collections: Queue Linked Lists: LinkedList Providing an Index Operator Returning Null or an Empty Collection Iterators Defining an Iterator Iterator Syntax Yielding Values from an Iterator Iterators and State More Iterator Examples Placing a yield return within a Loop Canceling Further Iteration: yield break Creating Multiple Iterators in a Single Class yield Statement Characteristics Summary 17 Reflection, Attributes, and Dynamic Programming Reflection Accessing Metadata Using System.Type Member Invocation Reflection on Generic Types Attributes Custom Attributes Looking for Attributes Initializing an Attribute through a Constructor System.AttributeUsageAttribute Named Parameters Programming with Dynamic Objects Invoking Reflection Using dynamic dynamic Principles and Behaviors Why Dynamic Binding? Static Compilation versus Dynamic Programming Implementing a Custom Dynamic Object Summary 18 Multithreading Running and Controlling a Separate Thread ContinueWith() Unhandled Exception Handling on Task Canceling a Task Long-Running Tasks Disposing a Task Executing Iterations in Parallel Parallel Exception Handling with System.AggregateException Canceling a Parallel Loop Running LINQ Queries in Parallel Canceling a PLINQ Query Multithreading before .NET Framework 4 Asynchronous Operations with System.Threading.Thread Thread Management Thread Pooling Unhandled Exceptions on the AppDomain Summary 19 Synchronization and More Multithreading Patterns Synchronization Synchronization Using Monitor Using the Lock Keyword Choosing a Lock Object Why to Avoid Locking on this, typeof(type), and string Declaring Fields as volatile Using the System.Threading.Interlocked Class Event Notification with Multiple Threads Synchronization Design Best Practices More Synchronization Types Thread Local Storage Timers Asynchronous Programming Model Calling the APM Calling the APM Using TPL Asynchronous Delegate Invocation Passing Data to and from an Alternate Thread Event-Based Asynchronous Pattern (EAP) Background Worker Pattern Establishing the Pattern Exception Handling Windows UI Programming Windows Forms Windows Presentation Foundation (WPF) Summary 20 Platform Interoperability and Unsafe Code Platform Invoke Declaring External Functions Parameter Data Types Using ref Rather Than Pointers Using StructLayoutAttribute for Sequential Layout Error Handling Using SafeHandle Calling External Functions Simplifying API Calls with Wrappers Function Pointers Map to Delegates Guidelines Pointers and Addresses Unsafe Code Pointer Declaration Assigning a Pointer Dereferencing a Pointer Accessing the Member of a Referent Type Summary 21 The Common Language Infrastructure Defining the Common Language Infrastructure (CLI) CLI Implementations C# Compilation to Machine Code Runtime Garbage Collection Garbage Collection on .NET Type Safety Code Access Security Platform Portability Performance Application Domains Assemblies, Manifests, and Modules Common Intermediate Language (CIL) Common Type System (CTS) Common Language Specification (CLS) Base Class Library (BCL) Metadata Summary A: Downloading and Installing the C# Compiler and the CLI Platform B: Full Source Code Listings C: Concurrent Classes from System.Collections.Concurrent D: C# 2.0 Topics E: C# 3.0 Topics F: C# 4.0 Topics Index
essential C# 4.0 Is A Well-organized,“no-fluff” Guide To All Versions Of C# For Programmers At All Levels Of C# Experience. This Fully Updated Edition Shows How To Make The Most Of C# 4.0’s New Features And Programming Patterns To Write Code That Is Simple, Yet Powerful.
this Edition Contains Two New Chapters On Parallel Programming, Multithreading, And Concurrency, As Well As Extensive Coverage Of New C# 4.0 Features: Dynamic Typing, Variance, Optional/named Parameters, And Many Other New Topics.
mark Michaelis Covers The C# Language In Depth, Illustrating Key Constructs With Succinct, Downloadable Code Examples. Graphical “mind Maps” At The Beginning Of Each Chapter Show What Material Is Covered And How Individual Topics Interrelate. Topics Intended For Beginners And Advanced Readers Are Clearly Marked, And The Book Includes Indexes Of C# Versions (2.0, 3.0, And 4.0), Which Make It Easy For Readers To Reference Topics Specific To A Given Release Of C#.
following An Introduction To C#, Readers Learn About
- Best Practices For Object-oriented Programming In C#
- C# Primitive Data Types, Value And Reference Types, Implicitly Typed Variables, Anonymous Types, Plus Dynamic Typing In C# 4.0
- Methods And Parameters–including Extension Methods, Partial Methods, And C# 4.0’s Optional And Named Parameters
- Generics, Concurrent Collections, And Custom Collections With Iterators
- Delegates, Events, And Lambda Expressions
- Collection Interfaces And Standard Query Operators
- Query Expressions And The Tree Expressions On Which Linq Providers Are Based
- Reflection, Attributes, And Dynamic Programming
- Parallel Query Processing With Plinq
- Multithreaded Programming With The Task Parallel Library
- Platform Interoperability And Unsafe Code
- The Common Language Infrastructure That Underlies C#
whether You’re Just Starting Out, Are An Experienced Developer Moving To C#, Or Are A Seasoned C# Programmer Seeking To Master C# 4.0’s Most Valuable Enhancements, Essential C# 4.0 Will Help You Write High-quality, Highly Effective Code.
This is a well-organized, "no fluff" guide to all versions of C♯ for programmers at all levels. This edition shows how to make the most of C♯ 4.0's new features and programming to write code that is simple, yet powerful.--[book cover]