100% found this document useful (1 vote)
522 views

Pro C# 7 with .NET and .NET Core Andrew Troelsen All Chapters Instant Download

Troelsen

Uploaded by

ketjonadloy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
522 views

Pro C# 7 with .NET and .NET Core Andrew Troelsen All Chapters Instant Download

Troelsen

Uploaded by

ketjonadloy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

Experience Seamless Full Ebook Downloads for Every Genre 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/

OR CLICK BUTTON

DOWNLOAD NOW

Explore and download more ebook 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/

textboxfull.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/
textboxfull.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/
textboxfull.com

Building Microservices with NET Core 2 0 Transitioning


Monolithic Architectures Using Microservices with NET Core
2 0 Using C 7 0 Gaurav Aroraa
https://textbookfull.com/product/building-microservices-with-net-
core-2-0-transitioning-monolithic-architectures-using-microservices-
with-net-core-2-0-using-c-7-0-gaurav-aroraa/
textboxfull.com
C 8 0 and NET Core 3 0 Modern Cross Platform Development
Build applications with C NET Core Entity Framework Core
ASP NET Core and ML NET using Visual Studio Code 4th
Edition Mark J. Price
https://textbookfull.com/product/c-8-0-and-net-core-3-0-modern-cross-
platform-development-build-applications-with-c-net-core-entity-
framework-core-asp-net-core-and-ml-net-using-visual-studio-code-4th-
edition-mark-j-price/
textboxfull.com

Modern Data Access with Entity Framework Core: Database


Programming Techniques for .NET, .NET Core, UWP, and
Xamarin with C# 1st Edition Holger Schwichtenberg
https://textbookfull.com/product/modern-data-access-with-entity-
framework-core-database-programming-techniques-for-net-net-core-uwp-
and-xamarin-with-c-1st-edition-holger-schwichtenberg/
textboxfull.com

Modern Data Access with Entity Framework Core: Database


Programming Techniques for . NET, . NET Core, UWP, and
Xamarin with C# 1st Edition Holger Schwichtenberg
https://textbookfull.com/product/modern-data-access-with-entity-
framework-core-database-programming-techniques-for-net-net-core-uwp-
and-xamarin-with-c-1st-edition-holger-schwichtenberg-2/
textboxfull.com

Pro ASP NET Core Identity Under the Hood with


Authentication and Authorization in ASP NET Core 5 and 6
Applications 1st Edition Adam Freeman
https://textbookfull.com/product/pro-asp-net-core-identity-under-the-
hood-with-authentication-and-authorization-in-asp-net-
core-5-and-6-applications-1st-edition-adam-freeman/
textboxfull.com

C 7 and NET Core Modern Cross Platform Development 2nd


Edition Mark J. Price

https://textbookfull.com/product/c-7-and-net-core-modern-cross-
platform-development-2nd-edition-mark-j-price/

textboxfull.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
orders-ny@springer-sbm.com, 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 rights@apress.com, 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
■ 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
■ 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
■ Contents

Building a .NET Assembly with CIL������������������������������������������������������������������������������� 684


Building CILCars.dll���������������������������������������������������������������������������������������������������������������������������� 684
Building CILCarClient.exe������������������������������������������������������������������������������������������������������������������� 687

Understanding Dynamic Assemblies���������������������������������������������������������������������������� 688


Exploring the System.Reflection.Emit Namespace����������������������������������������������������������������������������� 689
The Role of the System.Reflection.Emit.ILGenerator�������������������������������������������������������������������������� 690
Emitting a Dynamic Assembly������������������������������������������������������������������������������������������������������������ 691
Emitting the Assembly and Module Set���������������������������������������������������������������������������������������������� 693
The Role of the ModuleBuilder Type��������������������������������������������������������������������������������������������������� 694
Emitting the HelloClass Type and the String Member Variable����������������������������������������������������������� 695
Emitting the Constructors������������������������������������������������������������������������������������������������������������������� 696
Emitting the SayHello() Method���������������������������������������������������������������������������������������������������������� 697
Using the Dynamically Generated Assembly�������������������������������������������������������������������������������������� 697

Summary���������������������������������������������������������������������������������������������������������������������� 698


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

■Chapter 19: Multithreaded, Parallel, and Async Programming������������������������� 701
The Process/AppDomain/Context/Thread Relationship������������������������������������������������ 701
The Problem of Concurrency�������������������������������������������������������������������������������������������������������������� 702
The Role of Thread Synchronization��������������������������������������������������������������������������������������������������� 703

A Brief Review of the .NET Delegate���������������������������������������������������������������������������� 703


The Asynchronous Nature of Delegates����������������������������������������������������������������������� 705
The BeginInvoke() and EndInvoke() Methods�������������������������������������������������������������������������������������� 706
The System.IAsyncResult Interface���������������������������������������������������������������������������������������������������� 706

Invoking a Method Asynchronously������������������������������������������������������������������������������ 707


Synchronizing the Calling Thread������������������������������������������������������������������������������������������������������� 708
The Role of the AsyncCallback Delegate�������������������������������������������������������������������������������������������� 709
The Role of the AsyncResult Class����������������������������������������������������������������������������������������������������� 711
Passing and Receiving Custom State Data����������������������������������������������������������������������������������������� 712

The System.Threading Namespace������������������������������������������������������������������������������ 713

xxviii
■ Contents

The System.Threading.Thread Class���������������������������������������������������������������������������� 714


Obtaining Statistics About the Current Thread of Execution��������������������������������������������������������������� 715
The Name Property����������������������������������������������������������������������������������������������������������������������������� 716
The Priority Property��������������������������������������������������������������������������������������������������������������������������� 717

Manually Creating Secondary Threads������������������������������������������������������������������������� 718


Working with the ThreadStart Delegate���������������������������������������������������������������������������������������������� 718
Working with the ParameterizedThreadStart Delegate���������������������������������������������������������������������� 720
The AutoResetEvent Class������������������������������������������������������������������������������������������������������������������ 721
Foreground Threads and Background Threads����������������������������������������������������������������������������������� 722

The Issue of Concurrency��������������������������������������������������������������������������������������������� 723


Synchronization Using the C# lock Keyword�������������������������������������������������������������������������������������� 726
Synchronization Using the System.Threading.Monitor Type��������������������������������������������������������������� 728
Synchronization Using the System.Threading.Interlocked Type��������������������������������������������������������� 729
Synchronization Using the [Synchronization] Attribute���������������������������������������������������������������������� 730

Programming with Timer Callbacks����������������������������������������������������������������������������� 730


Using a Stand-Alone Discard�������������������������������������������������������������������������������������������������������������� 732

Understanding the CLR ThreadPool������������������������������������������������������������������������������ 732


Parallel Programming Using the Task Parallel Library������������������������������������������������� 734
The System.Threading.Tasks Namespace������������������������������������������������������������������������������������������ 735
The Role of the Parallel Class������������������������������������������������������������������������������������������������������������� 735
Data Parallelism with the Parallel Class��������������������������������������������������������������������������������������������� 736
Accessing UI Elements on Secondary Threads����������������������������������������������������������������������������������� 739
The Task Class������������������������������������������������������������������������������������������������������������������������������������ 740
Handling Cancellation Request����������������������������������������������������������������������������������������������������������� 740
Task Parallelism Using the Parallel Class������������������������������������������������������������������������������������������� 742

Parallel LINQ Queries (PLINQ)��������������������������������������������������������������������������������������� 745


Opting in to a PLINQ Query����������������������������������������������������������������������������������������������������������������� 746
Cancelling a PLINQ Query������������������������������������������������������������������������������������������������������������������� 746

Asynchronous Calls with the async Keyword��������������������������������������������������������������� 748


A First Look at the C# async and await Keywords������������������������������������������������������������������������������ 748
Naming Conventions for Asynchronous Methods������������������������������������������������������������������������������� 750

xxix
■ Contents

Async Methods Returning Void����������������������������������������������������������������������������������������������������������� 750


Async Methods with Multiple Awaits�������������������������������������������������������������������������������������������������� 751
Calling Async Methods from Non-async Methods������������������������������������������������������������������������������ 751
Await in catch and finally Blocks�������������������������������������������������������������������������������������������������������� 752
Generalized Async Return Types (New)���������������������������������������������������������������������������������������������� 752
Local Functions (New)������������������������������������������������������������������������������������������������������������������������ 753
Wrapping Up async and await������������������������������������������������������������������������������������������������������������ 754

Summary���������������������������������������������������������������������������������������������������������������������� 754

■Chapter 20: File I/O and Object Serialization���������������������������������������������������� 755
Exploring the System.IO Namespace��������������������������������������������������������������������������� 755
The Directory(Info) and File(Info) Types������������������������������������������������������������������������ 756
The Abstract FileSystemInfo Base Class�������������������������������������������������������������������������������������������� 757

Working with the DirectoryInfo Type���������������������������������������������������������������������������� 758


Enumerating Files with the DirectoryInfo Type����������������������������������������������������������������������������������� 759
Creating Subdirectories with the DirectoryInfo Type�������������������������������������������������������������������������� 760

Working with the Directory Type���������������������������������������������������������������������������������� 761


Working with the DriveInfo Class Type������������������������������������������������������������������������� 762
Working with the FileInfo Class������������������������������������������������������������������������������������ 763
The FileInfo.Create() Method�������������������������������������������������������������������������������������������������������������� 764
The FileInfo.Open() Method����������������������������������������������������������������������������������������������������������������� 765
The FileInfo.OpenRead() and FileInfo.OpenWrite() Methods��������������������������������������������������������������� 766
The FileInfo.OpenText() Method���������������������������������������������������������������������������������������������������������� 767
The FileInfo.CreateText() and FileInfo.AppendText() Methods������������������������������������������������������������� 767

Working with the File Type������������������������������������������������������������������������������������������� 767


Additional File-Centric Members�������������������������������������������������������������������������������������������������������� 768

The Abstract Stream Class������������������������������������������������������������������������������������������� 770


Working with FileStreams������������������������������������������������������������������������������������������������������������������ 771

Working with StreamWriters and StreamReaders������������������������������������������������������� 772


Writing to a Text File��������������������������������������������������������������������������������������������������������������������������� 773
Reading from a Text File��������������������������������������������������������������������������������������������������������������������� 774
Directly Creating StreamWriter/StreamReader Types������������������������������������������������������������������������� 775
xxx
■ Contents

Working with StringWriters and StringReaders����������������������������������������������������������� 775


Working with BinaryWriters and BinaryReaders���������������������������������������������������������� 777
Watching Files Programmatically��������������������������������������������������������������������������������� 779
Understanding Object Serialization������������������������������������������������������������������������������ 781
The Role of Object Graphs������������������������������������������������������������������������������������������������������������������ 782

Configuring Objects for Serialization���������������������������������������������������������������������������� 784


Defining Serializable Types����������������������������������������������������������������������������������������������������������������� 784
Public Fields, Private Fields, and Public Properties���������������������������������������������������������������������������� 785

Choosing a Serialization Formatter������������������������������������������������������������������������������ 785


The IFormatter and IRemotingFormatter Interfaces��������������������������������������������������������������������������� 786
Type Fidelity Among the Formatters��������������������������������������������������������������������������������������������������� 787

Serializing Objects Using the BinaryFormatter������������������������������������������������������������ 788


Deserializing Objects Using the BinaryFormatter������������������������������������������������������������������������������� 790

Serializing Objects Using the SoapFormatter��������������������������������������������������������������� 790


Serializing Objects Using the XmlSerializer����������������������������������������������������������������� 791
Controlling the Generated XML Data�������������������������������������������������������������������������������������������������� 792

Serializing Collections of Objects��������������������������������������������������������������������������������� 794


Customizing the Soap/Binary Serialization Process����������������������������������������������������� 795
A Deeper Look at Object Serialization������������������������������������������������������������������������������������������������ 796
Customizing Serialization Using ISerializable������������������������������������������������������������������������������������� 797
Customizing Serialization Using Attributes����������������������������������������������������������������������������������������� 800

Summary���������������������������������������������������������������������������������������������������������������������� 801

■Chapter 21: Data Access with ADO.NET������������������������������������������������������������� 803
A High-Level Definition of ADO.NET������������������������������������������������������������������������������ 803
The Three Faces of ADO.NET�������������������������������������������������������������������������������������������������������������� 804

Understanding ADO.NET Data Providers����������������������������������������������������������������������� 805


The Microsoft-Supplied ADO.NET Data Providers������������������������������������������������������������������������������� 806
Obtaining Third-Party ADO.NET Data Providers���������������������������������������������������������������������������������� 807

Additional ADO.NET Namespaces��������������������������������������������������������������������������������� 808

xxxi
Exploring the Variety of Random
Documents with Different Content
House, to stand at the Table before the famous despatch box, to
lean elbow on it, and even to thump it, as an added emphasis in the
very passion of argument, as was done by all the renowned
parliamentarians of the past. It is true that keen and fierce is the
competition for the higher offices in the Administration. The House
of Commons, with all its constitutional supremacy as an institution,
is composed of human beings. That being so, it is not free from the
unamiable characteristics of intrigue and envy; and the qualities of
resolute will and tenacity of purpose are, indeed, necessary in the
ambitious young Member if he is to escape from being pushed aside
or being trampled upon in the race for office. Once on the Treasury
Bench, however, he has won half the battle for a post in the very
hierarchy of the Government—the exclusive ring of Cabinet
Ministers.
Yet the number of men in the House of Commons without social
or political ambition is remarkably large; men, too, who are
absolutely unknown outside their constituencies. They are in
Parliament literally for their health. During the day they are engaged
in the direction of great industrial and commercial undertakings, and
in the evening they go down to Westminster for that rest and
recuperation which comes with change of scene and occupation.
They find the duties of an M.P. very agreeable, on the whole. The
responsibilities of the position sit lightly upon them. They find a joy
in all the details of parliamentary life.
Many old men, who have spent themselves in trade or finance,
take to politics in the evening of their days as a mild relaxation or
hobby, and a means of prolonging life. There was once a great
merchant who, when he left for ever his desk in the city, after an
association of half a century, found the separation a terrible strain,
and seemed likely to pine and mope his way quickly to the grave.
His medical adviser recommended him to find a seat in the House of
Commons as a distraction to relieve the monotony of his existence.
But the old man did not like the suggestion. He knew nothing of
public questions. The financial intelligence was the only portion of
his morning paper which he had carefully studied for fifty years. “If
you do not go into the House of Commons, you will have to go to
Paradise,” said the doctor; “it is the only alternative.” “Then I will
choose the House of Commons,” said the old City man, with a sigh
of resignation. And how glad he was when he became a Member! At
last, something of the joy of life had really come to him.
To sit silently on the green benches during a debate, save when
they cheer a supporter, or roar at an opponent, and to walk through
the division lobbies, voting as directed by the Whips, amply satisfy
the desire of not a few Members for political thought and labour. It is
an existence that excites and soothes by turns. Disraeli once said to
a friend who had just entered the House of Commons: “You have
chosen the only career in which a man is never old. A statesman can
feel and inspire interest longer than any other man.” A seat in the
House does not, of course, make one a statesman. But, as a general
proposition, there is much force in Disraeli’s saying. Old men find the
fountain of youth in the halls of Westminster. It is all nonsense what
one sometimes reads about the weary and trying round of
parliamentary life. There are men in the House of Commons who,
after twenty, thirty, forty years of service, show no symptoms of
physical exhaustion, and who will tell you that Parliament is the most
interesting and most entertaining place in the world. John Morley
once spoke of the daily round of an M.P. as “business without work
and idleness without rest.” During the years he was engaged in
writing his Life of Gladstone he took no active part in the
controversies of the House of Commons. But he could not keep
entirely away from the place. How often had I seen that fine
philosophical writer at this particular period of his career sitting on
the front Opposition Bench, at the gangway corner, his arms folded,
his legs crossed, listening, like an ordinary mortal, for hours to
Members venturing to say this, not hesitating to say that, going one
step further, adding another word, on subjects that must have had
no interest for him. The spell of the House of Commons was upon
him. He could not keep away. He had to come down, even as a
distraction, just to see if anything was going on. Nothing was going
on, but he remained for hours.
3
Parliamentary life has a fascination which few men, having once
breathed its intoxicating atmosphere, can successfully withstand. Its
call is irresistible. Cobden thus wrote from a retreat in Wales, in July,
1846, after the object of his parliamentary career, the repeal of the
Corn Laws, had been achieved:

I am going into the wilderness to pray for a return of the taste I once
possessed for nature, and simple, quiet life. Here I am, one day from
Manchester, in the loveliest valley out of Paradise. Ten years ago, before
I was an agitator, I spent a day or two in this house. Comparing my
sensations now with those I then experienced, I feel how much I have
lost in winning public fame. The rough tempest has spoiled for me a
quiet haven. I feel I shall never be able to cast anchor again. It seems
as if some mesmeric hand were on my brain, or that I was possessed by
an unquiet fiend urging me forward in spite of myself.

However disappointed a Member may be in failing to realize his


dreams of political ambition and social success, there remains for
him the consoling thought—indeed, the great reward—that he has
the honour of serving the State, of helping in the management of
national affairs, of guiding the destinies of a mighty Commonwealth.
No wonder that most Members quit this exalted and historic scene
reluctantly, with the deepest regret—aye, with breaking hearts.
Should so great a misfortune befall them of being rejected from
further service by their constituents at the General Election, they
long to return again to the green benches. Complacently to settle
down to the humdrum of private life is for many of them impossible.
Even the old and worn agitators who have voluntarily resigned
pine to be in the thick of the shoutings of the rival Parties, and the
trampings through the division lobbies. There was William
Wilberforce, the emancipator of the slaves. Sir Samuel Romilly, who
sat in the House of Commons in 1807, when slavery within the
British Empire was finally abolished, said of Wilberforce: “He can lay
his head upon his pillow and remember that the slave trade was no
more.” But was Wilberforce content to be out of Parliament even in
his extreme old age? Hannah Macaulay relates that in 1830, while
staying at Highwood Hill, the guest of Wilberforce, she got a letter
from her brother, enclosing an offer to him from Lord Lansdowne of
the seat for the pocket borough of Calne. She showed the
communication to Wilberforce. “He was silent for a moment,” she
writes, “and then his mobile face lighted up, and he slapped his
hand to his ear and cried: ‘Ah! I hear that shout again! Hear, hear!
What a life it was!’”
CHAPTER VII

PALACE OF WESTMINSTER

1
The Palace of Westminster, in which Lords and Commons meet—the
largest and most imposing Gothic building in the world—may be
regarded, rising so nobly on the left bank of the Thames, as an
expression in architecture of the dignity and stability of Parliament,
and the honour in which it is held by the Nation. Most visitors to the
Palace reach it by Whitehall or Victoria Street. On that side are the
entrances to both Houses. It is more picturesque, but less imposing,
than the river front. The inclusion of Westminster Hall—the only
overground portion of the old Palace saved from the fire of 1834—
enforced the breaking up of the western or land front of the new
Palace into a variety of façades. The light and shade produced by
the massive grey masonry of the ancient Hall, mingling with the
Gothic gracefulness of the new Palace, is very beautiful, and also
pregnant with historic meaning. It reminds one of the survival of
tradition in the forms and ceremonies of Parliament. The effect of
this blending of the past and present is heightened by the close
contiguity of the venerable Abbey, and the open grassy space,
known as Parliament Square, with its effigies of great Victorian
statesmen—Sir Robert Peel, Lord Palmerston, the Earl of Derby, and
Lord Beaconsfield—which front the forecourt of the Palace; and the
striking figure of Oliver Cromwell, with sword and Bible, on the
sunken grass plot by the side of Westminster Hall. To the
contemplative mind the long history of government and
administration is presented—its struggles, its controversies, its
failures, its successes.
But the most impressive view of the Palace to the eye is obtained
from the opposite bank of the Thames. Standing beneath the aged
and hoary Lambeth Palace on the Surrey side—town house of the
Archbishop of Canterbury—and looking across the river, especially
when the mighty waterway is at its full tide, one realizes more
completely the Gothic stateliness of this temple of legislation, the
outcome of the constructive genius of Sir Charles Barry, and the
graceful fancy of Augustus Welby Pugin. The long façade above the
river wall and terrace, its uniform symmetry, the lightness and grace
of its stone carving, the many steeples and pinnacles—beginning
with the delicate tracery of the lofty Clock Tower, close to
Westminster Bridge, and terminating with the solid massiveness of
the colossal Victoria Tower—form altogether a most imposing
masterpiece in architecture, worthy of the ancient and august
National Assembly which deliberates within its walls, that mother of
representative institutions which perhaps is the greatest gift of the
English race to mankind. So it is that something of the secret of the
high place which Parliament holds in popular esteem and pride may
be found in the grandeur of its home. At any rate, the spectacle
presented by the Palace of Westminster does impress the mind with
the glory of the purpose of Parliament and its might. Here we see
the apotheosis of politics, the science of the progress and well-being
of humanity, and the temple in which it is fittingly served.
Thus at Westminster we have not only the flower or the fruit of
the national life in the guidance of the State aright, but its roots and
fibres going deep down to the very bedrock of the past. For more
than six centuries the grand inquest of the Nation has sat at
Westminster. At first it was a council of the great and wise
summoned by the King personally. When Edward I, “the great law-
giver,” sent to the sheriffs writs for the election of two knights for
each shire, two citizens for each city, two burgesses for each
borough, in addition to himself calling together the prelates and the
nobles, the principle of popular election came into operation. The
Parliament thus elected and known as the “Model Parliament” was
really representative of the Nation at large. It met in the Palace of
Westminster so long ago as November, 1295. For over a century the
three estates of the realm—the Prelates, the Nobles, and the
Commons—deliberated together. The division of Parliament into two
Houses—one for the Peers, spiritual and temporal, and the other for
the Commons—took place in 1377, the last year of the reign of
Edward III. The Lords have always met in the Palace of Westminster.
The Commons for the best part of two centuries assembled in the
Chapter House, or the Refectory, of Westminster Abbey. They held
their last sitting there on the day that Henry VIII died.
Henry’s son and successor, Edward VI, gave St. Stephen’s Chapel
—within the Palace of Westminster—to the Commons for their
meeting place in 1547, the first year of his reign, and there the
representatives of the people regularly met and deliberated until the
place was destroyed by fire in 1834. This Chapel, built by Edward III
in 1327, the first year of his reign, on the ruins of the original St.
Stephen’s Chapel (which was provided by King Stephen in 1147 for
the use of the inhabitants of the Palace, and dedicated by him to the
first Christian martyr) was in the beautiful Gothic of the period, and
Italian artists were brought to London to adorn its walls with
religious frescoes. After the Reformation, when the Chapel was
transferred from the Crown to the House of Commons, these mural
paintings were covered over with a plain, decorous wainscot, which
in the gay times of Charles II was in turn hidden behind rich tapestry
hangings. These tapestries disappeared in the alterations made by
Sir Christopher Wren in 1707, after the Union of England and
Scotland, so as to provide accommodation for the forty-five Members
from Scotland. The Chamber underwent a final transformation in
1800, when, as a result of the Union of Great Britain and Ireland,
seats for 100 additional Members had to be found. The old wainscot
was then taken down; and although the paintings of the Italian
artists of the fourteenth century were found to be in a perfect state
of preservation, they were demolished likewise to make room for the
required two extra lines of benches on each side. There were now
five rows of benches on either side, divided, as in the present
Chamber, by a gangway. The Speaker’s Chair was at the top of the
Chamber, where the altar originally stood. It was a carved oak
armchair, surmounted with the Royal Arms of England. Below it, as
now, was the Clerk’s table.
The old House of Lords, like the old House of Commons, was an
oblong chamber with rows of benches on each side running up from
the floor to the walls. On the walls hung tapestries, divided into
compartments by oak frames, illustrating scenes from the defeat of
the Spanish Armada in 1588, and with medallion portraits of the
principal English naval captains woven in the borders. They were the
gifts of the States of Holland to Queen Elizabeth in commemoration
of England’s great deliverance and the ruined dream of Spain. The
Throne on which all the Sovereigns of England from 1550 to 1834—
from Edward VI to William IV—sat on the assembling of Parliament
was at the top of the Chamber. It was a carved gilt armchair
standing on a dais. The seat was lined with crimson velvet. Two gilt
Corinthian pillars supported a canopy, also of crimson velvet, and the
whole was surmounted by a crown.
Between the two Houses lay the Painted Chamber, a survival of
the original Palace, erected by Edward the Confessor, who indeed
used this particular room as a sleeping apartment and died in it. Its
walls were painted with battle scenes by direction of Henry III in the
middle of the thirteenth century, and hence its name. Here the
Court, before which Charles I was arraigned, sat for the concluding
days of the trial. Here Oliver Cromwell and Henry Martin blacked
each other’s faces in fun, like giddy young schoolboys, as they
signed the warrant which condemned the King to the headsman’s
axe. The Chamber was also used for conferences between
representatives of both Houses when they differed in regard to a Bill.
At these meetings the Peers were seated and wore their hats, while
the Commons had humbly to stand uncovered.

2
Thus the old Palace of Westminster was historically of great
interest. But it had no pretensions to beauty. It was just an
architectural patchwork, added to from time to time without any
sense of order or unity of design. Interiorily, it was also confined and
uncommodious. Yet the idea of pulling it down to give place to a
building of nobler proportions and one more suitable to its great
purpose was not relished. In the very last session of the Commons
that was held in St. Stephen’s Chapel Joseph Hume proposed that
new Houses of Parliament should be built in the Green Park. The
motion was rejected. Four or five months later, as the buildings were
enveloped in flames, one of the spectators wittily cried out: “There is
Joe Hume’s motion being carried without a division.”
The great conflagration which destroyed the Palace was on the
night of Thursday, October 16, 1834. The Whig Ministry, under Earl
Grey, that carried the Reform Act of 1832, broke up in July on the
question of appropriating a portion of the revenues of the Church in
Ireland to secular purposes, and was succeeded by another Whig
Administration with Lord Melbourne as Prime Minister. Parliament
was prorogued on August 15th by King William IV in person. It was
to meet again on October 23rd. When that day came the ancient
Palace of Westminster was a thing of the past. At first it was thought
the fire was the work of political incendiaries. But a Committee of
the Privy Council found, after a long and searching investigation,
that it was due solely to human stupidity. An immense quantity of
old wooden “tallies” or notched sticks, originally used as receipts for
sums paid into the Exchequer, had accumulated at Westminster, and,
after the abolition of this barbaric mode of keeping the national
accounts and the substitution of pens, ink and paper, in 1826, the
sticks were used as firewood in the Government offices. As the room
in which the remaining “tallies” were stored at Westminster was
required for another purpose, two men were employed all day, on
October 16, 1834, in getting rid of the sticks by burning them in the
stove under the House of Lords by which that Chamber was heated.
At five o’clock they went home. At half-past six the House of Lords
was found to be on fire. The heat from the over-charged flues had
ignited the panelling of the Chamber. The progress of the flames
could not be stayed, and gradually the conflagration swept over the
whole mass of buildings. Thus did the ancient Palace of Westminster
disappear through an act of almost incredible carelessness. All that
remained of the historic fabric were the cloisters of the old St.
Stephen’s Chapel (or House of Commons), the crypt beneath the
Chapel, in which the Speaker used to entertain Members at dinners
and other social functions, and, happily, Westminster Hall, with its
centuried associations of great men and historic deeds. Practically
everything else was destroyed, including the Throne in the House of
Lords and the Chair in the House of Commons.
On October 23, 1834, the day appointed for the reassembling of
Parliament, the two Houses met for a brief and formal sitting amid
acres of still smouldering ruins, the Lords within the charred walls of
their library, and the Commons in an adjoining committee-room. It
was decided temporarily to fit up the House of Lords for the use of
the Commons, and the Painted Chamber for the use of the Lords,
and a sum of £30,000 was voted for the purpose. A Royal
Commission was also appointed to superintend the construction of a
new Palace of Westminster. Parliament then adjourned. On
November 14th King William dismissed the Melbourne Ministry, and
Sir Robert Peel was commanded to form a new Administration. On
the advice of the Prime Minister, the King dissolved Parliament on
December 29th, and the new Parliament met on February 19, 1835,
in the temporary buildings, which continued to be used till the
completion of the present Palace of Westminster.

3
Among the immense crowd which witnessed the grand and
terrible spectacle of the burning of the old Houses of Parliament on
that night in October 1834 was an architect named Charles Barry. He
had known and loved the ancient and historic pile from his earliest
years, for, born in 1795, the son of a stationer who had a shop in
Bridge Street, opposite the Houses of Parliament, he had grown to
manhood under its very shadow. Parliament decided to have an
open competition for designs of the new legislative buildings. The
only condition imposed was that the style should be either Gothic or
Elizabethan. As many as ninety-seven architects entered the lists.
The successful competitor was Barry for his Gothic plan. He was
forty years old at the time. In superintending the building and
internal decoration of the Palace—subject to the control of the Royal
Commission—Barry was assisted by Augustus Welby Pugin, another
architect and an authority on the Gothic style. Hume’s idea of
removing the Houses of Parliament to the Green Park was revived,
but the historic associations of Westminster made too great an
appeal. Moreover, was not the Duke of Wellington of opinion—far-
seeing man that he was—that the site by the river was the best, as
it would be fool-hardy to have the Houses of Parliament accessible
on all sides to an attacking mob?
The river wall was begun in 1837. The buildings were not
commenced until three years later. The selection of the stone
received the anxious consideration of the Commissioners. Finally the
hard magnesian limestone from Anston, in Yorkshire, was selected
for the exterior of the buildings, and French Caen stone for the
interior. Then, on April 27, 1840, the first stone—it may be seen from
Westminster Bridge in the south-east angle of the plinth of the
Speaker’s House—was laid without any public ceremony by the wife
of the architect, and the vast edifice was raised on a bed of
concrete, 12 feet thick. Exactly seven years later—April 15, 1847—
the Lords first occupied their House; and at the opening of the
session of 1852, on November 4th, the Commons assembled in their
new Chamber.
The progress of the building was beset with many difficulties and
vexations for the designer. The Palace was originally expected to be
finished in six years, at a cost of £800,000, exclusive of furniture and
fittings. Twenty years passed before it was fully completed, and over
£2,000,000 was expended upon it. The Treasury refused to pay
Barry an architect’s professional fees of 5 per cent. upon the outlay
on the works executed under his direction, and fixed his
remuneration at £25,000, or £23,000 less than he held he was
entitled to. His designs were also subjected to continuous criticism
and attack by other architects. However, he was knighted on the
completion of his splendid work. Dying suddenly at Clapham
Common on May 12, 1860, his remains were honoured by a grave in
Westminster Abbey. His statue by John Henry Foley stands at the
foot of the great staircase leading to the committee-rooms of the
Houses of Parliament.

4
Probably no feature of London is so familiar in the metropolis, or
so widely known by name in the provinces, as the famous clock of
the Houses of Parliament. No visitor to London would think of
returning home without having seen “Big Ben” and heard him
chiming the quarters and booming out the hour. During the summer
season hundreds of thousands of strangers, not only from the
provinces, but from far-off lands, gaze up at his massive, honest
face, proud and delighted to have made the acquaintance of so
great a London celebrity. It is the largest clock in the world. Each of
the four dials, there being one for each point of the compass, is of
white enamelled glass and 23 feet in diameter. The minute marks on
the dial look as if they were close together. They are 14 inches
apart. The numerals are two feet long. The minute hand is 14 feet,
and the hour hand six feet. To wind the clock takes about five hours.
The time is regulated by electric communication with Greenwich
Observatory.
The clock has a large bell to toll the hours and four smaller ones
to chime the quarters. The large bell is called “Big Ben,” after Sir
Benjamin Hall, who was First Commissioner of Works when the Clock
Tower was erected. It weighs 13½ tons. Twenty men could stand
under it. For a clapper it has a piece of iron 2 feet long, 12 inches in
diameter, and weighing 12 cwt. No wonder, then, that there are few
things more impressive than “Big Ben” tolling the hour of twelve, in
his slow, measured and solemn tones, especially at midnight, when
the roar of London is hushed in slumber. And what is said by the full
chime of bells before the striking of each hour? Here is the verse,
simple and beautiful, to which the chime—a run of notes from the
accompaniment to “I know that my Redeemer liveth” in Handel’s
Messiah—is set:
Lord, through this hour
Be Thou our guide,
That by Thy Power
No foot may slide.
During the session of Parliament a brilliant steady light, blazing
from a lantern over “Big Ben,” may be seen at night from most parts
of London. It indicates that the House of Commons is sitting. So long
as the representatives of the people are in conclave, the light flashes
its white flame through the darkness. It vanishes the moment the
House rises. A wire runs from the lantern down to a room under the
floor of the House of Commons, and when the question, “That this
House do now adjourn” is agreed to, a man stationed below pulls a
switch, which instantly extinguishes the light. When this beacon was
first set on high, and for many years after, it shone only towards the
west, for it was thought unlikely than an M.P. would dwell in, or even
visit, any other quarter of the town. But with the extension of the
franchise Parliament became democratized, and a new lantern was
provided which sheds its beams in the direction of Peckham as well
as of Pall Mall. The light should be regarded by all who see it as a
sacred symbol of the fire of liberty, law and justice ever burning in
the House of Commons. Another comparatively recent innovation is
the flying of the Union Jack from the iron flagstaff, 64 feet high,
which tops the 336 feet of the Victoria Tower, on days that
Parliament is sitting. Only the Royal Standard was seen, before that,
on the rare occasions that Queen Victoria came to open Parliament
in person. Small as the Union Jack seems to the upturned gaze of
persons in the streets, it is of remarkable dimensions, being 60 feet
long and 45 feet wide. I saw one day the flag of another country
flying for the first time side by side with the Union Jack over the
Victoria Tower. It was the Stars and Stripes. The day was April 20,
1917—the day on which the United States joined France, Italy and
England in the War against Germany.
5
The Palace of Westminster covers an area of nine acres. Eleven
courts or quadrangles give light and air to its 1,200 or 1,300 rooms,
its hundred staircases, and its two miles of corridors. In the very
heart of the Palace is the great Central Hall, above which rises a
tower terminating in a spire, and right and left of the Hall are the
two Houses of Parliament—the Commons’ Chamber nearer to the
Clock Tower, the Lords’ Chamber nearer to the Victoria Tower—while
about them lie the retiring rooms of their respective Members and
the homes of their principal officers. There, used to be twenty
official residences in the Palace. They have been considerably
reduced in order to provide more accommodation for Members. Still,
on the Commons side, the Speaker, the Clerk and the Sergeant-at-
Arms are commodiously housed. In the old Palace a Minister had no
escape from the House of Commons except the Library or smoking-
room, which were available to all Members, and one gathers from
the published recollections of old parliamentarians that it was not
seemly for a Cabinet Minister to be seen there. “The place for a
Minister,” it used to be said, “if at the House, is in the House.” In the
new Palace every Minister has a private room in the corridors at the
back of the Speaker’s Chair, in which he may transact departmental
business and receive visitors, when his presence in the House is not
particularly required.
The principal entrance to the Palace of Westminster is by St.
Stephen’s Porch, in Old Palace Yard. Immediately to the left extends
the wonderful and impressive Westminster Hall, the thrilling
associations of which must quicken the pulses of the least
imaginative. Straight ahead lies St. Stephen’s Hall, leading to the
Central Hall of the Houses of Parliament. This noble hall is traversed
daily, during the session, by thousands of the public on their way to
or from the Legislative Chambers. How many pay heed to its strange
vicissitudes? It occupies the site of old St. Stephen’s Chapel
(originally the Chapel Royal of the ancient Palace of Westminster), in
which, as I have said, the Commons sat regularly from the sixteenth
century to the nineteenth. In the building of the new Palace, St.
Stephen’s Hall was raised on the vaulted foundations of St. Stephen’s
Chapel. The positions of the Speaker’s Chair and the Table are
marked by brass plates set in the floor of St. Stephen’s Hall. Here it
was that one of the most historic of parliamentary incidents took
place. On this very spot stood Charles I and Mr. Speaker Lenthal
when the King demanded whether there were then present in the
House the five Members, including Pym and Hampden, who had
promoted the Grand Remonstrance against his unconstitutional
action, and the Speaker made his famous reply: “I have neither eyes
to see nor tongue to speak in this place, but as the House is pleased
to direct me, whose servant I am,” and when the angry cries of
“Privilege, Privilege!” raised by Members were the presage of civil
war. St. Stephen’s Hall fittingly contains statues of twelve of the
greatest and wisest statesmen whose voices so often rang through
the old House of Commons. The statesmen thus honoured are
Selden, Hampden, Falkland, Clarendon, Somers, Walpole, Chatham,
Mansfield, Burke, Fox, Pitt and Grattan; and the selection was made
by the historians Macaulay and Hallam.
Beneath St. Stephen’s Hall is the old crypt of St. Stephen’s Chapel.
Like the Chapel, it was originally used for religious services. For
centuries after the Reformation it was used as a place for shooting
rubbish. About a quarter of a century before the fire of 1834 it was
converted into a dining-room in which the dinners given by the
Speaker to Members took place. After the fire the crypt was restored
to its original purpose, and for a time was a place of worship for the
numerous residents within the area of the Palace of Westminster. It
is the most beautiful place in the Palace, with its altar, inlaid marble
floor, walls of mosaic and groined ceiling. It is also a place of
solitude and silence. Not for years has it been used as a place of
worship. The only sound to which it now re-echoes is the cry of the
infant as the water of baptism is poured on its head. One of the few
privileges of an M.P. is that a child born to him may be christened in
St. Stephen’s Crypt.
A new Member is not many hours in the Palace of Westminster
before he has secured the special peg for his hat and overcoat in the
beautiful cloisters of old St. Stephen’s, which has been turned into a
cloak-room for the Commons; obtained one of the long rows of
lockers, or presses, in the corridors, immediately surrounding the
Chamber, to which each Member is entitled, for storing books and
papers; enjoyed a pipe or cigar in the smoking-room; had a meal in
one of the several dining-rooms; read the newspapers in the news-
room, or made himself acquainted with some of the contents of the
extensive Library; strolled on the Terrace; had tea in the tea-room,
and dispatched numbers of letters on the official stationery of the
House to relatives and friends giving his first impressions of the
scene where glory or obscurity awaits him as a representative of the
people.

6
One of the most pleasant adjuncts of the House of Commons is
the large and lofty suite of rooms overlooking the Thames, which is
devoted to the Library. But there is more in these apartments than
books. They also contain some rare and most interesting historical
relics, parliamentary and political. Here in a glass case is shown a
manuscript volume, stained and mouldered, of the old Journals of
the House of Commons. The writing on the pages that are open is
not easily decipherable. But it is well worth while endeavouring to
peruse it, for it is the official chronicle of the raid of Charles I on the
House of Commons. The shaky handwriting tells of the agitation of
the Clerk when he made the record.
In the Library is also to be seen a memento of a curious privilege
enjoyed of old by Members of Parliament. This is a collection of
envelopes franked by eminent Members of both Houses. It
comprises about 10,000 signatures, and covers the period from 1784
to 1840, when franking was abolished. By the system of franking,
Peers and Commons had the free delivery of letters posted by
themselves and their friends. It was introduced in 1660 to relieve
Members of some of the expenses incurred in the discharge of their
national duties. But this freedom of the Post Office was not confined
to letters. Household furniture and even a pack of hounds were sent
free through the post by M.P.’s in England, and in Ireland an M.P.
franked his wife and children from Galway to Dublin and back on a
holiday trip. Members also signed packets of letters wholesale and
gave them away to friends. One noble lord thereby franked the
tidings of his own death. He died suddenly at his desk after
addressing some covers to friends, and the family economically used
the covers to tell those friends that he had passed away. Ultimately,
in the last decade of the eighteenth century, the daily allowance to
each Member of both Houses was limited to ten sent by himself and
fifteen received by him. All such letters had to bear on their covers
the signatures of those who franked them. In the House of
Commons collection are to be seen the autographs of archbishops
and bishops, of Peers and of Commoners, including such celebrities
as Nelson, Byron, Canning, Fox, Peel, Palmerston, Wellington, Clive,
Cobbett, Grattan, O’Connell and Gladstone. In the year 1837 as
many as 7,400,000 franked letters were posted, at an estimated loss
to the revenue of the Post Office of over £1,000,000. At the same
time all sorts of devices had to be resorted to by the poor to evade
the heavy postage, from 10d. to 1s. 6d., which was then charged for
letters. Rowland Hill, the author of the penny postal system, used to
underline words in newspapers which he sent home—a Whig
politician’s name to indicate that he was well, and a Tory’s that he
was ill. Franking was abolished in 1840, on the establishment of the
penny post. Members, however, are still entitled to the privilege of
sending free through the post a limited number of copies of a Bill to
their constituents, by endorsing the covering wrapper with their
signatures.
The table of the old House of Commons, which was designed by
Sir Christopher Wren in 1706, and at which Burke, Pitt, Fox, Canning
and Peel stood while addressing the House, was found in the ruins,
after the fire of 1834, almost uninjured. It is now preserved in the
tea-room. In one of the smoking-rooms is to be seen an interesting
memorial of Henry Broadhurst, one of the first of the Labour
members. In a glass case are the mallet and chisels used by him as
a stonemason employed on the buildings of the new Palace of
Westminster, which he was afterwards to enter, not only as a
Member, but as a Minister, for he served as Under-Secretary of the
Home Department in 1886.

7
The old Houses of Parliament had no such pleasant lounge as the
Terrace, which extends the whole length of the river front. On
summer nights Members who desired a blow of fresh air
promenaded old Westminster Bridge. “It was a beautiful, rosy, dead
calm morning when we broke up a little before five to-day,” wrote
Francis Jeffrey, M.P. and editor of the Edinburgh Review, to a friend
on April 20, 1831, in reference to a late and stormy sitting over the
first Reform Bill, “and I took three pensive turns along the solitude of
Westminster Bridge, admiring the sharp clearness of St. Paul’s, and
all the city spires soaring up in a cloudless sky, the orange-red light
that was beginning to play on the trees of the Abbey and the old
windows of the Speaker’s house, and the flat green mist of the river
floating upon a few lazy hulks on the tide and moving low under the
arches. It was a curious contrast with the long previous
imprisonment in the stifling, roaring House, amid dying candles, and
every sort of exhalation.” If Jeffrey could return from the Shades and
see the Terrace, especially on a fine afternoon in June or July, when
“five o’clock tea” is being served, how amazed he would be, and
how he would curse his fate that he should have been born a
century or so too soon! Perhaps? For there are legislators who think
that “Tea on the Terrace” is a function lowering to the dignity of
Parliament. A part of the Terrace is reserved for their sole use by a
notice, “For Members Only,” where they may ruminate in gloomy
aloofness undisturbed by the smiles of beauty and the rustle of her
skirts.
As the new Member explores the corridors and rooms, he will see
the walls hung with portraits of all the Prime Ministers, all the
Speakers, and a long line of Chancellors of the Exchequer, besides
those of other distinguished politicians who never attained to office.
Apart from their innate interest as counterfeit presentments of great
statesmen, in mezzotints or line engravings, these pictures should
stimulate the ambition of the new Member to make a name for
himself. There is one way in which the new Member may employ his
leisure at Westminster with profit to the tax-payer. That is to follow
the excellent example set by Passmore Edwards, the philanthropist,
who sat in Parliament for a number of years in the last quarter of
the nineteenth century. Writing in his autobiography, A Few
Footprints, he says:
I would write the words “Waste not, want not” over the doors of
parliament houses, palaces, cottages, workshops and kitchens; and if
the spirit and meaning of the motto were put in practice the world would
spin through space with a double joy. While a Member of Parliament I
always, when opportunity offered, lowered the gas within reach that was
burning to waste. I did so for a double reason—to prevent waste and to
preserve the purity of the air of the House; but I never saw or heard of
any other Member or servant of the House doing a similar thing.

“True political economy,” Edwards adds, “is in reality true moral


economy. I hate waste anywhere and everywhere.”
CHAPTER VIII

ASSEMBLING OF THE NEW PARLIAMENT

1
The procedure of Parliament is very ancient. An old-world spirit
animates especially the quaint and curious ceremonies that mark the
assembling of a new Parliament. The House of Commons is
crowded. What a number of strange faces are in the throng! It is
easy to distinguish the new Members by the eager looks of curiosity
and wonder, not unmixed with triumph, with which they gaze on
every feature of the historic Chamber and follow every movement of
the officials, and the shyness with which they cheer, or indulge in
forms of applause unfamiliar to the House, such as the clapping of
hands, as their leaders appear and take their places on the two front
benches—the Treasury Bench on one side and the Opposition Bench
on the other. But this shyness soon disappears. There is a story told
that an old Member was thus addressed by a new Member at the
opening of a new Parliament: “If you please, sir, where do the
Members for boroughs sit?” The incident was told to Disraeli, who
was much diverted. “Yes,” said he, “and in three months we shall
have that Member bawling and bellowing and making such a row
there will be no holding him!” At one time county Members and
borough Members were distinct not only in class, but in manners
and dress. The ancient distinction between “Knight of the Shire,”
“Citizen of the City,” “Burgess of the Borough,” was removed by the
Ballot Act of 1872, all representatives being grouped as “Members of
the House of Commons.”
As yet they are without a head. They have no Speaker. In fact, the
House of Commons has not yet been constituted. It is only when the
Speaker is elected and the Members have taken the oath of
allegiance and signed the Roll that the House really begins its
corporate existence. The first thing to be done, therefore, is for this
throng to obtain that coherency, that solidarity, which is given to an
assembly by the appointment of a president. Until the Speaker is
elected, the Clerk, sitting in wig and gown at the Table, assumes the
direction of affairs. But before the Commons can appoint a Speaker
they must have the consent of the Sovereign, and that is given them
at the Bar of the House of Lords.
Suddenly the buzz of conversation, the interchange of jokes, and
the laughter which follows, are stilled by a stentorian cry of “Black
Rod.” It comes from the door-keeper in the lobby outside. Presently
“Black Rod,” the messenger of the House of Lords, appears. He is
never allowed free access to the House of Commons. The doors are
closed in his face by the Serjeant-at-Arms, and he has to knock for
admission before it is granted to him. He walks slowly up the floor,
carrying in his right hand a short ebony rod tipped with gold, the
emblem of his office. On reaching the Table “Black Rod” delivers his
message, which is an invitation to the Commons to come to the
House of Lords. Then, retreating backwards down the floor to the
Bar, he waits until joined by the Clerk, when the two officials walk
across the intervening lobbies to the House of Lords, followed by a
struggling crowd of new Members, determined not to miss anything,
shoving and jostling each other in their eagerness to secure good
places in the “Gilded Chamber.”
“Gilded Chamber,” indeed! Gladstone’s most appropriate
description of the House of Lords springs at once to the mind, such
is its gorgeous colouring in which gold predominates, and its glow
and sparkle, especially when the electric lights are on. The first thing
that arrests the eye of the spectator is the Throne, provided with
two chairs for the King and Queen, and emblazoned with the Royal
Arms, on a dais at the top of the Chamber. It is unoccupied, but
seated on a bench beneath it, all in a row, are five Lords, arrayed in
ample red robes, slashed with ermine or white fur, and three-
cornered hats. These are the Lords Commissioners, to whom the
King delegates his authority in matters parliamentary when his
Majesty is not present in person.
When the Commons, headed by the Clerk, stand huddled together
at the Bar, the Lord Chancellor—the central personage among the
Lords Commissioners—without rising from his seat or even lifting his
hat by way of salutation, informs them that his Majesty has been
pleased to issue Letters Patent under the Great Seal constituting a
Royal Commission to do all things in his Majesty’s name necessary to
the holding of the Parliament. He then addresses the Members of
the two Houses of the Legislature in the following words:

My Lords and Gentlemen,—We have it in command from his Majesty to


let you know that his Majesty will, as soon as the Members of both
Houses shall be sworn, declare the causes of his calling this Parliament;
and it being necessary that a Speaker of the House of Commons shall be
first chosen, it is his Majesty’s pleasure that you, gentlemen of the
House of Commons, repair to the place where you are to sit and there
proceed to the choice of some proper person to be your Speaker, and
that you present such person whom you shall so choose here to-morrow
at twelve o’clock for his Majesty’s Royal approbation.

Then the Clerk and the Members of the House of Commons,


without a word having been spoken on their side, return to their
Chamber.

2
The election of Speaker is at once proceeded with in the House of
Commons. There is no ceremony at Westminster more novel and
interesting, and none that illustrates more strikingly the continuity
through the centuries of parliamentary customs. The Clerk of the
House of Commons presides. He sits in his own seat at the Table.
Immediately behind him is the untenanted high-canopied Chair of
the Speaker. The Mace, that glittering emblem of the Speaker’s
authority, is invisible. The Clerk may not speak a word in the
discharge of his duties on this great occasion. All he is permitted to
do is to rise and silently point with outstretched finger at the
Member who, according to previous arrangement, is to propose the
candidate for the Chair, and later on to indicate in the same dumb
way the Member who is to second the motion. If there is to be no
contest, and at the assembling of a new Parliament the former
Speaker is invariably re-elected unanimously, the motion that he “do
take the Chair of this House as Speaker” is made by a leading
unofficial Ministerialist, and seconded by an old and respected
Member of the Opposition. The Government take no part in the
ceremony so far, in accordance with an old-established tradition that
the election or re-election of a Speaker is the independent and
unfettered action of the House. The motion is not put to the House
in the customary manner. The Clerk does not say, “The question is
that James William Lowther do take the Chair of this House as
Speaker.” The Speaker-designate rises in his place on one of the
back benches and humbly submits himself to the will of the House.
The Commons express their unanimous approval of the motion by
cheers without question put. Thus the Speaker-Elect is literally
“called” to the Chair by the House.
In one respect only has time altered the symbolic details of the
ceremony. In the long, long ago it was the custom for the Member
chosen for the Chair humbly to protest that of all the House he was
the least suited for the exalted position. An amusing instance of this
modest declaration of unfitness comes down to us from the days of
Queen Elizabeth. The House of Commons having met for the choice
of a Speaker, Mr. Serjeant Yelverton was proposed by Sir William
Knowles. “I know him,” said Knowles, “to be a man wise and
learned, secret and circumspect, religious and faithful, every way
able to fill the place.” “Aye, aye, aye,” cried the whole House; “let
him be Speaker.” Then rose the modest, blushing Yelverton. He said
he was at a loss to account for his selection for the Chair, lacking as
he did every quality that was necessary in a Speaker. He had no
merit and no ability. He was moreover a poor man with a large
family. Nor was he of a sufficiently imposing presence. The Speaker
ought to be a big man, stately and comely, well-spoken, his voice
great, his carriage majestical, his nature haughty, and his purse
plentiful and heavy. But, contrarily, he was of a small body, he spoke
indifferently, his voice was low, his carriage of the commonest
fashion, his nature soft and yielding, and his purse light. He adjured
the House to consider well before it made the grievous mistake of
appointing to the Chair a man so totally unfitted for the post. But the
House, mightily impressed by these humble expostulations, so
becoming in a candidate for the Speakership, persisted in
unanimously electing Mr. Serjeant Yelverton; as, indeed, Mr. Serjeant
Yelverton, despite all his protestations of unworthiness, well and
gladly knew they would do.
It is not so long since another amusing piece of comedy used to
be enacted on this otherwise serious and solemn occasion. The
proposer and seconder of the Speaker-designate were required in
the prescribed parliamentary phrase to “take him out of his place”
and conduct him to the Chair; while he was obliged to wriggle his
shoulders as if he were struggling to free himself from their hands
and escape from the House. Surely they were not serious—he meant
to convey—in conferring upon one so lowly and unworthy an office
so dignified and exalted? This display of mock modesty is now a
thing of the past. The only part of it that survives is that the
proposer and seconder approach the Speaker-designate, and when
they are within a few paces of him, the Speaker-designate rises and
walks to the Chair, his sponsors following close behind. The Speaker-
designate does not, however, immediately go into the Chair.
Standing on the dais, he again thanks the House for the high honour
conferred on him, and then takes his seat as “Speaker-Elect,” as he
is called at this stage of his evolution. The glittering Mace, which all
the time lay hidden under the Table, is now placed by the Serjeant-
at-Arms in its usual position within sight of all eyes to indicate that
the House is sitting. Then follow congratulations generally offered by
the Leader of the House and the Leader of the Opposition, after
which the House adjourns. The first day’s ceremony of the opening
of the new Parliament is over.

3
But although the Commons have chosen one of their number “to
take the Chair of this House as Speaker,” the Constitution requires
that before he can enter upon the duties of his office he must
submit himself in the House of Lords for the Sovereign’s ratification
of his election. Until the approval of the Crown has been signified he
continues to be styled “Mr. Speaker-Elect.” Next day sees the
completion of the ceremony of Mr. Speaker’s election. He enters the
Chamber, by way of the lobby, heralded by the ushers who preceded
him, crying “Way for the Speaker-Elect” with an emphasis on “elect,”
and attended by the Serjeant-at-Arms. It is also evident from the
dress of the choice of the Commons, that his evolution as Mr.
Speaker is not yet complete. He is still, as it were, in the chrysalis or
transition state. He is seen to be only half-made up, wearing, it is
true, the customary Court dress—cutaway coat, knee-breeches, silk
stockings, and shoes—but not the customary full-flowing silk gown,
and with only a small bob-wig—that is, the short wig of counsel
when practising in courts of law—instead of the customary full-
bottomed wig with wings, which fall over his shoulders. Further, it is
noticeable that the Serjeant-at-Arms does not carry the Mace on his
shoulder—as he usually does—but holds it reclining in the hollow of
his left arm, his right hand grasping its end.
The Lords assemble on the second day of the new Parliament at
the same hour as the Commons, and once more is “Black Rod”
despatched to invite the attendance of Members of the Lower House
to the House of Peers, to hear the Royal will in regard to the election
of the Speaker. On arriving at the Upper Chamber, the Speaker-Elect
stands at the centre of the Bar, with “Black Rod” to his right, the
Serjeant-at-Arms (who has left the Mace outside) to his left, and his
proposer and seconder immediately behind in the forefront of the
crowd of Commons who have followed him across the lobbies. He
bows to the Lords Commissioners, who, in all the glory of scarlet
robes and cocked hats, are again seated on the form in front of the
Throne, and they who yesterday encountered the Commons without
lifting a hat, now acknowledge the salutation of the Speaker-Elect by
thrice respectfully bending their uncovered heads. Then the
Speaker-Elect addresses them as follows:

I have to acquaint your Lordships that, in obedience to his Royal


commands, his Majesty’s faithful Commons have, in the exercise of their
undoubted right and privilege, proceeded to the choice of a Speaker.
Their choice has fallen upon myself, and I therefore present myself at
your Lordship’s Bar humbly submitting myself for his Majesty’s gracious
approbation.

To this the Lord Chancellor, addressing the Speaker-Elect by name,


replies:

We are commanded to assure you that his Majesty is so fully sensible


of your zeal for the public service, and your undoubted efficiency to
execute all the arduous duties of the position which his faithful
Commons have selected you to discharge, that he does most readily
approve and confirm your election as Speaker.

His election having thus been ratified by the Sovereign, Mr.


Speaker “submits himself in all humility to his Majesty’s royal will and
pleasure”; and if, says he, in the discharge of his duties, and in
maintaining the rights and privileges of the Commons’ House of
Parliament, he should fall inadvertently into error, he “entreats that
the blame may be imputed to him alone, and not to his Majesty’s
faithful Commons.” Assertions of the rights and privileges of the
House of Commons follow fast on expressions of loyalty to the
Throne during the ten minutes that the Speaker, surrounded by “the
faithful Commons,” stands at the Bar of the House of Lords, and
holds this significant historical colloquy—which has been repeated at
every election of Speaker on the assembling of a new Parliament for
many centuries—with the Lord Chancellor, not as the President of
the House of Lords, but as the representative of the Sovereign; for
the next duty of the Speaker is to request from the Sovereign
recognition of all the ancient rights and privileges of Members of
Parliament, which are “readily granted” by the Sovereign, speaking
through the Lord Chancellor. This ends the ceremonial. The Speaker
and the Commons return to their Chamber as they came. But, see,
the Mace is now borne high on the shoulder of the Serjeant-at-Arms,
and hear the usher announcing “Mr. Speaker” and “Way for Mr.
Speaker.” The Speaker passes through the Chamber to his rooms,
and in a few minutes comes back arrayed in the complete robes of
his office. Then, standing on the dais of the Chair, he reports what
took place in the House of Lords. It is one of the curious customs of
Parliament that the Speaker always assumes that he has been to the
House of Lords alone, and that the Commons are in absolute
ignorance of what has happened there. Without the slightest tremor
of emotion, or the faintest indication of satisfaction, the Commoners
learn that their “ancient rights and undoubted privileges” have been
fully confirmed, particularly freedom from arrest and molestation,
liberty of speech in their debates, and free access to the Sovereign.
They know full well that if they do anything criminal they may feel
the dread touch of the policeman on their shoulders—freedom from
arrest for debt was abolished long ago—and they know also that
even if they would they could not disturb the domestic privacy of the
King. So the solemn announcement evokes not a solitary cheer. But
there is loud applause upon the Speaker thus finally concluding: “I
have now again to make my grateful acknowledgments to the House
for the honour done to me in placing me again in the Chair, and to
assure it of my complete devotion to its service.” The ancient and
picturesque ceremony of the election of Speaker of the House of
Commons is completed.

4
At the assembling of every new Parliament the Members for the
City of London, in accordance with an ancient custom, have the
privilege of sitting on the Treasury Bench with the Ministers, though
for the opening day only. I have frequently read in the newspapers
that this privilege was given to the City of London by way of
commemorating the protection afforded to the Five Members on that
historic day, January 4, 1642, when Charles I came down to the
House of Commons to arrest them for their opposition to his will,
and found to his discomfiture that “the birds had flown,” to use his
own words. The statement is not well established. It is a singular
thing that no written record of the origin or existence of the custom
is to be found at the Guildhall any more than at the House of
Commons. But there is authority for saying that the right was
exercised in the time of Elizabeth, and over seventy years before the
conflict between Charles I and the Parliament.
The earliest reference to it is contained in a Report on the
Procedure of the English Parliament prepared in 1568 at the request
of the then Speaker of the Irish Parliament by Hooker, a well-known
antiquarian of the time, who was a Member both of the English and
Irish Parliaments. This report was printed and presented to the Irish
Parliament, and was reprinted in London about 1575 under the title
of “The Order and Usuage of the Keeping of a Parliament in
England.” It is set out fully in Lord Mountmorres’s History of the
Principal Transactions in the Irish Parliament from 1634 to 1666,
published in 1792. Hooker, describing the seating of Members in the
House of Commons, says:

Upon the lower row on both sides the Speaker, sit such personages as
be of the King’s Privy Counsel, or of his Chief Officers; but as for any
other, none claimeth, or can claim, any place, but sitteth as he cometh,
saving that on the right hand of the Speaker next beneath the said
Counsels, the Londoners and the citizens of York do sit, and so in order
should sit all the citizens accordingly.

It will be noticed that the representatives of York as well as those


of London sat, according to Hooker, on the Front Bench to the right
of the Speaker. Probably the privilege was conferred upon London
and York as being the first and second cities of the Kingdom. But it
seems clear that the privilege was not at first confined merely to the
opening day of a new Parliament, but was exercised at every sitting
of the House of Commons. The only other authoritative statement
on this subject which I have found is in Oldfield’s Representative
History of Great Britain and Ireland, published in 1816. The passage
is as follows: “It (York City) sends two Members to Parliament, who
are chosen by the freemen in general, and who enjoy the privilege
of sitting in their scarlet gowns next the Members for London on the
Privy Councillors’ bench on the first day of the meeting of every new
Parliament.” In 1910, the then representatives of York, A. Rowntree
and John Butcher, with a view to asserting this privilege in the same
manner as it is asserted by the representatives of the City of
London, laid the facts before Mr. Speaker Lowther. After a full
consideration of the matter he gave it as his opinion that, assuming
the right to have once existed, it must be considered, in the absence
of any evidence of having been used in modern times, to have
lapsed, and could not now be properly claimed or exercised.

5
On the morning of the day that the new Parliament meets for
business—the day on which the King’s Speech is read—the corridors,
vaults and cellars of the Palace of Westminster are searched to see
that all is well with the building and safe for the King, Lords and
Commons to assemble within it—a ceremony (for it is now only that)
which is repeated on the opening day of every session. It recalls the
Gunpowder Plot of Guy Fawkes to blow up the Parliament in 1605.
The Commons possess but one memento of Guy, that most
notorious of all anti-parliamentarians. In a glass case in the
Members’ Library may be seen a long, narrow key with a hinge in
the centre for folding it up—so that it might be carried more
conveniently in the pocket—which was found on Fawkes when he
was captured. It was the key to the cellar of gunpowder extending
under the House of Lords, though it was really part of an adjoining
empty house which the conspirators had taken for their purpose.
The custom of searching the Houses of Parliament is popularly
supposed to date from the Gunpowder Plot, but it did not commence
until eighty-five years later. According to a document preserved in
the House of Lords, an anonymous warning received in 1690 by the
Marquess of Carmarthen, setting forth, “There is great cause to
judge that there is a second Gunpowder Plot, or some other such
great mischief, designing against the King and Parliament by a
frequent and great resort of notorious ill-willers at most private
hours to the house of one Hutchinson in the Old Palace Yard,
Westminster, situate very dangerous for such purpose,” led to a
thorough examination of the buildings, and though nothing was then
found, from that time to this the search appears to have been
regularly made year after year.
The search party consists of twelve Yeomen of the Guard from the
Tower in all the picturesque glory of their Tudor uniforms,
accompanied by representatives of the Lord Great Chamberlain and
the Office of Works, and the two police inspectors of the Houses of
Lords and Commons. They tramp through the miles of corridors and
lobbies, looking carefully into every nook and corner, and down in
the equally extensive basements they examine everything with the
utmost minuteness, going among gas pipes, steam pipes, hot-water
pipes, electric-light conductors, to make sure that no explosives have
been deposited there. When the search was first ordered, years and
years ago, the Yeomen of the Guard were directed to carry lanterns
to light their way through the dark passages. The corridors and
cellars are now flooded with electric light. But the search party, still
obeying the old order, march along swinging their lanterns. And still
the solemn function ends up with service of cake and wine to the old
Beefeaters, and the drinking of long life to the King, with a hip-hip
hurrah! Only in one respect is there a departure from the old
procedure. At one time it was customary, when the inspection was
over, for the Lord Great Chamberlain to send a mounted soldier with
the message “All’s well” to the Sovereign. The mounted soldier no
longer rides post-haste to the King at Buckingham Palace; but every
year the Vice-Chamberlain lets his Majesty know, by private wire,
that everything is ready for his coming to meet the Lords and
Commons in the House of Lords to announce from the Throne the
business for which he has summoned Parliament to meet.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like