Illustrated C# 7: The C# Language Presented Clearly, Concisely, and Visually

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"

Get to work quickly with C# with a uniquely succinct and visual format used to present the C# 7.0 language. Whether you're getting to grips with C# for the first time or working to deepen your understanding, you'll find this book to be a clear and refreshing take on each aspect of the language. Figures are of prime importance in this book. While teaching programming seminars, Daniel Solis found that he could almost watch the light bulbs going on over the students' heads as he drew the figures on the whiteboard. In this text, he has distilled each important concept into simple but accurate illustrations. For this latest edition, Dan is joined by fellow experienced teacher and programmer, Cal Schrotenboer, to bring you the very latest C# language features, along with an understanding of the frameworks it most often lives in: .NET and the new .NET Core. For something as intricate and precise as a programming language, there must be text as well as figures. But rather than long, wordy explanations, the authors use short, concise descriptions and bullet lists to make each important piece of information visually distinct and memorable. What You'll Learn Start with an overview of C# programming and how the language works under the hood Put things in context with a little useful history of C# and .NET Know how .NET Core fits into the picture Understand how C# handles types Benefit from clear, concise explanations of each language feature, from classes and inheritance to enumerators and iterators, and the new C# 7.0 tuples Quickly access material via this book's visual introduction to asynchronous programming with C# Who This Book Is For Novice to intermediate C# programmers, and more experienced programmers moving to C# from other languages

Author(s): Daniel Solis; Cal Schrotenboer
Edition: 5
Publisher: Apress
Year: 2018

Language: English
Pages: 799

Contents
About the Authors
About the Technical Reviewers
Acknowledgments
Introduction
Chapter 1: C# and the .NET Framework
Before .NET
Windows Programming in the Late 1990s
Goals for the Next-Generation Platform Services
Enter Microsoft .NET
Components of the .NET Framework
An Improved Programming Environment
Object-Oriented Development Environment
Automatic Garbage Collection
Interoperability
No COM Required
Simplified Deployment
Type Safety
The Base Class Library
Compiling to the Common Intermediate Language
Compiling to Native Code and Execution
Overview of Compilation and Execution
The Common Language Runtime
The Common Language Infrastructure
Important Parts of the CLI
The Common Type System
The Common Language Specification
Review of the Acronyms
The Evolution of C#
C# and the Evolution of Windows
Chapter 2: C# and .NET Core
The .NET Framework Background
Why .NET Core (and Xamarin)?
Goals of .NET Core
Multiplatform Support
Rapid Development and Upgrades
Smaller Application Footprints, Simpler Deployment, and Reduced Versioning Problems
Open Source Community Support
Improved Application Performance
Fresh Start
The Development of .NET Core
Where Does This Leave the .NET Framework?
Where Does Xamarin Fit In?
Chapter 3: Overview of C# Programming
A Simple C# Program
More About SimpleProgram
Identifiers
Keywords
Main: The Starting Point of a Program
Whitespace
Statements
Blocks
Text Output from a Program
Write
WriteLine
The Format String
Multiple Markers and Values
Formatting Numeric Strings
The Alignment Specifier
The Format Field
Standard Numeric Format Specifiers
Comments: Annotating the Code
More About Comments
Documentation Comments
Summary of Comment Types
Chapter 4: Types, Storage, and Variables
A C# Program Is a Set of Type Declarations
A Type Is a Template
Instantiating a Type
Data Members and Function Members
Types of Members
Predefined Types
More About the Predefined Types
User-Defined Types
The Stack and the Heap
The Stack
Facts About Stacks
The Heap
Value Types and Reference Types
Storing Members of a Reference Type Object
Categorizing the C# Types
Variables
Variable Declarations
Variable Initializers
Automatic Initialization
Multiple-Variable Declarations
Using the Value of a Variable
Static Typing and the dynamic Keyword
Nullable Types
Chapter 5: Classes: The Basics
Overview of Classes
A Class Is an Active Data Structure
Programs and Classes: A Quick Example
Declaring a Class
Class Members
Fields
Explicit and Implicit Field Initialization
Declarations with Multiple Fields
Methods
Creating Variables and Instances of a Class
Allocating Memory for the Data
Combining the Steps
Instance Members
Access Modifiers
Private and Public Access
Depicting Public and Private Access
Example of Member Access
Accessing Members from Inside the Class
Accessing Members from Outside the Class
Putting It All Together
Chapter 6: Methods
The Structure of a Method
Code Execution in the Method Body
Local Variables
Type Inference and the var Keyword
Local Variables Inside Nested Blocks
Local Constants
Flow of Control
Method Invocations
Return Values
The Return Statement and Void Methods
Local Functions
Parameters
Formal Parameters
Actual Parameters
An Example of Methods with Positional Parameters
Value Parameters
Reference Parameters
Reference Types As Value and Reference Parameters
Output Parameters
Parameter Arrays
Method Invocation
Expanded Form
Arrays As Actual Parameters
Summary of Parameter Types
Ref Local and Ref Return
Method Overloading
Named Parameters
Optional Parameters
Stack Frames
Recursion
Chapter 7: More About Classes
Class Members
Order of Member Modifiers
Instance Class Members
Static Fields
Accessing Static Members from Outside the Class
Example of a Static Field
Lifetimes of Static Members
Static Function Members
Other Static Class Member Types
Member Constants
Constants Are Like Statics
Properties
Property Declarations and Accessors
A Property Example
Using a Property
Properties and Associated Fields
Performing Other Calculations
Read-Only and Write-Only Properties
Properties vs. Public Fields
An Example of a Computed, Read-Only Property
Automatically Implemented Properties—Auto-properties
Static Properties
Instance Constructors
Constructors with Parameters
Default Constructors
Static Constructors
Example of a Static Constructor
Object Initializers
Destructors
The readonly Modifier
The this Keyword
Indexers
What Is an Indexer?
Indexers and Properties
Declaring an Indexer
The Indexer set Accessor
The Indexer get Accessor
More About Indexers
Declaring the Indexer for the Employee Example
Another Indexer Example
Indexer Overloading
Access Modifiers on Accessors
Partial Classes and Partial Types
Partial Methods
Chapter 8: Classes and Inheritance
Class Inheritance
Accessing the Inherited Members
All Classes Are Derived from Class object
Masking Members of a Base Class
Base Access
Using References to a Base Class
Virtual and Override Methods
Overriding a Method Marked override
Case 1: Declaring Print with override
Case 2: Declaring Print with new
Overriding Other Member Types
Constructor Execution
Constructor Initializers
Class Access Modifiers
Inheritance Between Assemblies
Member Access Modifiers
Regions Accessing a Member
Public Member Accessibility
Private Member Accessibility
Protected Member Accessibility
Internal Member Accessibility
Protected Internal Member Accessibility
Summary of Member Access Modifiers
Abstract Members
Abstract Classes
Example of an Abstract Class and an Abstract Method
Another Example of an Abstract Class
Sealed Classes
Static Classes
Extension Methods
Naming Conventions
Chapter 9: Expressions and Operators
Expressions
Literals
Integer Literals
Real Literals
Character Literals
String Literals
Order of Evaluation
Precedence
Associativity
Simple Arithmetic Operators
The Remainder Operator
Relational and Equality Comparison Operators
Comparison and Equality Operations
Increment and Decrement Operators
Conditional Logical Operators
Logical Operators
Shift Operators
Assignment Operators
Compound Assignment
The Conditional Operator
Unary Arithmetic Operators
User-Defined Type Conversions
Explicit Conversion and the Cast Operator
Operator Overloading
Example of Operator Overloading
Restrictions on Operator Overloading
The typeof Operator
The nameof Operator
Other Operators
Chapter 10: Statements
What Are Statements?
Expression Statements
Flow-of-Control Statements
The if Statement
The if…else Statement
The while Loop
The do Loop
The for Loop
The Scope of Variables in a for Statement
Multiple Expressions in the Initializer and Iteration Expression
The switch Statement
A Switch Example Involving Constants
Other Types of Pattern Expressions
More on the switch Statement
Switch Labels
Jump Statements
The break Statement
The continue Statement
Labeled Statements
Labels
The Scope of Labeled Statements
The goto Statement
The goto Statement Inside a switch Statement
The using Statement
Packaging the Use of a Resource
Example of the using Statement
Multiple Resources and Nesting
Another Form of the using Statement
Other Statements
Chapter 11: Structs
What Are Structs?
Structs Are Value Types
Assigning to a Struct
Constructors and Destructors
Instance Constructors
Static Constructors
Summary of Constructors and Destructors
Property and Field Initializers
Structs Are Sealed
Boxing and Unboxing
Structs As Return Values and Parameters
Additional Information About Structs
Chapter 12: Enumerations
Enumerations
Setting the Underlying Type and Explicit Values
Implicit Member Numbering
Bit Flags
The Flags Attribute
Example Using Bit Flags
More About Enums
Chapter 13: Arrays
Arrays
Definitions
Important Details
Types of Arrays
An Array As an Object
One-Dimensional and Rectangular Arrays
Declaring a One-Dimensional or Rectangular Array
Instantiating a One-Dimensional or Rectangular Array
Accessing Array Elements
Initializing an Array
Explicit Initialization of One-Dimensional Arrays
Explicit Initialization of Rectangular Arrays
Syntax Points for Initializing Rectangular Arrays
Shortcut Syntax
Implicitly Typed Arrays
Putting It All Together
Jagged Arrays
Declaring a Jagged Array
Shortcut Instantiation
Instantiating a Jagged Array
Subarrays in Jagged Arrays
Comparing Rectangular and Jagged Arrays
The foreach Statement
The Iteration Variable Is Read-Only
The foreach Statement with Multidimensional Arrays
Example with a Rectangular Array
Example with a Jagged Array
Array Covariance
Useful Inherited Array Members
The Clone Method
Comparing Array Types
Arrays and Ref Return and Ref Local
Chapter 14: Delegates
What Is a Delegate?
An Overview of Delegates
Declaring the Delegate Type
Creating the Delegate Object
Assigning Delegates
Combining Delegates
Adding Methods to Delegates
Removing Methods from a Delegate
Invoking a Delegate
Delegate Example
Invoking Delegates with Return Values
Invoking Delegates with Reference Parameters
Anonymous Methods
Using Anonymous Methods
Syntax of Anonymous Methods
Return Type
Parameters
The params Parameters
Scope of Variables and Parameters
Outer Variables
Extension of a Captured Variable’s Lifetime
Lambda Expressions
Chapter 15: Events
Publishers and Subscribers
Overview of Source Code Components
Declaring an Event
An Event Is a Member
Subscribing to an Event
Raising an Event
Standard Event Usage
Passing Data by Extending EventArgs
Removing Event Handlers
Event Accessors
Chapter 16: Interfaces
What Is an Interface?
Example Using the IComparable Interface
Declaring an Interface
Implementing an Interface
Example with a Simple Interface
An Interface Is a Reference Type
Using the as Operator with Interfaces
Implementing Multiple Interfaces
Implementing Interfaces with Duplicate Members
References to Multiple Interfaces
An Inherited Member As an Implementation
Explicit Interface Member Implementations
Accessing Explicit Interface Member Implementations
Interfaces Can Inherit Interfaces
Example of Different Classes Implementing an Interface
Chapter 17: Conversions
What Are Conversions?
Implicit Conversions
Explicit Conversions and Casting
Casting
Types of Conversions
Numeric Conversions
Implicit Numeric Conversions
Overflow Checking Context
The checked and unchecked Operators
The checked and unchecked Statements
Explicit Numeric Conversions
Integer Type to Integer Type
float or double to Integer Type
decimal to Integer Type
double to float
float or double to decimal
decimal to float or double
Reference Conversions
Implicit Reference Conversions
Explicit Reference Conversions
Valid Explicit Reference Conversions
Boxing Conversions
Boxing Creates a Copy
The Boxing Conversions
Unboxing Conversions
The Unboxing Conversions
User-Defined Conversions
Constraints on User-Defined Conversions
Example of a User-Defined Conversion
Evaluating User-Defined Conversions
Example of a Multistep User-Defined Conversion
The is Operator
The as Operator
Chapter 18: Generics
What Are Generics?
A Stack Example
Generics in C#
Continuing with the Stack Example
Generic Classes
Declaring a Generic Class
Creating a Constructed Type
Creating Variables and Instances
The Stack Example Using Generics
Comparing the Generic and Nongeneric Stack
Constraints on Type Parameters
Where Clauses
Constraint Types and Order
Generic Methods
Declaring a Generic Method
Invoking a Generic Method
Inferring Types
Example of a Generic Method
Extension Methods with Generic Classes
Generic Structs
Generic Delegates
Another Generic Delegate Example
Generic Interfaces
An Example Using Generic Interfaces
Generic Interface Implementations Must Be Unique
Covariance and Contravariance
Covariance
Contravariance
Summarizing the Differences Between Covariance and Contravariance
Covariance and Contravariance in Interfaces
More About Variance
Chapter 19: Enumerators and Iterators
Enumerators and Enumerable Types
Using the foreach Statement
The IEnumerator Interface
The IEnumerable Interface
Example Using IEnumerable and IEnumerator
The Generic Enumeration Interfaces
Iterators
Iterator Blocks
Using an Iterator to Create an Enumerator
Using an Iterator to Create an Enumerable
Common Iterator Patterns
Producing Multiple Enumerables
Iterators As Properties
Behind the Scenes with Iterators
Chapter 20: Introduction to LINQ
What Is LINQ?
LINQ Providers
Anonymous Types
Method Syntax and Query Syntax
Query Variables
The Structure of Query Expressions
The from Clause
The join Clause
What Is a Join?
The from ... let ... where Section in the Query Body
The from Clause
The let Clause
The where Clause
The orderby Clause
The select . . . group Clause
Anonymous Types in Queries
The group Clause
Query Continuation: The into Clause
The Standard Query Operators
Signatures of the Standard Query Operators
Query Expressions and the Standard Query Operators
Delegates As Parameters
The LINQ Predefined Delegate Types
Example Using a Delegate Parameter
Example Using a Lambda Expression Parameter
LINQ to XML
Markup Languages
XML Basics
The XML Classes
Creating, Saving, Loading, and Displaying an XML Document
Creating an XML Tree
Using Values from the XML Tree
Adding Nodes and Manipulating XML
Working with XML Attributes
Other Types of Nodes
XComment
XDeclaration
XProcessingInstruction
Using LINQ Queries with LINQ to XML
Chapter 21: Introduction to Asynchronous Programming
What Is Asynchrony?
A Starting Example
The Structure of the async/await Feature
What Is an async Method?
The Flow of Control in an Async Method
The await Expression
Cancelling an async Operation
Exception Handling and the await Expression
Waiting Synchronously for Tasks in the Calling Method
Waiting Asynchronously for Tasks in the async Method
The Task.Delay Method
Async Operations in GUI Programs
Task.Yield
Using an async Lambda Expression
A Full GUI Example
The BackgroundWorker Class
Example of the BackgroundWorker Class in a WPF Program
Parallel Loops
Other Asynchronous Programming Patterns
BeginInvoke and EndInvoke
The Wait-Until-Done Pattern
The AsyncResult Class
The Polling Pattern
The Callback Pattern
The Callback Method
Calling EndInvoke Inside the Callback Method
Timers
Chapter 22: Namespaces and Assemblies
Referencing Other Assemblies
The mscorlib Library
Namespaces
Namespace Names
More About Namespaces
Namespaces Spread Across Files
Nesting Namespaces
The using Directives
The using Namespace Directive
The using Alias Directive
The using static Directive
The Structure of an Assembly
The Identity of an Assembly
Strongly Named Assemblies
Creating a Strongly Named Assembly
Private Deployment of an Assembly
Shared Assemblies and the GAC
Installing Assemblies into the GAC
Side-by-Side Execution in the GAC
Configuration Files
Delayed Signing
Chapter 23: Exceptions
What Are Exceptions?
The try Statement
Handling the Exception
The Exception Classes
The catch Clause
Examples Using Specific catch Clauses
Exception Filters
The catch Clauses Section
The finally Block
Finding a Handler for an Exception
Searching Further
General Algorithm
Example of Searching Down the Call Stack
Throwing Exceptions
Throwing Without an Exception Object
Throw Expressions
Chapter 24: Preprocessor Directives
What Are Preprocessor Directives?
General Rules
The #define and #undef Directives
Conditional Compilation
The Conditional Compilation Constructs
Diagnostic Directives
Line Number Directives
Region Directives
The #pragma warning Directive
Chapter 25: Reflection and Attributes
Metadata and Reflection
The Type Class
Getting a Type Object
What Is an Attribute?
Applying an Attribute
Predefined, Reserved Attributes
The Obsolete Attribute
The Conditional Attribute
Example of the Conditional Attribute
The Caller Information Attributes
The DebuggerStepThrough Attribute
Other Predefined Attributes
More About Applying Attributes
Multiple Attributes
Other Types of Targets
Global Attributes
Custom Attributes
Declaring a Custom Attribute
Using Attribute Constructors
Specifying the Constructor
Using the Constructor
Positional and Named Parameters in Constructors
Restricting the Usage of an Attribute
The Constructor for AttributeUsage
Suggested Practices for Custom Attributes
Accessing an Attribute
Using the IsDefined Method
Using the GetCustomAttributes Method
Chapter 26: What’s New in C# 6 and 7
What’s New
String Interpolation (C# 6.0)
Auto-Property Initializers
Read-Only Auto-Properties (C# 6.0)
Expression-Bodied Members (C# 6.0 and 7.0)
using static (C# 6.0)
Null Conditional Operator (C# 6.0)
Using await in catch and finally (C# 6.0)
The nameof Operator (C# 6.0)
Exception Filters (C# 6.0)
Index Initializers (C# 6.0)
Extension Methods for Collection Initializers (C# 6.0)
Improved Overload Resolution (C# 6.0)
ValueTuples (C# 7.0)
Pattern Matching with is (C# 7.0)
Pattern Matching with switch (C# 7.0)
Custom Deconstruct (C# 7.0)
Binary Literals and Numeric Separators (C# 7.0)
Out Variables (C# 7.0)
Local Functions (C# 7.0)
Ref Locals (Ref Variables) and Ref Returns (C# 7.0)
More Expression-Bodied Members (C# 7.0)
Throw Expressions (C# 7.0)
Expanded Async Return Types (C# 7.0)
Chapter 27: Other Topics
Overview
Strings
The StringBuilder Class
Parsing Strings to Data Values
More About the Nullable Types
Assigning to a Nullable Type
The Null Coalescing Operator
The Null Conditional Operator
Using Nullable User-Defined Types
Nullable
Method Main
Accessibility of Main
Documentation Comments
Inserting Documentation Comments
Using Other XML Tags
Nested Types
Example of a Nested Class
Visibility and Nested Types
Destructors and the Dispose Pattern
The Standard Dispose Pattern
Comparing Constructors and Destructors
Tuples and ValueTuples
Interoperating with COM
Index