100% found this document useful (3 votes)
70 views

Instant Download Pro C# 7 With .NET and .NET Core Andrew Troelsen PDF All Chapter

Core

Uploaded by

wayatcalcai
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (3 votes)
70 views

Instant Download Pro C# 7 With .NET and .NET Core Andrew Troelsen PDF All Chapter

Core

Uploaded by

wayatcalcai
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Download the full version of the textbook now at textbookfull.

com

Pro C# 7 with .NET and .NET Core Andrew


Troelsen

https://textbookfull.com/product/pro-c-7-with-net-
and-net-core-andrew-troelsen/

Explore and download more textbook at https://textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Pro C# 8 with .NET Core 3: Foundational Principles and


Practices in Programming - Ninth Edition Andrew Troelsen

https://textbookfull.com/product/pro-c-8-with-net-core-3-foundational-
principles-and-practices-in-programming-ninth-edition-andrew-troelsen/

textbookfull.com

Pro C 9 with NET 5 Foundational Principles and Practices


in Programming Tenth Edition Andrew Troelsen Phillip
Japikse
https://textbookfull.com/product/pro-c-9-with-net-5-foundational-
principles-and-practices-in-programming-tenth-edition-andrew-troelsen-
phillip-japikse/
textbookfull.com

Pro C 9 with NET 5 Foundational Principles and Practices


in Programming Tenth Edition Andrew Troelsen Phillip
Japikse
https://textbookfull.com/product/pro-c-9-with-net-5-foundational-
principles-and-practices-in-programming-tenth-edition-andrew-troelsen-
phillip-japikse-2/
textbookfull.com

Smart Card Research and Advanced Applications 16th


International Conference CARDIS 2017 Lugano Switzerland
November 13 15 2017 Revised Selected Papers 1st Edition
Thomas Eisenbarth
https://textbookfull.com/product/smart-card-research-and-advanced-
applications-16th-international-conference-cardis-2017-lugano-
switzerland-november-13-15-2017-revised-selected-papers-1st-edition-
thomas-eisenbarth/
textbookfull.com
Understanding the Modern World David Ferriby

https://textbookfull.com/product/understanding-the-modern-world-david-
ferriby/

textbookfull.com

Publication Manual of the American Psychological


Association - 7th Edition American Psychological
Association
https://textbookfull.com/product/publication-manual-of-the-american-
psychological-association-7th-edition-american-psychological-
association/
textbookfull.com

Decentralization, Regional Diversity, and Conflict: The


Case of Ukraine Hanna Shelest

https://textbookfull.com/product/decentralization-regional-diversity-
and-conflict-the-case-of-ukraine-hanna-shelest/

textbookfull.com

Architecting HBase Applications A Guidebook for Successful


Development and Design 1 (Early Release) Edition Jean-Marc
Spaggiari
https://textbookfull.com/product/architecting-hbase-applications-a-
guidebook-for-successful-development-and-design-1-early-release-
edition-jean-marc-spaggiari/
textbookfull.com

Gender and the Nuclear Family in Twenty-First-Century


Horror 1st Edition Kimberly Jackson (Auth.)

https://textbookfull.com/product/gender-and-the-nuclear-family-in-
twenty-first-century-horror-1st-edition-kimberly-jackson-auth/

textbookfull.com
The AI Advantage How to Put the Artificial Intelligence
Revolution to Work 1st Edition Thomas H. Davenport

https://textbookfull.com/product/the-ai-advantage-how-to-put-the-
artificial-intelligence-revolution-to-work-1st-edition-thomas-h-
davenport/
textbookfull.com
Pro C# 7
With .NET and .NET Core

Eighth Edition

Andrew Troelsen
Philip Japikse
Pro C# 7: With .NET and .NET Core
Andrew Troelsen Philip Japikse
Minneapolis, Minnesota, USA West Chester, Ohio, USA
ISBN-13 (pbk): 978-1-4842-3017-6 ISBN-13 (electronic): 978-1-4842-3018-3
https://doi.org/10.1007/978-1-4842-3018-3
Library of Congress Control Number: 2017958717
Copyright © 2017 by Andrew Troelsen and Philip Japikse
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the
material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage
and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or
hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with
every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are
not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to
proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material
contained herein.
Cover image by Freepik (www.freepik.com)
Managing Director: Welmoed Spahr
Editorial Director: Todd Green
Acquisitions Editor: Gwenan Spearing
Development Editor: Laura Berendson
Technical Reviewers: Eric Potter, Lee Brandt, and Sean Whitesell
Coordinating Editor: Mark Powers
Copy Editor: Kim Wimpsett
Distributed to the book trade worldwide by Springer Science+Business Media New York,
233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail
[email protected], or visit www.springeronline.com. Apress Media, LLC is a California LLC
and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc).
SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail [email protected], or visit www.apress.com/
rights-permissions.
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions
and licenses are also available for most titles. For more information, reference our Print and eBook Bulk
Sales web page at www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available to
readers on GitHub via the book’s product page, located at www.apress.com/9781484230176. For more
detailed information, please visit www.apress.com/source-code.
Printed on acid-free paper
Contents at a Glance

About the Authors����������������������������������������������������������������������������������������������������� li


About the Technical Reviewers������������������������������������������������������������������������������ liii
Acknowledgments��������������������������������������������������������������������������������������������������� lv
Introduction����������������������������������������������������������������������������������������������������������� lvii


■Part I: Introducing C# and the .NET Platform������������������������������������� 1

■Chapter 1: The Philosophy of .NET������������������������������������������������������������������������� 3

■Chapter 2: Building C# Applications�������������������������������������������������������������������� 35


■Part II: Core C# Programing�������������������������������������������������������������� 53

■Chapter 3: Core C# Programming Constructs, Part I������������������������������������������� 55

■Chapter 4: Core C# Programming Constructs, Part II���������������������������������������� 111


■Part III: Object-Oriented Programming with C#������������������������������ 159

■Chapter 5: Understanding Encapsulation���������������������������������������������������������� 161

■Chapter 6: Understanding Inheritance and Polymorphism�������������������������������� 213

■Chapter 7: Understanding Structured Exception Handling�������������������������������� 255

■Chapter 8: Working with Interfaces������������������������������������������������������������������� 283


■Part IV: Advanced C# Programming����������������������������������������������� 323

■Chapter 9: Collections and Generics������������������������������������������������������������������ 325

■Chapter 10: Delegates, Events, and Lambda Expressions��������������������������������� 365

■Chapter 11: Advanced C# Language Features��������������������������������������������������� 407

■Chapter 12: LINQ to Objects������������������������������������������������������������������������������� 445

■Chapter 13: Understanding Object Lifetime������������������������������������������������������� 479
v
■ Contents at a Glance


■Part V: Programming with .NET Assemblies����������������������������������� 507

■Chapter 14: Building and Configuring Class Libraries��������������������������������������� 509
■■Chapter 15: Type Reflection, Late Binding, and Attribute-Based Programming���� 561

■Chapter 16: Dynamic Types and the Dynamic Language Runtime�������������������� 609

■Chapter 17: Processes, AppDomains, and Object Contexts������������������������������� 631

■Chapter 18: Understanding CIL and the Role of Dynamic Assemblies��������������� 657


■Part VI: Introducing the .NET Base Class Libraries������������������������� 699

■Chapter 19: Multithreaded, Parallel, and Async Programming������������������������� 701

■Chapter 20: File I/O and Object Serialization���������������������������������������������������� 755

■Chapter 21: Data Access with ADO.NET������������������������������������������������������������� 803

■Chapter 22: Introducing Entity Framework 6���������������������������������������������������� 857

■Chapter 23: Introducing Windows Communication Foundation������������������������ 907


■Part VII: Windows Presentation Foundation����������������������������������� 963

■Chapter 24: Introducing Windows Presentation Foundation and XAML������������� 965

■Chapter 25: WPF Controls, Layouts, Events, and Data Binding������������������������ 1003

■Chapter 26: WPF Graphics Rendering Services����������������������������������������������� 1061

■Chapter 27: WPF Resources, Animations, Styles, and Templates�������������������� 1095

■Chapter 28: WPF Notifications, Validations, Commands, and MVVM��������������� 1137


■Part VIII: ASP.NET.������������������������������������������������������������������������� 1177

■Chapter 29: Introducing ASP.NET MVC������������������������������������������������������������� 1179

■Chapter 30: Introducing ASP.NET Web API������������������������������������������������������� 1223


■Part IX: .NET CORE������������������������������������������������������������������������ 1243

■Chapter 31: The Philosophy of .NET Core�������������������������������������������������������� 1245

■Chapter 32: Introducing Entity Framework Core��������������������������������������������� 1255

■Chapter 33: Introducing ASP.NET Core Web Applications�������������������������������� 1279

■Chapter 34: Introducing ASP.NET Core Service Applications��������������������������� 1329
Index������������������������������������������������������������������������������������������������������������������� 1353
vi
Contents

About the Authors����������������������������������������������������������������������������������������������������� li


About the Technical Reviewers������������������������������������������������������������������������������ liii
Acknowledgments��������������������������������������������������������������������������������������������������� lv
Introduction����������������������������������������������������������������������������������������������������������� lvii


■Part I: Introducing C# and the .NET Platform������������������������������������� 1

■Chapter 1: The Philosophy of .NET������������������������������������������������������������������������� 3
An Initial Look at the .NET Platform��������������������������������������������������������������������������������� 3
Some Key Benefits of the .NET Platform������������������������������������������������������������������������������������������������ 4

Introducing the Building Blocks of the .NET Platform (the CLR, CTS, and CLS)���������������� 4
The Role of the Base Class Libraries������������������������������������������������������������������������������������������������������ 5
What C# Brings to the Table������������������������������������������������������������������������������������������������������������������� 5
Managed vs. Unmanaged Code�������������������������������������������������������������������������������������������������������������� 8

Additional .NET-Aware Programming Languages������������������������������������������������������������� 8


Life in a Multilanguage World����������������������������������������������������������������������������������������������������������������� 9

An Overview of .NET Assemblies�������������������������������������������������������������������������������������� 9


The Role of the Common Intermediate Language�������������������������������������������������������������������������������� 10
Benefits of CIL�������������������������������������������������������������������������������������������������������������������������������������� 13
Compiling CIL to Platform-Specific Instructions����������������������������������������������������������������������������������� 13
The Role of .NET Type Metadata����������������������������������������������������������������������������������������������������������� 13
The Role of the Assembly Manifest������������������������������������������������������������������������������������������������������ 14

Understanding the Common Type System���������������������������������������������������������������������� 15


CTS Class Types������������������������������������������������������������������������������������������������������������������������������������ 15
CTS Interface Types������������������������������������������������������������������������������������������������������������������������������ 16

vii
■ Contents

CTS Structure Types����������������������������������������������������������������������������������������������������������������������������� 16


CTS Enumeration Types������������������������������������������������������������������������������������������������������������������������ 17
CTS Delegate Types������������������������������������������������������������������������������������������������������������������������������ 17
CTS Type Members������������������������������������������������������������������������������������������������������������������������������� 17
Intrinsic CTS Data Types����������������������������������������������������������������������������������������������������������������������� 18

Understanding the Common Language Specification���������������������������������������������������� 19


Ensuring CLS Compliance��������������������������������������������������������������������������������������������������������������������� 20

Understanding the Common Language Runtime������������������������������������������������������������ 20


The Assembly/Namespace/Type Distinction������������������������������������������������������������������ 22
The Role of the Microsoft Root Namespace����������������������������������������������������������������������������������������� 25
Accessing a Namespace Programmatically����������������������������������������������������������������������������������������� 25
Referencing External Assemblies��������������������������������������������������������������������������������������������������������� 26

Exploring an Assembly Using ildasm.exe����������������������������������������������������������������������� 27


Viewing CIL Code���������������������������������������������������������������������������������������������������������������������������������� 28
Viewing Type Metadata������������������������������������������������������������������������������������������������������������������������� 29
Viewing Assembly Metadata (aka the Manifest)����������������������������������������������������������������������������������� 30

The Platform-Independent Nature of .NET��������������������������������������������������������������������� 30


The Mono Project���������������������������������������������������������������������������������������������������������������������������������� 32
Xamarin������������������������������������������������������������������������������������������������������������������������������������������������ 32
Microsoft .NET Core������������������������������������������������������������������������������������������������������������������������������ 32

Summary������������������������������������������������������������������������������������������������������������������������ 33

■Chapter 2: Building C# Applications�������������������������������������������������������������������� 35
Building .NET Applications on Windows������������������������������������������������������������������������� 35
Installing Visual Studio 2017���������������������������������������������������������������������������������������������������������������� 36
Taking Visual Studio 2017 for a Test-Drive������������������������������������������������������������������������������������������� 38
Visual Studio 2017 Professional����������������������������������������������������������������������������������������������������������� 50
Visual Studio 2017 Enterprise�������������������������������������������������������������������������������������������������������������� 50
The .NET Framework Documentation System�������������������������������������������������������������������������������������� 50

Building.NET Applications on a Non-Windows OS���������������������������������������������������������� 52


Summary������������������������������������������������������������������������������������������������������������������������ 52

viii
■ Contents


■Part II: Core C# Programing�������������������������������������������������������������� 53

■Chapter 3: Core C# Programming Constructs, Part I������������������������������������������� 55
The Anatomy of a Simple C# Program���������������������������������������������������������������������������� 55
Variations on the Main( ) Method���������������������������������������������������������������������������������������������������������� 57
Specifying an Application Error Code��������������������������������������������������������������������������������������������������� 58
Processing Command-Line Arguments������������������������������������������������������������������������������������������������ 59
Specifying Command-Line Arguments with Visual Studio�������������������������������������������������������������������� 61

An Interesting Aside: Some Additional Members of the System.Environment Class������ 61


The System.Console Class��������������������������������������������������������������������������������������������� 63
Basic Input and Output with the Console Class������������������������������������������������������������������������������������ 63
Formatting Console Output������������������������������������������������������������������������������������������������������������������� 65
Formatting Numerical Data������������������������������������������������������������������������������������������������������������������ 65
Formatting Numerical Data Beyond Console Applications������������������������������������������������������������������� 67

System Data Types and Corresponding C# Keywords���������������������������������������������������� 68


Variable Declaration and Initialization�������������������������������������������������������������������������������������������������� 69
Intrinsic Data Types and the new Operator������������������������������������������������������������������������������������������� 71
The Data Type Class Hierarchy������������������������������������������������������������������������������������������������������������� 72
Members of Numerical Data Types������������������������������������������������������������������������������������������������������� 73
Members of System.Boolean���������������������������������������������������������������������������������������������������������������� 74
Members of System.Char��������������������������������������������������������������������������������������������������������������������� 74
Parsing Values from String Data����������������������������������������������������������������������������������������������������������� 75
Using TryParse to Parse Values from String Data��������������������������������������������������������������������������������� 75
System.DateTime and System.TimeSpan��������������������������������������������������������������������������������������������� 76
The System.Numerics.dll Assembly����������������������������������������������������������������������������������������������������� 76
Digit Separators (New)������������������������������������������������������������������������������������������������������������������������� 78
Binary Literals (New)���������������������������������������������������������������������������������������������������������������������������� 78

Working with String Data����������������������������������������������������������������������������������������������� 79


Basic String Manipulation�������������������������������������������������������������������������������������������������������������������� 80
String Concatenation���������������������������������������������������������������������������������������������������������������������������� 80
Escape Characters�������������������������������������������������������������������������������������������������������������������������������� 81

ix
■ Contents

Defining Verbatim Strings��������������������������������������������������������������������������������������������������������������������� 82


Strings and Equality����������������������������������������������������������������������������������������������������������������������������� 82
Strings Are Immutable�������������������������������������������������������������������������������������������������������������������������� 85
The System.Text.StringBuilder Type����������������������������������������������������������������������������������������������������� 86
String Interpolation������������������������������������������������������������������������������������������������������������������������������� 87

Narrowing and Widening Data Type Conversions����������������������������������������������������������� 88


The checked Keyword�������������������������������������������������������������������������������������������������������������������������� 91
Setting Project-wide Overflow Checking���������������������������������������������������������������������������������������������� 93
The unchecked Keyword���������������������������������������������������������������������������������������������������������������������� 93

Understanding Implicitly Typed Local Variables������������������������������������������������������������� 94


Restrictions on Implicitly Typed Variables�������������������������������������������������������������������������������������������� 95
Implicit Typed Data Is Strongly Typed Data������������������������������������������������������������������������������������������� 96
Usefulness of Implicitly Typed Local Variables������������������������������������������������������������������������������������� 97

C# Iteration Constructs��������������������������������������������������������������������������������������������������� 98
The for Loop������������������������������������������������������������������������������������������������������������������������������������������ 98
The foreach Loop���������������������������������������������������������������������������������������������������������������������������������� 99
Use of Implicit Typing Within foreach Constructs��������������������������������������������������������������������������������� 99
The while and do/while Looping Constructs�������������������������������������������������������������������������������������� 100

Decision Constructs and the Relational/Equality Operators����������������������������������������� 101


The if/else Statement������������������������������������������������������������������������������������������������������������������������� 101
Equality and Relational Operators������������������������������������������������������������������������������������������������������ 101
The Conditional Operator�������������������������������������������������������������������������������������������������������������������� 102
Logical Operators������������������������������������������������������������������������������������������������������������������������������� 103
The switch Statement������������������������������������������������������������������������������������������������������������������������� 103
Using Pattern Matching in Switch Statements (New)������������������������������������������������������������������������� 106

Summary���������������������������������������������������������������������������������������������������������������������� 109

■Chapter 4: Core C# Programming Constructs, Part II���������������������������������������� 111
Understanding C# Arrays���������������������������������������������������������������������������������������������� 111
C# Array Initialization Syntax�������������������������������������������������������������������������������������������������������������� 112
Implicitly Typed Local Arrays�������������������������������������������������������������������������������������������������������������� 113

x
■ Contents

Defining an Array of Objects��������������������������������������������������������������������������������������������������������������� 114


Working with Multidimensional Arrays����������������������������������������������������������������������������������������������� 115
Arrays As Arguments or Return Values����������������������������������������������������������������������������������������������� 116
The System.Array Base Class������������������������������������������������������������������������������������������������������������� 117

Methods and Parameter Modifiers������������������������������������������������������������������������������� 118


Return Values and Expression Bodied Members (Updated)���������������������������������������������������������������� 119
Method Parameter Modifiers�������������������������������������������������������������������������������������������������������������� 119
Discards���������������������������������������������������������������������������������������������������������������������������������������������� 120
The Default by Value Parameter-Passing Behavior����������������������������������������������������������������������������� 120
The out Modifier (Updated)����������������������������������������������������������������������������������������������������������������� 121
The ref Modifier���������������������������������������������������������������������������������������������������������������������������������� 123
ref Locals and Returns (New)������������������������������������������������������������������������������������������������������������� 124
The params Modifier�������������������������������������������������������������������������������������������������������������������������� 126
Defining Optional Parameters������������������������������������������������������������������������������������������������������������� 127
Invoking Methods Using Named Parameters������������������������������������������������������������������������������������� 129
Understanding Method Overloading��������������������������������������������������������������������������������������������������� 131
Local Functions (New)������������������������������������������������������������������������������������������������������������������������ 133

Understanding the enum Type�������������������������������������������������������������������������������������� 134


Controlling the Underlying Storage for an enum�������������������������������������������������������������������������������� 135
Declaring enum Variables������������������������������������������������������������������������������������������������������������������� 136
The System.Enum Type���������������������������������������������������������������������������������������������������������������������� 137
Dynamically Discovering an enum’s Name-Value Pairs��������������������������������������������������������������������� 137

Understanding the Structure (aka Value Type)������������������������������������������������������������� 139


Creating Structure Variables��������������������������������������������������������������������������������������������������������������� 141

Understanding Value Types and Reference Types�������������������������������������������������������� 142


Value Types, References Types, and the Assignment Operator����������������������������������������������������������� 143
Value Types Containing Reference Types�������������������������������������������������������������������������������������������� 145
Passing Reference Types by Value������������������������������������������������������������������������������������������������������ 147
Passing Reference Types by Reference���������������������������������������������������������������������������������������������� 149
Final Details Regarding Value Types and Reference Types����������������������������������������������������������������� 150

xi
■ Contents

Understanding C# Nullable Types��������������������������������������������������������������������������������� 150


Working with Nullable Types�������������������������������������������������������������������������������������������������������������� 152
The Null Coalescing Operator������������������������������������������������������������������������������������������������������������� 153
The Null Conditional Operator������������������������������������������������������������������������������������������������������������� 153

Tuples (New)����������������������������������������������������������������������������������������������������������������� 154


Getting Started with Tuples���������������������������������������������������������������������������������������������������������������� 155
Inferred Variable Names (C# 7.1)�������������������������������������������������������������������������������������������������������� 156
Tuples As Method Return Values�������������������������������������������������������������������������������������������������������� 156
Discards with Tuples��������������������������������������������������������������������������������������������������������������������������� 157
Deconstructing Tuples������������������������������������������������������������������������������������������������������������������������ 157

Summary���������������������������������������������������������������������������������������������������������������������� 158


■Part III: Object-Oriented Programming with C#������������������������������ 159

■Chapter 5: Understanding Encapsulation���������������������������������������������������������� 161
Introducing the C# Class Type�������������������������������������������������������������������������������������� 161
Allocating Objects with the new Keyword������������������������������������������������������������������������������������������ 164

Understanding Constructors����������������������������������������������������������������������������������������� 165


The Role of the Default Constructor��������������������������������������������������������������������������������������������������� 165
Defining Custom Constructors������������������������������������������������������������������������������������������������������������ 166
The Default Constructor Revisited������������������������������������������������������������������������������������������������������ 167

The Role of the this Keyword��������������������������������������������������������������������������������������� 169


Chaining Constructor Calls Using this������������������������������������������������������������������������������������������������ 170
Observing Constructor Flow��������������������������������������������������������������������������������������������������������������� 173
Revisiting Optional Arguments����������������������������������������������������������������������������������������������������������� 174

Understanding the static Keyword������������������������������������������������������������������������������� 176


Defining Static Field Data������������������������������������������������������������������������������������������������������������������� 176
Defining Static Methods��������������������������������������������������������������������������������������������������������������������� 178
Defining Static Constructors��������������������������������������������������������������������������������������������������������������� 179
Defining Static Classes����������������������������������������������������������������������������������������������������������������������� 182
Importing Static Members via the C# using Keyword������������������������������������������������������������������������ 183

xii
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
■ Contents

Defining the Pillars of OOP������������������������������������������������������������������������������������������� 184


The Role of Encapsulation������������������������������������������������������������������������������������������������������������������ 184
The Role of Inheritance����������������������������������������������������������������������������������������������������������������������� 184
The Role of Polymorphism������������������������������������������������������������������������������������������������������������������ 186

C# Access Modifiers����������������������������������������������������������������������������������������������������� 188


The Default Access Modifiers������������������������������������������������������������������������������������������������������������� 188
Access Modifiers and Nested Types��������������������������������������������������������������������������������������������������� 189

The First Pillar: C#’s Encapsulation Services��������������������������������������������������������������� 190


Encapsulation Using Traditional Accessors and Mutators������������������������������������������������������������������ 191
Encapsulation Using .NET Properties������������������������������������������������������������������������������������������������� 193
Using Properties Within a Class Definition����������������������������������������������������������������������������������������� 196
Read-Only and Write-Only Properties������������������������������������������������������������������������������������������������� 198
Revisiting the static Keyword: Defining Static Properties������������������������������������������������������������������ 199

Understanding Automatic Properties���������������������������������������������������������������������������� 199


Interacting with Automatic Properties������������������������������������������������������������������������������������������������ 201
Automatic Properties and Default Values������������������������������������������������������������������������������������������� 201
Initialization of Automatic Properties�������������������������������������������������������������������������������������������������� 203

Understanding Object Initialization Syntax������������������������������������������������������������������� 204


Calling Custom Constructors with Initialization Syntax���������������������������������������������������������������������� 205
Initializing Data with Initialization Syntax������������������������������������������������������������������������������������������� 207

Working with Constant Field Data�������������������������������������������������������������������������������� 208


Understanding Read-Only Fields�������������������������������������������������������������������������������������������������������� 209
Static Read-Only Fields���������������������������������������������������������������������������������������������������������������������� 210

Understanding Partial Classes������������������������������������������������������������������������������������� 211


Use Cases for Partial Classes?����������������������������������������������������������������������������������������������������������� 212

Summary���������������������������������������������������������������������������������������������������������������������� 212

■Chapter 6: Understanding Inheritance and Polymorphism�������������������������������� 213
The Basic Mechanics of Inheritance���������������������������������������������������������������������������� 213
Specifying the Parent Class of an Existing Class�������������������������������������������������������������������������������� 214
Regarding Multiple Base Classes������������������������������������������������������������������������������������������������������� 216
The sealed Keyword��������������������������������������������������������������������������������������������������������������������������� 216
xiii
■ Contents

Revisiting Visual Studio Class Diagrams���������������������������������������������������������������������� 218


The Second Pillar of OOP: The Details of Inheritance��������������������������������������������������� 220
Controlling Base Class Creation with the base Keyword�������������������������������������������������������������������� 221
Keeping Family Secrets: The protected Keyword������������������������������������������������������������������������������� 223
Adding a Sealed Class������������������������������������������������������������������������������������������������������������������������ 224

Programming for Containment/Delegation������������������������������������������������������������������� 225


Understanding Nested Type Definitions���������������������������������������������������������������������������������������������� 226

The Third Pillar of OOP: C#’s Polymorphic Support������������������������������������������������������ 228


The virtual and override Keywords����������������������������������������������������������������������������������������������������� 229
Overriding Virtual Members Using the Visual Studio IDE�������������������������������������������������������������������� 231
Sealing Virtual Members�������������������������������������������������������������������������������������������������������������������� 233
Understanding Abstract Classes��������������������������������������������������������������������������������������������������������� 233
Understanding the Polymorphic Interface������������������������������������������������������������������������������������������ 236
Understanding Member Shadowing��������������������������������������������������������������������������������������������������� 240

Understanding Base Class/Derived Class Casting Rules���������������������������������������������� 241


The C# as Keyword����������������������������������������������������������������������������������������������������������������������������� 243
The C# is Keyword (Updated)������������������������������������������������������������������������������������������������������������� 245
Pattern Matching Revisited (New)������������������������������������������������������������������������������������������������������ 246

The Master Parent Class: System.Object��������������������������������������������������������������������� 247


Overriding System.Object.ToString()��������������������������������������������������������������������������������������������������� 250
Overriding System.Object.Equals()����������������������������������������������������������������������������������������������������� 250
Overriding System.Object.GetHashCode()������������������������������������������������������������������������������������������ 251
Testing Your Modified Person Class���������������������������������������������������������������������������������������������������� 252
The Static Members of System.Object����������������������������������������������������������������������������������������������� 253

Summary���������������������������������������������������������������������������������������������������������������������� 254

■Chapter 7: Understanding Structured Exception Handling�������������������������������� 255
Ode to Errors, Bugs, and Exceptions���������������������������������������������������������������������������� 255
The Role of .NET Exception Handling��������������������������������������������������������������������������� 256
The Building Blocks of .NET Exception Handling�������������������������������������������������������������������������������� 257
The System.Exception Base Class������������������������������������������������������������������������������������������������������ 257

xiv
■ Contents

The Simplest Possible Example����������������������������������������������������������������������������������� 259


Throwing a General Exception (Updated)������������������������������������������������������������������������������������������� 261
Catching Exceptions��������������������������������������������������������������������������������������������������������������������������� 262

Configuring the State of an Exception�������������������������������������������������������������������������� 264


The TargetSite Property���������������������������������������������������������������������������������������������������������������������� 264
The StackTrace Property��������������������������������������������������������������������������������������������������������������������� 265
The HelpLink Property������������������������������������������������������������������������������������������������������������������������ 265
The Data Property������������������������������������������������������������������������������������������������������������������������������� 266

System-Level Exceptions (System.SystemException)�������������������������������������������������� 268


Application-Level Exceptions (System.ApplicationException)�������������������������������������� 268
Building Custom Exceptions, Take 1��������������������������������������������������������������������������������������������������� 269
Building Custom Exceptions, Take 2��������������������������������������������������������������������������������������������������� 271
Building Custom Exceptions, Take 3��������������������������������������������������������������������������������������������������� 272

Processing Multiple Exceptions����������������������������������������������������������������������������������� 273


General catch Statements������������������������������������������������������������������������������������������������������������������ 276
Rethrowing Exceptions����������������������������������������������������������������������������������������������������������������������� 276
Inner Exceptions��������������������������������������������������������������������������������������������������������������������������������� 277
The finally Block��������������������������������������������������������������������������������������������������������������������������������� 278
Exception Filters��������������������������������������������������������������������������������������������������������������������������������� 279

Debugging Unhandled Exceptions Using Visual Studio������������������������������������������������ 280


Summary���������������������������������������������������������������������������������������������������������������������� 281

■Chapter 8: Working with Interfaces������������������������������������������������������������������� 283
Understanding Interface Types������������������������������������������������������������������������������������� 283
Interface Types vs. Abstract Base Classes����������������������������������������������������������������������������������������� 284

Defining Custom Interfaces������������������������������������������������������������������������������������������ 286


Implementing an Interface������������������������������������������������������������������������������������������� 288
Invoking Interface Members at the Object Level���������������������������������������������������������� 290
Obtaining Interface References: The as Keyword������������������������������������������������������������������������������� 291
Obtaining Interface References: The is Keyword (Updated)��������������������������������������������������������������� 292

xv
■ Contents

Interfaces As Parameters��������������������������������������������������������������������������������������������� 293


Interfaces As Return Values����������������������������������������������������������������������������������������� 295
Arrays of Interface Types���������������������������������������������������������������������������������������������� 296
Implementing Interfaces Using Visual Studio��������������������������������������������������������������� 297
Explicit Interface Implementation�������������������������������������������������������������������������������� 299
Designing Interface Hierarchies����������������������������������������������������������������������������������� 301
Multiple Inheritance with Interface Types������������������������������������������������������������������������������������������� 303

The IEnumerable and IEnumerator Interfaces�������������������������������������������������������������� 305


Building Iterator Methods with the yield Keyword������������������������������������������������������������������������������ 308
Building a Named Iterator������������������������������������������������������������������������������������������������������������������� 310

The ICloneable Interface���������������������������������������������������������������������������������������������� 311


A More Elaborate Cloning Example���������������������������������������������������������������������������������������������������� 313

The IComparable Interface������������������������������������������������������������������������������������������� 316


Specifying Multiple Sort Orders with IComparer�������������������������������������������������������������������������������� 319
Custom Properties and Custom Sort Types���������������������������������������������������������������������������������������� 320

Summary���������������������������������������������������������������������������������������������������������������������� 321


■Part IV: Advanced C# Programming����������������������������������������������� 323

■Chapter 9: Collections and Generics������������������������������������������������������������������ 325
The Motivation for Collection Classes�������������������������������������������������������������������������� 325
The System.Collections Namespace�������������������������������������������������������������������������������������������������� 327
A Survey of System.Collections.Specialized Namespace������������������������������������������������������������������� 329

The Problems of Nongeneric Collections��������������������������������������������������������������������� 330


The Issue of Performance������������������������������������������������������������������������������������������������������������������� 330
The Issue of Type Safety��������������������������������������������������������������������������������������������������������������������� 333
A First Look at Generic Collections����������������������������������������������������������������������������������������������������� 336

The Role of Generic Type Parameters�������������������������������������������������������������������������� 337


Specifying Type Parameters for Generic Classes/Structures������������������������������������������������������������� 339
Specifying Type Parameters for Generic Members����������������������������������������������������������������������������� 340
Specifying Type Parameters for Generic Interfaces���������������������������������������������������������������������������� 340

xvi
■ Contents

The System.Collections.Generic Namespace��������������������������������������������������������������� 342


Understanding Collection Initialization Syntax����������������������������������������������������������������������������������� 343
Working with the List<T> Class��������������������������������������������������������������������������������������������������������� 345
Working with the Stack<T> Class������������������������������������������������������������������������������������������������������ 346
Working with the Queue<T> Class����������������������������������������������������������������������������������������������������� 347
Working with the SortedSet<T> Class����������������������������������������������������������������������������������������������� 348
Working with the Dictionary<TKey, TValue> Class����������������������������������������������������������������������������� 350

The System.Collections.ObjectModel Namespace������������������������������������������������������� 351


Working with ObservableCollection<T>��������������������������������������������������������������������������������������������� 352

Creating Custom Generic Methods������������������������������������������������������������������������������� 354


Inference of Type Parameters������������������������������������������������������������������������������������������������������������� 356
Creating Custom Generic Structures and Classes�������������������������������������������������������� 357
The default Keyword in Generic Code������������������������������������������������������������������������������������������������ 358

Constraining Type Parameters�������������������������������������������������������������������������������������� 360


Examples Using the where Keyword�������������������������������������������������������������������������������������������������� 360
The Lack of Operator Constraints������������������������������������������������������������������������������������������������������� 362

Summary���������������������������������������������������������������������������������������������������������������������� 363

■Chapter 10: Delegates, Events, and Lambda Expressions��������������������������������� 365
Understanding the .NET Delegate Type������������������������������������������������������������������������ 365
Defining a Delegate Type in C#����������������������������������������������������������������������������������������������������������� 366
The System.MulticastDelegate and System.Delegate Base Classes�������������������������������������������������� 369

The Simplest Possible Delegate Example�������������������������������������������������������������������� 370


Investigating a Delegate Object���������������������������������������������������������������������������������������������������������� 372

Sending Object State Notifications Using Delegates���������������������������������������������������� 373


Enabling Multicasting������������������������������������������������������������������������������������������������������������������������� 376
Removing Targets from a Delegate’s Invocation List�������������������������������������������������������������������������� 378
Method Group Conversion Syntax������������������������������������������������������������������������������������������������������ 379

Understanding Generic Delegates�������������������������������������������������������������������������������� 380


The Generic Action<> and Func<> Delegates����������������������������������������������������������������������������������� 382

xvii
■ Contents

Understanding C# Events��������������������������������������������������������������������������������������������� 384


The C# event Keyword������������������������������������������������������������������������������������������������������������������������ 386
Events Under the Hood����������������������������������������������������������������������������������������������������������������������� 387
Listening to Incoming Events������������������������������������������������������������������������������������������������������������� 388
Simplifying Event Registration Using Visual Studio���������������������������������������������������������������������������� 389
Cleaning Up Event Invocation Using the C# 6.0 Null-Conditional Operator���������������������������������������� 391
Creating Custom Event Arguments����������������������������������������������������������������������������������������������������� 392
The Generic EventHandler<T> Delegate�������������������������������������������������������������������������������������������� 393

Understanding C# Anonymous Methods���������������������������������������������������������������������� 394


Accessing Local Variables������������������������������������������������������������������������������������������������������������������ 396

Understanding Lambda Expressions���������������������������������������������������������������������������� 397


Dissecting a Lambda Expression�������������������������������������������������������������������������������������������������������� 400
Processing Arguments Within Multiple Statements���������������������������������������������������������������������������� 401
Lambda Expressions with Multiple (or Zero) Parameters������������������������������������������������������������������� 403
Retrofitting the CarEvents Example Using Lambda Expressions�������������������������������������������������������� 404
Lambdas and Expression-Bodied Members (Updated)����������������������������������������������������������������������� 404

Summary���������������������������������������������������������������������������������������������������������������������� 406

■Chapter 11: Advanced C# Language Features��������������������������������������������������� 407
Understanding Indexer Methods���������������������������������������������������������������������������������� 407
Indexing Data Using String Values������������������������������������������������������������������������������������������������������ 409
Overloading Indexer Methods������������������������������������������������������������������������������������������������������������� 411
Indexers with Multiple Dimensions���������������������������������������������������������������������������������������������������� 411
Indexer Definitions on Interface Types������������������������������������������������������������������������������������������������ 412

Understanding Operator Overloading��������������������������������������������������������������������������� 412


Overloading Binary Operators������������������������������������������������������������������������������������������������������������� 413
And What of the += and –= Operators?��������������������������������������������������������������������������������������������� 416
Overloading Unary Operators������������������������������������������������������������������������������������������������������������� 416
Overloading Equality Operators���������������������������������������������������������������������������������������������������������� 417
Overloading Comparison Operators���������������������������������������������������������������������������������������������������� 418
Final Thoughts Regarding Operator Overloading�������������������������������������������������������������������������������� 418

xviii
■ Contents

Understanding Custom Type Conversions�������������������������������������������������������������������� 419


Recall: Numerical Conversions����������������������������������������������������������������������������������������������������������� 419
Recall: Conversions Among Related Class Types�������������������������������������������������������������������������������� 419
Creating Custom Conversion Routines����������������������������������������������������������������������������������������������� 420
Additional Explicit Conversions for the Square Type�������������������������������������������������������������������������� 423
Defining Implicit Conversion Routines������������������������������������������������������������������������������������������������ 424

Understanding Extension Methods������������������������������������������������������������������������������� 425


Defining Extension Methods��������������������������������������������������������������������������������������������������������������� 426
Invoking Extension Methods��������������������������������������������������������������������������������������������������������������� 427
Importing Extension Methods������������������������������������������������������������������������������������������������������������� 428
The IntelliSense of Extension Methods����������������������������������������������������������������������������������������������� 428
Extending Types Implementing Specific Interfaces���������������������������������������������������������������������������� 429

Understanding Anonymous Types�������������������������������������������������������������������������������� 431


Defining an Anonymous Type�������������������������������������������������������������������������������������������������������������� 431
The Internal Representation of Anonymous Types������������������������������������������������������������������������������ 432
The Implementation of ToString() and GetHashCode()������������������������������������������������������������������������ 434
The Semantics of Equality for Anonymous Types������������������������������������������������������������������������������� 434
Anonymous Types Containing Anonymous Types������������������������������������������������������������������������������� 436

Working with Pointer Types������������������������������������������������������������������������������������������ 436


The unsafe Keyword��������������������������������������������������������������������������������������������������������������������������� 438
Working with the * and & Operators��������������������������������������������������������������������������������������������������� 440
An Unsafe (and Safe) Swap Function������������������������������������������������������������������������������������������������� 441
Field Access via Pointers (the -> Operator)���������������������������������������������������������������������������������������� 442
The stackalloc Keyword���������������������������������������������������������������������������������������������������������������������� 442
Pinning a Type via the fixed Keyword������������������������������������������������������������������������������������������������� 443
The sizeof Keyword���������������������������������������������������������������������������������������������������������������������������� 444

Summary���������������������������������������������������������������������������������������������������������������������� 444

■Chapter 12: LINQ to Objects������������������������������������������������������������������������������� 445
LINQ-Specific Programming Constructs����������������������������������������������������������������������� 445
Implicit Typing of Local Variables������������������������������������������������������������������������������������������������������� 446
Object and Collection Initialization Syntax����������������������������������������������������������������������������������������� 446

xix
■ Contents

Lambda Expressions��������������������������������������������������������������������������������������������������������������������������� 447


Extension Methods����������������������������������������������������������������������������������������������������������������������������� 448
Anonymous Types������������������������������������������������������������������������������������������������������������������������������� 449

Understanding the Role of LINQ����������������������������������������������������������������������������������� 449


LINQ Expressions Are Strongly Typed������������������������������������������������������������������������������������������������� 450
The Core LINQ Assemblies������������������������������������������������������������������������������������������������������������������ 450

Applying LINQ Queries to Primitive Arrays������������������������������������������������������������������� 451


Once Again, Using Extension Methods����������������������������������������������������������������������������������������������� 453
Once Again, Without LINQ������������������������������������������������������������������������������������������������������������������� 453
Reflecting Over a LINQ Result Set������������������������������������������������������������������������������������������������������ 454
LINQ and Implicitly Typed Local Variables������������������������������������������������������������������������������������������ 455
LINQ and Extension Methods�������������������������������������������������������������������������������������������������������������� 457
The Role of Deferred Execution���������������������������������������������������������������������������������������������������������� 458
The Role of Immediate Execution������������������������������������������������������������������������������������������������������� 459

Returning the Result of a LINQ Query��������������������������������������������������������������������������� 460


Returning LINQ Results via Immediate Execution������������������������������������������������������������������������������ 461

Applying LINQ Queries to Collection Objects���������������������������������������������������������������� 462


Accessing Contained Subobjects������������������������������������������������������������������������������������������������������� 462
Applying LINQ Queries to Nongeneric Collections������������������������������������������������������������������������������ 463
Filtering Data Using OfType<T>( )������������������������������������������������������������������������������������������������������ 464

Investigating the C# LINQ Query Operators������������������������������������������������������������������ 465


Basic Selection Syntax����������������������������������������������������������������������������������������������������������������������� 466
Obtaining Subsets of Data������������������������������������������������������������������������������������������������������������������ 467
Projecting New Data Types����������������������������������������������������������������������������������������������������������������� 468
Obtaining Counts Using Enumerable�������������������������������������������������������������������������������������������������� 469
Reversing Result Sets������������������������������������������������������������������������������������������������������������������������� 470
Sorting Expressions���������������������������������������������������������������������������������������������������������������������������� 470
LINQ As a Better Venn Diagramming Tool������������������������������������������������������������������������������������������� 471
Removing Duplicates�������������������������������������������������������������������������������������������������������������������������� 472
LINQ Aggregation Operations�������������������������������������������������������������������������������������������������������������� 472

xx
■ Contents

The Internal Representation of LINQ Query Statements����������������������������������������������� 473


Building Query Expressions with Query Operators (Revisited)����������������������������������������������������������� 474
Building Query Expressions Using the Enumerable Type and Lambda Expressions��������������������������� 474
Building Query Expressions Using the Enumerable Type and Anonymous Methods�������������������������� 476
Building Query Expressions Using the Enumerable Type and Raw Delegates������������������������������������ 476

Summary���������������������������������������������������������������������������������������������������������������������� 478

■Chapter 13: Understanding Object Lifetime������������������������������������������������������� 479
Classes, Objects, and References�������������������������������������������������������������������������������� 479
The Basics of Object Lifetime��������������������������������������������������������������������������������������� 480
The CIL of new������������������������������������������������������������������������������������������������������������������������������������ 481
Setting Object References to null������������������������������������������������������������������������������������������������������� 483

The Role of Application Roots��������������������������������������������������������������������������������������� 483


Understanding Object Generations������������������������������������������������������������������������������� 485
Concurrent Garbage Collection Prior to .NET 4.0��������������������������������������������������������� 486
Background Garbage Collection Under .NET 4.0 and Beyond�������������������������������������� 487
The System.GC Type����������������������������������������������������������������������������������������������������� 487
Forcing a Garbage Collection�������������������������������������������������������������������������������������������������������������� 488

Building Finalizable Objects����������������������������������������������������������������������������������������� 491


Overriding System.Object.Finalize()���������������������������������������������������������������������������������������������������� 492
Detailing the Finalization Process������������������������������������������������������������������������������������������������������ 494

Building Disposable Objects����������������������������������������������������������������������������������������� 494


Reusing the C# using Keyword����������������������������������������������������������������������������������������������������������� 497

Building Finalizable and Disposable Types������������������������������������������������������������������� 498


A Formalized Disposal Pattern����������������������������������������������������������������������������������������������������������� 499

Understanding Lazy Object Instantiation���������������������������������������������������������������������� 501


Customizing the Creation of the Lazy Data����������������������������������������������������������������������������������������� 504

Summary���������������������������������������������������������������������������������������������������������������������� 505

xxi
■ Contents


■Part V: Programming with .NET Assemblies����������������������������������� 507

■Chapter 14: Building and Configuring Class Libraries��������������������������������������� 509
Defining Custom Namespaces������������������������������������������������������������������������������������� 509
Resolving Name Clashes with Fully Qualified Names������������������������������������������������������������������������ 511
Resolving Name Clashes with Aliases������������������������������������������������������������������������������������������������ 513
Creating Nested Namespaces������������������������������������������������������������������������������������������������������������ 514
The Default Namespace of Visual Studio�������������������������������������������������������������������������������������������� 515

The Role of .NET Assemblies���������������������������������������������������������������������������������������� 516


Assemblies Promote Code Reuse������������������������������������������������������������������������������������������������������� 517
Assemblies Establish a Type Boundary���������������������������������������������������������������������������������������������� 517
Assemblies Are Versionable Units������������������������������������������������������������������������������������������������������ 517
Assemblies Are Self-Describing��������������������������������������������������������������������������������������������������������� 517
Assemblies Are Configurable�������������������������������������������������������������������������������������������������������������� 518

Understanding the Format of a .NET Assembly������������������������������������������������������������ 518


The Windows File Header������������������������������������������������������������������������������������������������������������������� 518
The CLR File Header��������������������������������������������������������������������������������������������������������������������������� 520
CIL Code, Type Metadata, and the Assembly Manifest������������������������������������������������������������������������ 520
Optional Assembly Resources������������������������������������������������������������������������������������������������������������ 521

Building and Consuming Custom Class Library������������������������������������������������������������ 521


Exploring the Manifest������������������������������������������������������������������������������������������������������������������������ 524
Exploring the CIL��������������������������������������������������������������������������������������������������������������������������������� 527
Exploring the Type Metadata�������������������������������������������������������������������������������������������������������������� 528
Building a C# Client Application���������������������������������������������������������������������������������������������������������� 529
Building a Visual Basic Client Application������������������������������������������������������������������������������������������� 530
Cross-Language Inheritance in Action������������������������������������������������������������������������������������������������ 532

Understanding Private Assemblies������������������������������������������������������������������������������� 533


The Identity of a Private Assembly����������������������������������������������������������������������������������������������������� 533
Understanding the Probing Process��������������������������������������������������������������������������������������������������� 533
Configuring Private Assemblies���������������������������������������������������������������������������������������������������������� 534
The Role of the App.Config File����������������������������������������������������������������������������������������������������������� 536

xxii
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
■ Contents

Understanding Shared Assemblies������������������������������������������������������������������������������ 538


The Global Assembly Cache���������������������������������������������������������������������������������������������������������������� 539
Understanding Strong Names������������������������������������������������������������������������������������������������������������� 541
Generating Strong Names at the Command Line������������������������������������������������������������������������������� 542
Generating Strong Names Using Visual Studio����������������������������������������������������������������������������������� 544
Installing Strongly Named Assemblies to the GAC����������������������������������������������������������������������������� 546

Consuming a Shared Assembly������������������������������������������������������������������������������������ 548


Exploring the Manifest of SharedCarLibClient������������������������������������������������������������������������������������ 550

Configuring Shared Assemblies����������������������������������������������������������������������������������� 550


Freezing the Current Shared Assembly���������������������������������������������������������������������������������������������� 551
Building a Shared Assembly Version 2.0.0.0�������������������������������������������������������������������������������������� 552
Dynamically Redirecting to Specific Versions of a Shared Assembly������������������������������������������������� 554

Understanding Publisher Policy Assemblies���������������������������������������������������������������� 555


Disabling Publisher Policy������������������������������������������������������������������������������������������������������������������ 556

Understanding the <codeBase> Element�������������������������������������������������������������������� 557


The System.Configuration Namespace������������������������������������������������������������������������ 558
The Configuration File Schema Documentation����������������������������������������������������������� 560
Summary���������������������������������������������������������������������������������������������������������������������� 560
■■Chapter 15: Type Reflection, Late Binding, and Attribute-Based
Programming����������������������������������������������������������������������������������������������������� 561
The Necessity of Type Metadata����������������������������������������������������������������������������������� 561
Viewing (Partial) Metadata for the EngineState Enumeration������������������������������������������������������������ 562
Viewing (Partial) Metadata for the Car Type��������������������������������������������������������������������������������������� 563
Examining a TypeRef�������������������������������������������������������������������������������������������������������������������������� 565
Documenting the Defining Assembly�������������������������������������������������������������������������������������������������� 565
Documenting Referenced Assemblies������������������������������������������������������������������������������������������������ 565
Documenting String Literals��������������������������������������������������������������������������������������������������������������� 566

Understanding Reflection��������������������������������������������������������������������������������������������� 566


The System.Type Class����������������������������������������������������������������������������������������������������������������������� 567
Obtaining a Type Reference Using System.Object.GetType()�������������������������������������������������������������� 568

xxiii
■ Contents

Obtaining a Type Reference Using typeof()����������������������������������������������������������������������������������������� 568


Obtaining a Type Reference Using System.Type.GetType()����������������������������������������������������������������� 569

Building a Custom Metadata Viewer���������������������������������������������������������������������������� 569


Reflecting on Methods������������������������������������������������������������������������������������������������������������������������ 570
Reflecting on Fields and Properties���������������������������������������������������������������������������������������������������� 570
Reflecting on Implemented Interfaces����������������������������������������������������������������������������������������������� 571
Displaying Various Odds and Ends����������������������������������������������������������������������������������������������������� 571
Implementing Main()�������������������������������������������������������������������������������������������������������������������������� 572
Reflecting on Generic Types��������������������������������������������������������������������������������������������������������������� 573
Reflecting on Method Parameters and Return Values������������������������������������������������������������������������ 574

Dynamically Loading Assemblies��������������������������������������������������������������������������������� 575


Reflecting on Shared Assemblies��������������������������������������������������������������������������������� 578
Understanding Late Binding����������������������������������������������������������������������������������������� 580
The System.Activator Class���������������������������������������������������������������������������������������������������������������� 580
Invoking Methods with No Parameters����������������������������������������������������������������������������������������������� 581
Invoking Methods with Parameters���������������������������������������������������������������������������������������������������� 582

Understanding the Role of .NET Attributes������������������������������������������������������������������� 583


Attribute Consumers��������������������������������������������������������������������������������������������������������������������������� 584
Applying Attributes in C#�������������������������������������������������������������������������������������������������������������������� 585
C# Attribute Shorthand Notation��������������������������������������������������������������������������������������������������������� 587
Specifying Constructor Parameters for Attributes������������������������������������������������������������������������������ 587
The Obsolete Attribute in Action��������������������������������������������������������������������������������������������������������� 587

Building Custom Attributes������������������������������������������������������������������������������������������� 588


Applying Custom Attributes���������������������������������������������������������������������������������������������������������������� 589
Named Property Syntax���������������������������������������������������������������������������������������������������������������������� 589
Restricting Attribute Usage����������������������������������������������������������������������������������������������������������������� 590

Assembly-Level Attributes������������������������������������������������������������������������������������������� 591


The Visual Studio AssemblyInfo.cs File���������������������������������������������������������������������������������������������� 592

Reflecting on Attributes Using Early Binding���������������������������������������������������������������� 593


Reflecting on Attributes Using Late Binding����������������������������������������������������������������� 594
Putting Reflection, Late Binding, and Custom Attributes in Perspective���������������������� 596
xxiv
■ Contents

Building an Extendable Application������������������������������������������������������������������������������ 597


Building the Multiproject ExtendableApp Solution����������������������������������������������������������������������������� 597
Building CommonSnappableTypes.dll������������������������������������������������������������������������������������������������ 598
Adding Projects to the Solution���������������������������������������������������������������������������������������������������������� 599
Adding Project References����������������������������������������������������������������������������������������������������������������� 600
Building the C# Snap-In���������������������������������������������������������������������������������������������������������������������� 601
Building the Visual Basic Snap-In������������������������������������������������������������������������������������������������������� 601
Setting the Startup Project����������������������������������������������������������������������������������������������������������������� 602
Setting the Project Build Order����������������������������������������������������������������������������������������������������������� 603
Building the Extendable Console Application������������������������������������������������������������������������������������� 604

Summary���������������������������������������������������������������������������������������������������������������������� 607

■Chapter 16: Dynamic Types and the Dynamic Language Runtime�������������������� 609
The Role of the C# dynamic Keyword��������������������������������������������������������������������������� 609
Calling Members on Dynamically Declared Data�������������������������������������������������������������������������������� 611
The Role of the Microsoft.CSharp.dll Assembly���������������������������������������������������������������������������������� 612
The Scope of the dynamic Keyword��������������������������������������������������������������������������������������������������� 613
Limitations of the dynamic Keyword�������������������������������������������������������������������������������������������������� 614
Practical Uses of the dynamic Keyword��������������������������������������������������������������������������������������������� 614

The Role of the Dynamic Language Runtime��������������������������������������������������������������� 615


The Role of Expression Trees�������������������������������������������������������������������������������������������������������������� 616
The Role of the System.Dynamic Namespace������������������������������������������������������������������������������������ 616
Dynamic Runtime Lookup of Expression Trees����������������������������������������������������������������������������������� 617

Simplifying Late-Bound Calls Using Dynamic Types���������������������������������������������������� 617


Leveraging the dynamic Keyword to Pass Arguments����������������������������������������������������������������������� 618

Simplifying COM Interoperability Using Dynamic Data������������������������������������������������� 621


The Role of Primary Interop Assemblies��������������������������������������������������������������������������������������������� 622
Embedding Interop Metadata������������������������������������������������������������������������������������������������������������� 623
Common COM Interop Pain Points������������������������������������������������������������������������������������������������������ 624

COM Interop Using C# Dynamic Data��������������������������������������������������������������������������� 625


COM interop Without C# Dynamic Data���������������������������������������������������������������������������������������������� 628

Summary���������������������������������������������������������������������������������������������������������������������� 629
xxv
■ Contents


■Chapter 17: Processes, AppDomains, and Object Contexts������������������������������� 631
The Role of a Windows Process����������������������������������������������������������������������������������� 631
The Role of Threads���������������������������������������������������������������������������������������������������������������������������� 632

Interacting with Processes Under the .NET Platform��������������������������������������������������� 633


Enumerating Running Processes�������������������������������������������������������������������������������������������������������� 635
Investigating a Specific Process��������������������������������������������������������������������������������������������������������� 636
Investigating a Process’s Thread Set�������������������������������������������������������������������������������������������������� 637
Investigating a Process’s Module Set������������������������������������������������������������������������������������������������� 639
Starting and Stopping Processes Programmatically�������������������������������������������������������������������������� 640
Controlling Process Startup Using the ProcessStartInfo Class����������������������������������������������������������� 641

Understanding .NET Application Domains�������������������������������������������������������������������� 643


The System.AppDomain Class������������������������������������������������������������������������������������������������������������ 643

Interacting with the Default Application Domain���������������������������������������������������������� 645


Enumerating Loaded Assemblies������������������������������������������������������������������������������������������������������� 646
Receiving Assembly Load Notifications���������������������������������������������������������������������������������������������� 647

Creating New Application Domains������������������������������������������������������������������������������ 648


Loading Assemblies into Custom Application Domains���������������������������������������������������������������������� 650
Programmatically Unloading AppDomains����������������������������������������������������������������������������������������� 651

Understanding Object Context Boundaries������������������������������������������������������������������� 652


Context-Agile and Context-Bound Types�������������������������������������������������������������������������������������������� 653
Defining a Context-Bound Object������������������������������������������������������������������������������������������������������� 654
Inspecting an Object’s Context����������������������������������������������������������������������������������������������������������� 654

Summarizing Processes, AppDomains, and Context���������������������������������������������������� 656


Summary���������������������������������������������������������������������������������������������������������������������� 656

■Chapter 18: Understanding CIL and the Role of Dynamic Assemblies��������������� 657
Motivations for Learning the Grammar of CIL�������������������������������������������������������������� 657
Examining CIL Directives, Attributes, and Opcodes������������������������������������������������������ 658
The Role of CIL Directives������������������������������������������������������������������������������������������������������������������� 659
The Role of CIL Attributes������������������������������������������������������������������������������������������������������������������� 659

xxvi
■ Contents

The Role of CIL Opcodes��������������������������������������������������������������������������������������������������������������������� 659


The CIL Opcode/CIL Mnemonic Distinction����������������������������������������������������������������������������������������� 659

Pushing and Popping: The Stack-Based Nature of CIL������������������������������������������������� 660


Understanding Round-Trip Engineering����������������������������������������������������������������������� 662
The Role of CIL Code Labels��������������������������������������������������������������������������������������������������������������� 665
Interacting with CIL: Modifying an *.il File������������������������������������������������������������������������������������������ 665
Compiling CIL Code Using ilasm.exe�������������������������������������������������������������������������������������������������� 667
The Role of peverify.exe��������������������������������������������������������������������������������������������������������������������� 668

Understanding CIL Directives and Attributes���������������������������������������������������������������� 668


Specifying Externally Referenced Assemblies in CIL�������������������������������������������������������������������������� 668
Defining the Current Assembly in CIL������������������������������������������������������������������������������������������������� 669
Defining Namespaces in CIL��������������������������������������������������������������������������������������������������������������� 670
Defining Class Types in CIL����������������������������������������������������������������������������������������������������������������� 670
Defining and Implementing Interfaces in CIL������������������������������������������������������������������������������������� 672
Defining Structures in CIL������������������������������������������������������������������������������������������������������������������� 672
Defining Enums in CIL������������������������������������������������������������������������������������������������������������������������ 673
Defining Generics in CIL��������������������������������������������������������������������������������������������������������������������� 673
Compiling the CILTypes.il File������������������������������������������������������������������������������������������������������������� 674

.NET Base Class Library, C#, and CIL Data Type Mappings������������������������������������������� 675
Defining Type Members in CIL�������������������������������������������������������������������������������������� 675
Defining Field Data in CIL������������������������������������������������������������������������������������������������������������������� 676
Defining Type Constructors in CIL������������������������������������������������������������������������������������������������������� 676
Defining Properties in CIL������������������������������������������������������������������������������������������������������������������� 677
Defining Member Parameters������������������������������������������������������������������������������������������������������������� 678

Examining CIL Opcodes������������������������������������������������������������������������������������������������ 678


The .maxstack Directive��������������������������������������������������������������������������������������������������������������������� 681
Declaring Local Variables in CIL��������������������������������������������������������������������������������������������������������� 681
Mapping Parameters to Local Variables in CIL����������������������������������������������������������������������������������� 682
The Hidden this Reference����������������������������������������������������������������������������������������������������������������� 682
Representing Iteration Constructs in CIL�������������������������������������������������������������������������������������������� 683

xxvii
Random documents with unrelated
content Scribd suggests to you:
I am, etc.
319
W. Pulteney.

Few persons did understand his conduct, and sensitive pride kept
his lips sealed. Nevertheless to all unprejudiced minds his conduct
needed no defence. On that higher plane where truth and justice are
alone considered (for justice is applied truth), Pitt did not swerve from
the principles which he at first laid down. From the beginning of the
Hastings case he had sought to hold the balances even. He left it open
to his colleagues to differ from him. He refused the publication of
papers favourable to Hastings where they compromised the welfare of
the State or the characters of our Indian feudatories. He insisted that
the charges against Hastings should be clearly drawn up, and that he
should be allowed to answer those charges in person. On the topic of
the Rohilla War he did not speak, doubtless because his mind was not
made up. The fact that Parliament had three times re-appointed
Hastings after that very censurable event, did in a technical sense
screen him from prosecution now. But on the Benares affair, no such
plea could be urged. It was a question on which the present Parliament
alone had to decide.
The enormous vogue enjoyed by Macaulay’s Essays compels me
once more to notice his treatment of Pitt respecting the Benares
charge. A man of philosophic temperament once expressed a wish
that he was as sure about anything, as the great Whig historian was
about everything. This assertiveness peeps through the veil of
diffidence which Macaulay donned before delivering the verdict, that
any man with a tenth part of Pitt’s abilities ought to have convicted
Hastings on the Rohilla charge and acquitted him on the Benares
320
charge. In order to establish this assertion Macaulay passed by the
technical plea above named, which must have weighed with Pitt, and
then used his powers of special pleading to whittle down Pitt’s
arguments on the Benares case, so that they seem to turn ultimately
on the trumpery question whether the fine inflicted on the Zamindar
was rather too large or not. But we may ask, firstly, was it a small affair
to exact half a million sterling from a prince who during three years had
been hard pressed, and as a matter of fact had paid up the arrears for
which that fine was imposed? Did it concern the Zamindar alone? Did
it not concern all the subjects from whom that half million must
ultimately be wrung?
Not only did the conduct of Hastings far exceed the limits required
by justice; it was also bound up with a question on which the stability of
our Indian Empire has ever rested. So long as the feudatories of the
British Raj feel confidence in his sense of justice, India is safe.
Whenever they have cause to believe that injustice and oppression are
the characteristics of his rule, the foundations of the Indian Empire are
shaken to their base. Not without reason did Fox declare that the
decision on the Benares affair was vital to the preservation of our
ascendancy in Bengal. The statesmanlike eye of Pitt, we may be sure,
discerned the same truth. Besides, there was an additional reason why
he should now more than ever resolve to engrave the names of Justice
and Mercy on the newly formed arch of the Indian Government. As has
been shown, the recent India Bill placed greatly increased powers in
the hands of the Governor-General. Burke and Fox had taunted Pitt
with setting up a despotism from which endless suffering must flow.
The charge was hollow; but, adorned as it was by splendid rhetoric, it
created a deep impression. Was it not well, then, to show by a
concrete example that any Viceroy who violated the principles of
justice would meet with condign punishment at Westminster? A
statesman has to consider, not merely the principles of justice, as
applied to an individual; he must also think of the results of his actions
on the millions whom they will affect; and we may reasonably infer that
among the motives which led Pitt to break with many of his friends not
the least was a heartfelt desire to safeguard the relations of the
feudatories to the Suzerain Power, and to protect the myriads of
Hindoos who had no protection save in the dimly known court of
appeal at Westminster.
On the charge respecting the spoliation of the Begums of Oude,
Pitt also cast his vote against Hastings; and again a majority followed
him. It is questionable whether even the sensationally brilliant oration
of Sheridan on this affecting topic moved the House so much as the
321
silent but scornful disapproval expressed in Pitt’s vote. The
impeachment was thenceforth inevitable.
With the forensic pageant that ensued we are not here concerned.
Thenceforth the case belonged strictly to the legal domain. Its duration
throughout the years 1788–95 was certainly discreditable to British
law. Hastings out of his never affluent fortunes spent some £71,000 in
322
the vindication of his actions, and at last secured an acquittal. But
though men in Europe forgot the case amidst the potent distractions of
the French Revolution, the effect of it was not lost upon the Orient. The
comparative calm which settled benignly on India for twelve years may
be attributed largely to a renewal of confidence in the sense of justice
of our people. After the events of the year 1786 princes and peasants
alike felt assured that the most transcendent services, if smirched with
acts of injustice, would never screen a Viceroy from the censure of the
British Parliament.
CHAPTER XI
THE IRISH PROBLEM

(1785)

We have the satisfaction of having proposed a system which


will not be discredited even by its failure, and we must wait times
and seasons for carrying it into effect.—Pitt to the Duke of
Rutland, 17th August 1785.

T HERE is a story, uncertain as to date and origin, which


picturesquely describes Pitt’s indebtedness to the author of “The
323
Wealth of Nations.” Adam Smith had been invited to meet the
young Prime Minister at dinner; but some mischance delayed his
arrival. Nevertheless, the guests patiently waited for him, and on his
entrance Pitt exclaimed, “Nay, we will stand until you are seated; for
we are all your scholars.” The compliment came with none the less
graciousness because the father of Political Economy had in his work
incautiously defined a statesman as “that insidious and crafty animal.”
Pitt was now to give a new connotation to the word. Almost alone
among the politicians of the eighteenth century, he had set himself to
gain a store of knowledge which would enable him to cope with the
increasingly complex problems of his craft; and thus, in an age when a
university degree, the grand tour, and London club-life were held to be
a sufficient preparation for a political career, he came forth like a
Minerva fully armed at all points.
Among the practical questions to which the Scottish thinker turned
the attention of his age, none was more important than those dealing
with the relations between England and her American colonies, the
desirability of an unfettered trade with France, and the need of a close
union with Ireland. The first of these questions had been disposed of
by war, and the second will engage our attention in a later chapter. On
the Irish question Adam Smith strongly advocated union with Great
Britain as conferring on the smaller island the boons which had
breathed new life into Scotland, namely, freedom of trade and
deliverance from an oppressive dominant caste.
These contentions must have secured the approval of Pitt; for the
outlines of his policy both towards Ireland and France bear a striking
resemblance to those sketched in “The Wealth of Nations,” with this
important difference, that after the gain of independence by the Irish
Legislature in 1782 the union of the two Parliaments was clearly
impossible for the present. We therefore find Pitt turning his attention
to the two topics which then chiefly agitated public opinion in Ireland,
viz., the reform of Parliament and the fiscal relations to Great Britain. In
order to understand Pitt’s handling of these problems it is necessary
briefly to review the course of Anglo-Irish affairs.
The story of the dealings of England with the sister isle in the years
1688–1778 is one that it is painful to contemplate. The efforts to
dragoon the Catholic Irish out of their creed, or to grind them into the
lowest stratum of society, produced a race hatred of which we are still
reaping the dire harvest. The Celt broods over the past; and his
memory clings round the days when Papists were excluded from
Parliament, from the possession of freehold estates, from the
professions and from juries; when they might not act as guardians or
possess a horse worth more than £5; and when their Protestant
neighbours on tendering £5 could take any horse that pleased them.
All this and far more may be read in the pages of Lecky. As for the
ruffianly enactments of the Irish penal code, many of them were so
monstrous as to bring their own cure. In the latter half of the eighteenth
century even the arrogant Protestant squirearchy of Ireland found it
impossible or undesirable to enforce them.
The growth of principles of toleration and enlightenment which
marked the years 1760–80 had some effect even on the nominees of
Protestant landlords and borough-mongers who formed the bulk of the
Irish Parliament. It is a curious fact that even the narrowest and most
bigoted of governing castes cannot wholly resist the tendencies of the
times; and the Dublin Parliament, representing only a part even of the
Protestant minority of Irishmen, was no more able to keep out new
ideas than the members of the pocket boroughs of Britain could
withstand the Reform movement of 1830–32. The infiltration of novel
principles into the Irish Legislature was slower and more partial,
inasmuch as that body misrepresented even more ludicrously the
324
opinions of the mass of Irishmen. It had long been swayed by a
clique of politicians who were termed “Undertakers,” because they
undertook its manipulation, ostensibly in the interests of the British
Government, but really in their own. The traditions of the past and the
determination of the members of the Protestant Established Church to
keep the Government in their own hands, formed a massive barrier
against change. Yet the dissolving touch of the Time-Spirit and the
shocks of war were at work upon that barrier; and when the war with
the American colonies and France strained the resources of Great
Britain and Ireland past endurance, it showed signs of giving way on
two questions, the one religious, the other fiscal. In the year 1778,
Catholics who took the oath of allegiance were allowed to become in
effect owners of land, that is, they might hold land on lease for 999
years. Further, the odious temptations formerly held out to sons of
Catholics to abjure their creed were also abrogated. That year
therefore seemed to be the beginning of an epoch of toleration, which
it was the ardent desire of Pitt to crown with an act of justice too long
delayed.
At present, however, we are concerned mainly with his attempt to
reform the fiscal relations between the two islands. Until the year 1778
Irishmen were still in the state of economic vassalage to England
which the Parliaments of William III had forcibly imposed. In some
respects, especially in regard to the woollen industry, they were now
worse off than in that time of humiliation. The enactment of 1699,
which absolutely forbade the export of her woollen goods, hopelessly
crippled an otherwise promising industry. Nor was this all. Her staple
product, wool, might not be sent to foreign lands lest their
manufacturers might benefit, and become rivals to ours. That fear was
not wholly groundless in the case of France; for French weavers found
that Irish wool supplied the qualities lacking in their own wool. The
result was the rise of an extensive smuggling trade in that article from
Ireland to France, which the Government utterly failed to stop.
The outbreak of war with the American colonies, as I have said,
brought all these questions to an acute phase; and in 1776 the British
Government so far relaxed the prohibitions on export as to allow Irish
woollens to be exported for the clothing of the Irish troops serving
away from their own country. At the same time Irish fishermen were
admitted to a share in the Newfoundland and other fisheries from
which they had been excluded.
Nothing, however, was done for the most important of Irish
manufactures. The linen industry had not been severely hampered by
the British Government. While prohibiting the export of fine linens, and
of sail-cloth, in the supposed interests of British manufacturers, the
British Government granted bounties on the coarse linens exported
from Ireland; and up to the year 1771 that industry had greatly
prospered. Thereafter it underwent a serious decline. So alarming was
the shrinkage of trade and the rise of Ireland’s debt, that in 1778 Lord
North’s Ministry was fain to propose the abolition of many of the fiscal
disabilities which sapped her strength. She was to be allowed to send
her products to the British colonies and to receive theirs directly in
return; but, in order to allay the fears of British manufacturers, the old
restrictions on the Irish woollen trade remained in force. Nothing,
however, could allay those fears. At once loud complaints were raised
from Aberdeen to Plymouth, so that North gave up nearly all his
proposals; and Ireland gained little or nothing from his well meant
efforts, except that ships built in Ireland thenceforth counted as British-
325
built, and could receive bounties granted for the fisheries.
Where reason and statesmanship had failed, force was to
succeed. The utter inability of the British Government to defend Ireland
against threatened French invasions furnished the pretext for the
formation of powerful Volunteer corps, consisting solely of Protestants,
and therefore especially strong in Ulster. The Presbyterians of that
province, smarting under the civic disabilities imposed by the old Test
Act, and under an equally archaic system of commerce, demanded
redress of these grievances, in the latter of which the more lethargic
Romanists gave them increasing support. Religious antipathies were
forgotten in the face of Ireland’s urgent needs. The governing coterie
at Dublin Castle failed either to check the movement or to revive the
old schisms. It seemed that the intolerable burdens of the British fiscal
system were about to mould the jarring elements of Irish society into
the unity that marks a nation.
Though they failed to reach that far-off goal, they for the present
won a noteworthy success. By combining to refrain from the purchase
of British goods they dealt a severe blow at the system thrust upon
them. Nor did they abstain from threats of force. The Volunteers
paraded the streets of Dublin with cannon bearing the motto, “Free
Trade—or this.” In face of an overwhelming opposition, the Lord-
Lieutenant, the Earl of Carlisle, advised the British Government to give
way; and at the close of the year 1779, and early in 1780, a series of
enactments was passed at Westminster withdrawing the prohibitions
on the export of woollen goods and glass from Ireland. Commerce with
the British colonies was now also provisionally thrown open to Irish
merchants, and they were admitted to a share in the Levant trade.
At the same time the cause of religious toleration gained an
equally signal triumph. The strength of the Ulster Volunteers and the
abatement of religious bigotry brought the Irish Parliament to pass a
measure for relieving the Protestant Dissenters of that land from the
sacramental test which had been looked on as one of the bulwarks of
the Established Church; and in the spring of 1780 the British
Parliament gave its grudging assent to that boon for Ireland which for
nearly half a century longer it persisted in withholding from
Nonconformists in England and Wales. As was stated in Chapter V of
this work, the Irish Volunteers in the year 1782 gained another most
important concession, namely, the recognition of the legislative
independence of the Irish Parliament. Fortunately the British
Government on this occasion acted with grace and dignity. The
Rockingham Ministry advocated the change, which passed both
Houses with but a single adverse vote, that of Lord Loughborough.
The disagreeable fact, that this last boon, like the others, was extorted
by force, was thus tactfully glozed over; and when the suspicions of
the good faith of England aroused in Ireland by that restless
demagogue, Flood, were laid to rest by the Renunciation Act of the
year 1783, the relations of the two islands became almost cordial.
Causes of friction, however, remained. The royal veto might, and
probably would, still tell against the Irish Legislature, even though the
veto of the British Parliament and of the Privy Council had lapsed. The
influence of the Lord Lieutenant and of his Chief Secretary on the Irish
Ministers was also great; and his influence was distinctly British. Dublin
Castle could also generally determine the votes of a majority in both
Houses of Parliament. Further, it was quite possible that on
commercial questions the Irish Parliament would differ sharply from
that of Westminster. This seemed so in the early months of Pitt’s
Ministry. The beginning of the year 1784 found Ireland depressed by a
very inclement winter; and the cry was raised that her Parliament
should “protect” her industries, especially that of wool, from English
competition. The exertions of the new Lord Lieutenant, the Duke of
Rutland, aided perhaps by the reluctance of the more moderate
members to enter on a commercial war with England, sufficed to
defeat these proposals; but the Irish House of Commons, in May 1784,
unanimously passed an address to the King, emphasizing the need of
“a wise and well-digested plan for a liberal arrangement of a
commercial intercourse between Great Britain and Ireland.” This was
the friendly challenge which Pitt determined to take up. From the
outset he made the Irish commercial question peculiarly his own. More
than once in his correspondence with the Duke of Rutland he
326
describes it as the nearest to his heart.
No problem could have been more tangled. Ireland was still in a
very restless state. Despite the warnings of that uncrowned King of
Ireland, Grattan, the Volunteers began to enroll Catholics and to
threaten the coercion of the Dublin Parliament. But, as the Duke of
Rutland wrote to Pitt, Parliament “does not bear the smallest
resemblance to representation”; and a petition from a great meeting
held at Belfast in July 1784 declared that “the [Irish] House of
Commons has degenerated into a fixed body so little connected with
the people that it ceases to be a guardian of their property, and hath
become the representative of an overbearing aristocracy.” The
petitioners asserted that the delegates of the Volunteers were a
representative body, and urged the King to dissolve the Irish House of
327
Commons. This demand was widely echoed. The Volunteers,
having already through their delegates exerted on Parliament a
pressure which was semi-national, refused either to let politics alone,
or to disband. Ultimately their recklessness and the efforts of Grattan
undermined their influence, and they gradually dwindled away; but, for
the present, they seemed able to extort all their demands, prominent
among which was that for the “protection” of Irish industries and
products. In his first long communication to Pitt, the Duke of Rutland
dwelt on the urgent need of investigating Irish claims, though he
frankly declared that he could not understand the commercial question.
Open-handed to ostentation, and devoted to the pleasures of the table,
this affable young aristocrat occasionally showed signs of political
foresight, as when he ventured to predict “that without an union Ireland
328
will not be connected with Great Britain in twenty years longer.”
Far abler and more painstaking was his chief secretary, Orde, on
whom was to fall the burden of work connected with the proposed
Reform. The letters which passed between him and Pitt in the summer
of 1784 show the care taken by both of them to master the facts of the
situation. Orde (the future Lord Bolton) warned Pitt that a resolute
effort would soon be made to effect the entire separation of the two
Kingdoms, and urged him to “act towards Ireland with the utmost
liberality consistent with your own safety: it must in the long run be the
wisest policy.” Above all he insisted, as the duke had also done, on the
need of a firm decision, which even the malcontents must regard as
329
final.
Pitt on his side sought to procure the fullest information on all
points. In regard to the Reform of the Irish Parliament he deprecated
any extreme measure such as the admission of the Roman Catholics
then appeared to be; but he advocated the extension of political rights
to Protestant Dissenters; for, as he forcibly put it, “we may keep the
Parliament, but lose the people.” As for the fiscal question he required
first of all a satisfactory knowledge of the facts, so that some general
principles of action could be agreed on; and he urged that the financial
relations of the Kingdoms should be regulated according as the
prosperity of Ireland increased with her enlarged commercial
opportunities. Justice required that Ireland should then take her share
of the imperial burdens, which at present rested almost entirely with
Great Britain. Finally they must seek some means calculated to bestow
on Ireland that permanent tranquillity which the late commercial
330
concessions had failed to secure.
In this letter, dated 19th September 1784, we see not only an
outline of the scheme which took definite form in the Irish Propositions,
or Resolutions, of the session of 1785, but also an instructive example
of Pitt’s methods of procedure. He began by collecting all the
ascertainable facts, including the causes of previous failures, and, by
sifting these data, he sought to arrive at general principles which would
illuminate the whole question. In a word, his method was inductive. It
begun with facts and ended with principles. Unlike the French
legislators of 1789–93, who first enunciated principles and then sought
to square the facts of life to them, he started with a solid basis and
reared on it a structure from whose summit the toiler might take a wide
survey. The Revolutionists built symmetrically and grandly, but without
foundations.
In order thoroughly to master details, Pitt summoned from Ireland
not only Orde but also Foster, Chancellor of the Exchequer, and
Beresford, Chief Commissioner of the Revenue. Both were able and
masterful men, the former the doughtiest opponent, the latter the
staunchest champion, of Pitt’s Act of Union. Beresford did much to
beautify Dublin, and his name lives on in Beresford Place. With these
experienced officials Pitt had many conferences at Downing Street, or
at the house on the north side of Putney Heath, which he rented for the
latter part of 1784. They confirmed Orde’s advice as to the wisdom of
granting to Ireland complete liberty and equality in matters of trade, but
warned him as to the difficulty of drawing from Ireland any contribution
to the imperial funds. Here it should be remembered that Ireland
supported 15,000 regular troops, 3,000 of whom were at the disposal
of the British Executive in Ireland, while the others could be moved
from Ireland with the consent of her Parliament.
Converse with Foster must also have strengthened Pitt’s resolve to
press on the Reform of the Irish Parliament; for he now warned the
Duke of Rutland, who stoutly opposed Reform, not to confuse
peaceable efforts in that direction with subversive or treasonable
schemes; and in a notable phrase of his letter of 4th December, he
declared that Parliamentary Reform must sooner or later be carried in
both countries. As regards procedure, he thought it best to postpone a
change in the Irish franchise until a similar measure came forward at
Westminster; for this, if successful, would impart to the movement in
Ireland an irresistible force. In the meantime it would be well to take up
the commercial problem.
Pitt’s sanguine temperament here led him into a tactical mistake.
The Irish Resolutions were destined to arouse in Great Britain a storm
of opposition which swept away the hopes of the Reform Associations;
and the collapse of their efforts told unfavourably on the Irish political
movement. Probably also he erred in bringing forward his proposals
first in Dublin—a matter on which Fox readily aroused resentment at
Westminster. Yet, where the issues were so tangled, it is difficult to say
whether success could have crowned Pitt’s efforts had they been put
331
forth in a different order. From his letter of 7th October 1784 to the
Lord Lieutenant we see that he looked on the Reform of the Irish
Parliament as simpler, but yet “perhaps more difficult and hazardous,”
than the commercial questions then at stake.
Here again he calculated wrongly. Ireland’s demand for equality of
trading advantages with Great Britain was certain to meet with
vehement opposition from our manufacturers, as the events of the year
1778 convincingly showed. His mistake is the more remarkable as he
proposed “to give Ireland an almost unlimited communication of
commercial advantage, if we can receive in return some security that
her strength and riches will be our benefit, and that she will contribute
from time to time in their increasing proportions to the common
332
exigencies of the Empire.” How buoyant was Pitt’s nature to cherish
the hope that British merchants would concede commercial equality to
Ireland, or that the factions at Dublin would take up the burdens of
Empire!
No letter of Pitt’s rings with more enthusiasm, though an undertone
of anxiety can be detected, than the very long one of 6th-7th January
1785. Writing until far past midnight he explained to the Lord-
Lieutenant in great detail the aim which he had in view, namely, the
sweeping aside of all local prejudices, so that England and Ireland
might become “one country in effect, though for local concerns under
distinct Legislatures.” The pupil of Adam Smith had caught a clear
glimpse of the truth that States which throw down their customs’
barriers become effectually parts of the same body. But he now saw
that British manufacturers would probably resist so sweeping a
change; and he pointed out to Rutland that the admission of Ireland to
commercial equality, even in the case of the export trade from British
Colonies, to which, he said, she had no claim of right, involved a
solemn duty to respond to imperial duties. He then pointed out that
Ireland would have more than mere equality; for Great Britain was
burdened by taxes which were the outcome of those duties; and Irish
shippers, with their lighter burdens, might find it possible to export the
produce of those colonies to Great Britain to the detriment of British
shippers. In many ways he sought to disprove the claims or excuses
put forward by Irish patriots why they should receive much and give
little in return. He showed the impossibility of conceding so much
unless Ireland would irrevocably pledge herself to contribute,
333
according to her ability, to the expenses of the Empire.
The despatches sent by the Home Secretary, Lord Sydney, to the
Lord Lieutenant, and the letters of Pitt to Orde, contained precise
instructions on this last point. Pitt first desired that Ireland’s
334
contribution should go towards the navy. Then for a time he
harboured the notion that it should go towards his proposed Sinking
Fund, because that money would not pass beyond England, and would
return in the form of a trade the balance of which was known to be in
335
favour of Ireland. But the Cabinet adopted the earlier proposal, with
the proviso that the contribution towards the naval expenses of the
Empire should be made in such a way as the Irish Parliament might
direct. The letter of George III to Pitt, of 28th January 1785, shows that
the King insisted on a contribution from Ireland as essential.
The ten Propositions, or Resolutions, embodying the aims of Pitt,
were brought before the Irish Parliament on 7th February 1785. They
embodied the information gleaned from Beresford, Foster, and Orde;
and a report recently drawn up by a special committee of the British
Privy Council also furnished useful information. Modified in some
particulars, and, with the addition of a Proposition soon to be noticed,
they passed the Dublin Parliament with little difficulty. In their modified
form they may be summarized as follows. Foreign and colonial
products were to pass between Great Britain and Ireland, in either
direction, without any increase of duty. The goods and products of the
sister islands were also to be imported either free or at identical rates;
or again, where the duties were not equal, they were to be reduced to
the lower of the two tariffs hitherto in operation. All prohibitions on
inter-insular trade were to lapse without renewal, unless it should seem
expedient in the case of corn, meal, malt, flour, and biscuits. The
British Government required that, when the “hereditary revenue”
exceeded a certain sum, Ireland should pay over the surplus as a
contribution to the naval expenses of the Empire. As the “hereditary
revenue” consisted mainly of custom and excise duties, its increase
(which was generally steady) afforded the best index of the prosperity
of Ireland. Moreover that branch of the revenue had hitherto been
under the general direction of the Crown; and Pitt’s proposal to transfer
its surplus to the control of the Irish Parliament was both statesmanlike
336
and conciliatory.
Nevertheless, the letters of the Duke of Rutland to Pitt revealed the
conviction even of the best friends of Government that the Propositions
would fail if they were coupled with any demand for a money payment.
The time, said the Duke, was very critical. They were seeking to
organize a legal militia force in place of the self-constituted Volunteers;
Grattan and Daly had spoken splendidly for the change; but the
demand for a subsidy would jeopardize everything, even the
337
connection with Great Britain. A secret report which he sent to Pitt
showed that of the members of the large towns of Ireland, only
Londonderry was well disposed to the Resolutions. In the case of
Waterford (“well governed, under Lord Tyrone’s influence”) the
freemen opposed them while the two members supported them.
Belfast, a close borough, opposed them. In all, he reckoned forty-five
members hostile, twelve friendly, and the others absent or not
accounted for. A list followed of the “expectations” of members as
338
regards judgeships, pensions and sinecures.
As Rutland and Orde had foreseen, the assailants of the measure
fastened on the question of the contribution. How could a country,
whose annual expenditure at present exceeded income by £150,000,
and whose absentee landlords drained her of a million a year, pay a
large sum to the richer island? Did not Ireland contribute largely in men
and money to the army? And was not a great part of her administration
controlled by a Monarch and a Ministry in whose succession and
appointment she had no voice? Such were the invectives of that most
acrid and restless of demagogues, Flood. Far more statesmanlike was
the conduct of Grattan. Equalling, nay excelling, Flood in his oratorical
powers, he held them under the control of a masculine reason. As his
energy and tact had gained for his land the boon of legislative
independence, so now he sought to cement friendly relations with
Great Britain, and therefore gave a general assent to the commercial
proposals. The Irish Ministers also pointed out that Great Britain
opened a far larger market than Ireland did; that the industries of the
larger island, being handicapped by war taxes and high wages, could
be exploited by Irishmen, whose national burdens were comparatively
light, and that the colonial trade was now to be opened up in its
entirety and for ever, not on terms that were revocable at the option of
the British Government, as was the case in 1780.
All these arguments were of no avail to carry the proposal
respecting Ireland’s contribution to the navy. Though Pitt had carefully
framed it so that Ireland would pay nothing until she was in a
prosperous state, he failed to meet the rooted objections of the Dublin
Parliament to money going out of the country. Grattan focused the
opposition by demanding that Ireland should pay nothing until her
Government had put an end to the long series of deficits. In private
conversations with him Orde failed to weaken this decision, in which
nearly all Irishmen concurred. A Resolution to that effect was therefore
added. It was further arranged that when the annual hereditary
revenue, which then stood at £652,000, should exceed £656,000 in
time of peace, the surplus should go towards the support of the
imperial navy in such a way as the Irish Parliament should direct.
Additional taxes were then voted which were estimated to yield
£140,000 a year.
No beginning could have been less auspicious. The arrangement
was far less satisfactory than the worst of the alternative plans to
which Pitt expressed the hope that Orde would never resort. The
contribution, on the present terms, could be evaded by any juggling
Chancellor of the Exchequer who should contrive a series of small and
profitable deficits. Consequently Orde, who came to London to
persuade Pitt of the need of the change, found him inexorable. Pitt was
resolved “not to proceed until the condition should be taken away from
339
the last Resolution.” This also appears in a part of his letter to the
Marquis of Buckingham:

[Secret.]
340
Sunday, February 20, 1785.
... I am able to tell you confidentially that we shall certainly
suspend the final approbation of the commercial system, and
declare the impossibility of completing it till more satisfaction and
explicit provision is made in Ireland respecting the object of
contribution.
Yours ever,
W. Pitt.

In opening his case at Westminster on 22nd February, Pitt had to


contend with the discouragement caused by this rebuff, and with a fit
of hoarseness, which he informed Grenville he had been trying to
sleep off without much success. Nevertheless his speech was allowed
to be a fine effort. He besought members fairly to consider his
proposals, which aimed at settling the relations of the two islands on a
liberal and permanent basis. Glancing scornfully at the tactics of the
Opposition and the campaign of malice and misrepresentation started
by the “Gazetteer” and taken up by various trading bodies, he claimed
that there should be fair play, at least until he had stated his case fully.
It was complex, and his proposals might need modification in details.
The old system of cruel and abominable restraint imposed on Irish
trade had vanished. They now had to complete a new system, and
community of benefits was the only principle on which they could
proceed. They proposed entirely and for ever to open to Ireland the
trade of our colonies except that of India, which was a monopoly of the
East India Company. There was no solid ground for the fear that so
poor a country as Ireland would become the emporium of colonial
goods, and would re-export them to our shores. Equally unlikely was
the suggestion that Ireland would undersell us in manufactures; for
British energy had secured for our goods a fairly large market in
Ireland even against her import duties. He then referred guardedly to
the subject of Ireland’s contribution to the imperial navy. Finally, while
deprecating any immediate decision, he declared that what England
lost by the bargain she would more than recoup from the growing
friendliness and prosperity of the sister island. He therefore proposed a
general motion for the permanent and irrevocable admission of Ireland
to all the advantages of British commerce when she irrevocably
341
pledged herself to pay a sum towards the defence of commerce.
The Opposition, exasperated by Pitt’s ungenerous treatment of
Fox concerning the Westminster election, at once opened a furious fire
of criticisms. Fox, who held the old Whig views in favour of a “national
commerce,” that is, protection, urged that Ireland would probably
smuggle into Great Britain the produce of foreign colonies, and would
become the “grand arbitress of all the commercial interests of the
Empire.” The Resolutions ought, he claimed, first to have been moved
at Westminster, in which he was probably right. If they were passed,
he said, Great Britain would never have anything more to concede to
Ireland. The Navigation Acts, the source of England’s prosperity, would
be a dead letter. As for Ireland’s contribution to the navy, he would
“trust everything to her generosity, but not much to her prudence.”
Eden, formerly Irish Secretary, then dwelt on the danger of allowing a
lightly taxed country to compete with a heavily burdened country. The
debt of Great Britain was a hundredfold that of Ireland; and, while a
Briton paid on an average fifty shillings a year in taxes, an Irishman
paid only eight shillings. The plan now proposed would be a revolution
in British trade. These words are remarkable in view of Eden’s
desertion of North and his assistance to Pitt in carrying through a still
greater “revolution,” the commercial treaty with France of 1786. The
speeches of Fox and Eden did some good; their attack on Pitt’s
measure convinced Irishmen that it must have many excellences. The
Earl of Mornington (afterwards the Marquis Wellesley) declared that
Ireland would warmly support Pitt. Beresford also stated that the Irish
members now only wanted an excuse for siding with him; but England
must beware of pressing Ireland too hard in this bargain. A rebuff
342
would seriously jeopardize the cause of order.
No sense of prudence or responsibility restrained the action of the
British Opposition and their mercantile allies. A campaign had already
begun. It bore signs of careful organization. The signal was given by
the “Gazetteer” of 16th February, which pointed out that the Navigation
Acts, the source of Britain’s prosperity, would be virtually annulled by
Pitt’s proposals. On the next day it showed that Irish competition,
based on low wages, must ruin our industries. On 18th February a
meeting of silk manufacturers protested against the Resolutions. On
the 24th the planters and merchants of the West Indies followed suit.
On that day the “Gazetteer” stated that, if Pitt’s measure became law,
the Exchange would be transferred from Cornhill to Cork; later on it
declared that Arkwright and Dempster would set up their factories in
Ireland. On 3rd March the “Morning Chronicle,” the organ of the middle
classes, joined in the hue and cry, declaring that even as it was the
balance of trade between Great Britain and Ireland was in favour of the
latter, and that the larger island must be drained of money by the
smaller if the old restrictions were not maintained.
Meetings of protest were now in full swing. Delegates of the West
India merchants had an interview with Pitt and declared his answer to
be unsatisfactory. The merchants themselves refused, by fifty-nine to
forty, to petition against his proposals, but the minority published and
circulated their opinions. The manufacturing towns, except those of the
woollen districts, petitioned strongly against the Resolutions.
Manchester, Lancaster, and Dudley each sent two petitions to that
effect; while three apiece emanated from Glasgow, Paisley, and Bristol.
So the game of misrepresentation went on. A petition from Lancashire
contained 80,000 signatures; and a document purporting to come from
13,243 weavers of Glasgow and Rutherglen, shows that artisans were
as much alarmed as the merchants. The weavers stated their
conviction that if the Resolutions became law, they would be undersold
343
by the Irish in the home market and reduced to beggary. This
solidarity of interest is noteworthy. In those days the “manufacturer”
was actually, as well as in name, the weaver; and tens of thousands of
households, where the hand-loom kept the wolf from the door through
the winter, saw pale Ruin stalking behind the figure of thrifty,
resourceful, energetic Paddy. The agitation therefore spread through
all classes with a unanimity that would scarcely be possible now, when
the term “manufacturer” has come to mean a capitalist who owns a
factory where nothing is done by hand. Then the solidarity of interest
between merchants and weavers was obvious. In imagination both
classes saw their industries wafted by a cruel east wind to a land
whose inhabitants they disliked and despised.
Some of the petitions were based on false information. That of the
Glasgow cotton workers complained that the fourth Resolution, as it
left the Irish Parliament, would place a heavy duty on British
344
cottons. But Pitt had throughout insisted that there must be an
equalizing of duties on both sides of the Irish Sea, the lower level
being always taken. In truth, all reasoning was in vain. The
protectionist spirit was proof against all arguments. Thus, the
committee of the merchants and manufacturers of Sheffield declared
that their industry could not be carried on without grave injury if the
present duty on bar iron imported into Great Britain, namely, 56
shillings per ton, were reduced to the level then obtaining in Ireland,
that is, 10 shillings a ton.
Still keener was the opposition in Bristol. The protectionist feeling
had lost none of the bitterness which mainly caused the unseating of
Burke in the election of 1774. The sugar refiners of that town now
declared that they had spent more than £150,000 in buildings and
plant, all of which would go for naught, if the Irish Parliament, “under
the privilege of importing raw and refined sugars through that country
to this [should] lay a heavy duty on loaf and lump sugar and a small
duty on bastard and ground sugars and molasses”; for the Irish
merchants would then “effectually prevent our exporting the former to
that kingdom and also to foreign markets, and enable them to send the
latter into Great Britain at a less price than it can be manufactured here
under the burthen of the high duties, the high price of labour, and
heavy taxes, which would inevitably tend to the ruin of that valuable
345
branch of trade in this kingdom.” The Bristol sugar-refiners can
scarcely have read Pitt’s proposals, which implied equal duties on all
articles at British and Irish ports; and the Irish Parliament had agreed
to this. The notion that Irish sugar-refiners, by complex duties of their
own devising, would soon beat their British rivals out of foreign
markets and ruin them in the home market, is a sign of the mad folly of
the time. Against stupidity such as this even the gods fight in vain.
By no arguments could the hubbub be appeased. Pamphlets,
especially one by Lord Sheffield, denounced the doom awaiting
England should Pitt’s Resolutions pass. In a short time sixty-four
346
petitions poured in against them; and the manufacturers of Great
Britain, under the chairmanship of Wedgwood, formed a “Great
Chamber” in order to stave off the catastrophe. Yet Pitt’s energies and
spirits seemed to rise with the rising opposition. In order to emphasize
the importance of commerce, he had recently appointed a Committee
of Council for Commerce, which promised to answer the purposes
which that ornamental body, the Board of Trade (abolished in 1782),
had signally failed to fulfil. The new Council was charged to examine
manufacturers and others as to the relations of Anglo-Irish commerce
and the probable effect of the Resolutions. Similar investigations were
made at the bar of the House of Commons. Pitt cherished high hopes
from these inquiries. “The more the subject is discussed,” he wrote to
Orde on 4th April, “the more our cause will be benefited in the end.... I
do not myself entertain a doubt of complete success.” To the Duke of
Rutland he wrote on the 16th: “Though we may lose a little in
popularity for the time, we shall ultimately gain—at least the country
347
will, which is enough.”
The report of the committee is very curious, as showing the
difficulty of obtaining trustworthy statistics even on the weightiest
topics. The Irish accounts showed a far larger export of goods to Great
Britain than of imports from Great Britain; while, on the contrary, the
British Custom House returns gave the balance of trade as largely
against Ireland. The committee could discover no means of accounting
348
for this extraordinary discrepancy. Thus, while protectionists on
both sides of the Irish Sea were croaking over the decline of their trade
and the growth of that of their rival, the official returns showed that (as
they would have phrased it) the balance of trade was so largely in their
favour as to warrant the hope of the speedy exhaustion of that rival.
In matters which were within the ken of the financiers of that age,
the report was reassuring. The woollen manufacturers of Norwich
declared that, though the wages of Irish spinners were less by one-half
than those of English spinners, Irish competition was not to be feared
under the conditions now proposed. Everett, a London merchant,
maintained that the British manufacturers, owing to their skill, taste,
and ingenuity, would always have a superiority over those of Ireland,

You might also like