100% found this document useful (3 votes)
2K views

Full Download Pro C# 7 With .NET and .NET Core Andrew Troelsen PDF

ebook

Uploaded by

meylinrible
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 (3 votes)
2K views

Full Download Pro C# 7 With .NET and .NET Core Andrew Troelsen PDF

ebook

Uploaded by

meylinrible
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/ 53

Full download test bank at ebook textbookfull.

com

Pro C# 7 with .NET and .NET Core

CLICK LINK TO DOWLOAD

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

textbookfull
More products digital (pdf, epub, mobi) instant
download maybe you interests ...

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/

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/

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/

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/
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/

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/

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/

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/

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/
Pro C# 7
With .NET and .NET Core

Eighth Edition

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

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


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


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

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

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


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

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

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


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

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

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

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

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


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

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

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

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

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

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


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

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

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

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

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


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

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

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

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

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

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


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

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

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

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

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

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


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

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

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


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

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

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

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

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

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


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


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

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

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

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


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

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


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

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


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

vii
■ Contents

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


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

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


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

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


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

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


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

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


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

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

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

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


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

viii
■ Contents


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

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

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


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

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


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

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


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

ix
■ Contents

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


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

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


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

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


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

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

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


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

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

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

x
■ Contents

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


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

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


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

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


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

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


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

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


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

xi
■ Contents

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


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

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


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

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


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

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

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


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

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


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

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


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

xii
■ 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
Another random document with
no related content on Scribd:
379. Mr. Maclaurin having noticed that the Author of Nature has
made it impossible for us to have any communication, from this
earth, with the other great bodies of the universe, in our present
state; and after remarking on some phænomena in the planetary
system, makes the following just reflections, which correspond with
those expressed by Dr. Rittenhouse, in the concluding pages of his
Oration:—“From hence, as well as from the state of the moral world
and many other considerations, we are induced to believe, that our
present state would be very imperfect without a subsequent one;
wherein our views of nature, and of its great Author, may be more
clear and satisfactory. It does not appear to be suitable to the
wisdom that shines throughout all nature, to suppose that we should
see so far, and have our curiosity so much raised concerning the
works of God, only to be disappointed in the end. As man is
undoubtedly the chief being upon this globe, and this globe may be
no less considerable, in the most valuable respects, than any other
in the solar system, and this system, for ought we know, not inferior
to any other in the universal system; so, if we should suppose man
to perish, without ever arriving at a more complete knowledge of
nature, than the very imperfect one he attains in his present state; by
analogy, or parity of reason, we might conclude, that the like desires
would be frustrated in the inhabitants of all the other planets and
systems; and that the beautiful scheme of nature would never be
unfolded, but in an exceedingly imperfect manner, to any of them.
This, therefore, naturally leads us to consider our present state as
only the dawn or beginning of our existence, and as a state of
preparation or probation for farther advancement: which appears to
have been the opinion of the most judicious philosophers of old. And
whoever attentively considers the constitution of human nature,
particularly the desires and passions of men, which appear greatly
superior to their present objects, will easily be persuaded that man
was designed for higher views than of this life. Surely, it is in His
power to grant us a far greater improvement of the faculties we
already possess, or even to endow us with new faculties, of which, at
this time, we have no idea, for penetrating farther into the scheme of
nature, and approaching nearer to Himself, the First and Supreme
Cause.”
The striking coincidence of the foregoing sentiments, with those
expressed by Dr. Rittenhouse; in addition to the sublimity of the
conceptions; the cogency of the argument; and the weight of the
concurring opinions of two so great astronomers and
mathematicians, on a subject of such high importance to mankind;
all plead an apology for the length of this extract, from Maclaurin’s
Account of Sir Isaac Newton’s Philosophical Discoveries.

380. Patrick Murdoch, M.A.F.R.S.

381. The words between inverted commas, in the above


paragraph, are quoted from Rittenhouse’s Oration.

Notwithstanding the fanciful theories introduced into physics by


Descartes, concerning his materia subtilis and vortices, and his
doctrine of a plenum, which were prostrated by the general adoption
of the Newtonian system, the improvements that had been made in
the mathematical sciences and some other branches of physics, by
the Cartesian system, produced a great revolution in the species of
philosophy which till then prevailed. The philosophy of Descartes,
erroneous and defective as, in some particulars, it was found to be,
triumphed, by its superior energy, over the crude and feeble systems
of the schools. The peripatetic doctrines which had revived in
Europe, after she emerged from the barbarism and gloom that
succeeded the final declension of the Roman empire, continued from
that period to be the prevailing philosophy; and tinctured, also, the
whole mass of the scholastic theology: but the systems of Descartes
first dissipated most of the useless subtleties of the schoolmen; while
the truths brought to light by the philosophy of Newton, still further
exposed their absurdities. According to Dr. Reid (in his Essays on
the intellectual and active powers of Man,) even the most useful and
intelligible parts of the writings of Aristotle himself had, among them,
become neglected; and philosophy was reduced to an art of
speaking learnedly and disputing subtilely, without producing any
invention of utility in the affairs of human life. “It was,” to use the
language of Dr. Reid, “fruitful in words, but barren of works; and
admirably contrived for drawing a veil over human ignorance, and
putting a stop to the progress of knowledge, by filling men with a
conceit that they knew every thing. It was very fruitful also in
controversies; but, for the most part, they were controversies about
words, or things above the reach of the human faculties.”

382. The celebrated Dr. Samuel Johnson has remarked, that


“Leibnitz persisted in affirming that Newton called Space, Censorium
Numinis, notwithstanding he was corrected, and desired to observe
that Newton’s words were, Quasi Censorium Numinis. See Boswell’s
Journal of a Tour to the Hebrides.

383. This concise, yet beautiful and expressive sentence, is


contained in St. Paul’s address to the Athenians, cited in the 17th
chapter of the Acts of the Apostles.

384. A strong proof of this veneration will be found in Dr.


Rittenhouse’s Oration, wherein he expresses himself in these
remarkable words:—“It was, I make no doubt, by a particular
appointment of Providence, that at this time the immortal Newton
appeared.”

385. Lord Strangford, in his Remarks on the Life and Writings of


Camoens.

386. See his Oration.


APPENDIX.

AN ORATION,
DELIVERED FEBRUARY 24, 1775,
BEFORE
THE AMERICAN PHILOSOPHICAL SOCIETY,
HELD AT PHILADELPHIA,
FOR PROMOTING USEFUL KNOWLEDGE.
BY DAVID RITTENHOUSE, A. M.
MEMBER OF THE SAID SOCIETY.

(INSCRIBED)

To the Delegates of the thirteen United Colonies, assembled in Congress, at


Philadelphia, to whom the future liberties, and consequently the virtue,
improvement in science and happiness, of America, are intrusted, the following
Oration is inscribed and dedicated, by their most obedient and humble servant,
the Author.

Gentlemen,

It was not without being sensible how very unequal I am to the


undertaking, that I first consented to comply with the request of
several gentlemen for whom I have the highest esteem, and to solicit
your attention on a subject which an able hand might indeed render
both entertaining and instructive; I mean Astronomy. But the earnest
desire I have to contribute something towards the improvement of
Science in general, and particularly of Astronomy, in this my native
country, joined with the fullest confidence that I shall be favoured
with your most candid indulgence, however far I may fall short of
doing justice to the noble subject, enables me chearfully to take my
turn as a member of the society, on this annual occasion.

The order I shall observe in the following discourse, is this: In the


first place I shall give a very short account of the rise and progress of
astronomy, then take notice of some of the most important
discoveries that have been made in this science, and conclude with
pointing out a few of its defects at the present time.

As, on this occasion, it is not necessary to treat my subject in a


strictly scientific way, I shall hazard some conjectures of my own;
which, if they have but novelty to recommend them, may perhaps be
more acceptable than retailing the conjectures of others.

The first rise of astronomy, like the beginnings of other sciences, is


lost in the obscurity of ancient times. Some have attributed its origin
to that strong propensity mankind have discovered, in all ages, for
prying into futurity; supposing that astronomy was cultivated only as
subservient to judicial astrology. Others with more reason suppose
astrology to have been the spurious offspring of astronomy; a
supposition that does but add one more to the many instances of
human depravity, which can convert the best things to the worst
purposes.

The honour of first cultivating astronomy has been ascribed to the


Chaldeans, the Egyptians, the Arabians, and likewise to the
Chinese;[A1] amongst whom, it is pretended, astronomical
observations are to be found of almost as early a date as the flood.
But little credit is given to these reports of the Jesuits, who it is
thought were imposed on by the natives; or else perhaps from
motives of vanity, they have departed a little from truth, in their
accounts of a country and people among whom they were the chief
European travellers.

Not to mention the prodigious number of years in which it is said


the Chaldeans observed the heavens, I pass on to what carries the
appearance of more probability;[A2] the report that when Alexander
took Babylon, astronomical observations for one thousand nine
hundred years before that time were found there, and sent from
thence to Aristotle. But we cannot suppose those observations to
have been of much value; for we do not find that any use was ever
after made of them.[A3]

The Egyptians too, we are told, had observations of the stars for
one thousand five hundred years before the Christian era. What they
were, is not known; but probably the astronomy of those ages
consisted in little more than remarks on the rising and setting of the
fixed stars, as they were found to correspond with the seasons of the
year;[A4] and, perhaps, forming them into constellations. That this was
done early, appears from the book of Job, which has by some been
attributed to Moses, who is said to have been learned in the
sciences of Egypt.[A5] “Canst thou bind the sweet influences of
Pleiades, or loose the bands of Orion? Canst thou bring forth
Mazzaroth in his season, or canst thou guide Arcturus with his
sons?” Perhaps too, some account might be kept of eclipses of the
sun and moon, as they happened, without pretending to predict them
for the future. These eclipses are thought by some to have been
foretold by the Jewish prophets in a supernatural way.

As to the Arabians, though some have supposed them the first


inventors of astronomy, encouraged to contemplate the heavens by
the happy temperature of their climate, and the serenity of their
skies, which their manner of life must likewise have contributed to
render more particularly the object of their attention; yet it is said,
nothing of certainty can now be found to induce us to think they had
any knowledge of this science amongst them before they learned it
from the writings of Ptolemy, who flourished one hundred and forty
years after the birth of Christ.

But notwithstanding the pretensions of other nations, since it was


the Greeks who improved geometry, probably from its first
rudiments, into a noble and most useful science; and since we
cannot conceive that astronomy should make any considerable
progress without geometry, it is to them we appear indebted for the
foundations of a science, that (to speak without a metaphor) has in
latter ages reached the astonishingly distant heavens.

Amongst the Greeks, Hipparchus[A6] deserves particular notice; by


an improvement of whose labours Ptolemy formed that system of
astronomy which appears to have been the only one studied for
ages after, and particularly (as was said before) by the Arabians;
who made some improvements of their own, and, if not the
inventors, were at least the preservers of astronomy. For with them it
took refuge, during those ages of ignorance which involved Europe,
after an inundation of northern people had swallowed up the Roman
empire; where the universally prevailing corruption of manners, and
false taste, were become as unfavourable to the cause of science,
as the ravages of the Barbarians themselves.

From this time, we meet with little account of astronomical learning


in Europe[A7] until Regiomontanus,[A8] and some others, revived it in
the fifteenth century; and soon afterwards appeared the celebrated
Copernicus,[A9] whose vast genius, assisted by such lights as the
remains of antiquity afforded him, explained the true system of the
universe, as at present understood. To the objection of the
Aristotelians, that the sun could not be the centre of the world,
because all bodies tended to the earth, Copernicus replied, that
probably there was nothing peculiar to the earth in this respect; that
the parts of the sun, moon and stars, likewise tended to each other,
and that their spherical figure was preserved amidst their various
motions, by this power; an answer that will at this day be allowed to
contain sound philosophy. And when it was further objected to him,
that, according to his system, Venus and Mercury ought to appear
horned like the moon, in particular situations; he answered as if
inspired by the spirit of prophecy, and long before the invention of
telescopes, by which alone his prediction could be verified, “That so
they would one day be found to appear.”

Next follows the noble Tycho,[A10] who with great labour and
perseverance, brought the art of observing the heavens to a degree
of accuracy unknown to the ancients; though in theory he mangled
the beautiful system of Copernicus. The whimsical Kepler, too,
(whose fondness for analogies frequently led him astray, yet
sometimes happily conducted him to important truths) did notable
services to astronomy: and from his time down to the present, so
many great men have appeared amongst the several nations of
Europe, rivalling each other in the improvement of astronomy, that I
should trespass on your patience were I to enumerate them. I shall
therefore proceed to what I proposed in the second place, and take
notice of some of the most important discoveries in this science.

Astronomy, like the Christian religion, if you will allow me the


comparison, has a much greater influence on our knowledge in
general, and perhaps on our manners too, than is commonly
imagined. Though but few men are its particular votaries, yet the
light it affords is universally diffused amongst us; and it is difficult for
us to divest ourselves of its influence so far, as to frame any
competent idea of what would be our situation without it.[A11] Utterly
ignorant of the heavens, our curiosity would be confined solely to the
earth, which we should naturally suppose a vast extended plain; but
whether of infinite extent or bounded, and if bounded, in what
manner, would be questions admitting of a thousand conjectures,
and none of them at all satisfactory.

The first discovery then, which paved the way for others more
curious, seems to have been the circular figure of the earth, inferred
from observing the meridian altitudes of the sun and stars to be
different in distant places. This conclusion would probably not be
immediately drawn, but the appearance accounted for, by the
rectilinear motion of the traveller; and then a change in the apparent
situations of the heavenly bodies would only argue their nearness to
the earth: and thus would the observation contribute to establish
error, instead of promoting truth, which has been the misfortune of
many an experiment. It would require some skill in geometry, as well
as practice in observing angles, to demonstrate the spherical figure
of the earth from such observations.[A12]
But this difficulty being surmounted, and the true figure of the earth
discovered, a free space would now be granted for the sun, moon,
and stars to perform their diurnal motions on all sides of it; unless
perhaps at its extremities to the north and south; where something
would be thought necessary to serve as an axis for the heavens to
revolve on. This Mr. Crantz in his very entertaining history of
Greenland informs us, is agreeable to the philosophy of that country,
with this difference perhaps, that the high latitude of the Greenlander
makes him conclude one pole only, necessary: He therefore
supposes a vast mountain situate in the utmost extremity of
Greenland, whose pointed apex supports the canopy of heaven, and
whereon it revolves with but little friction.

A free space around the earth being granted, our infant


astronomer would be at liberty to consider the diurnal motions of the
stars as performed in intire circles, having one common axis of
rotation. And by considering their daily anticipation in rising and
setting, together with the sun’s annual rising and falling in its noon
day height, swiftest about the middle space, and stationary for some
time when highest and lowest, he would be led to explain the whole
by attributing a slow motion to the sun, contrary to the diurnal
motion, along a great circle dividing the heavens into two equal
parts, but obliquely situated with respect to the diurnal motion. By a
like attention to the moon’s progress the Zodiac would be formed,
and divided into its several constellations or other convenient
divisions.

The next step that astronomy advanced, I conceive, must have


been in the discovery attributed to Pythagoras;[A13] who it is said first
found out that Hesperus and Phosphorus, or the Evening and
Morning Star, were the same. The superior brightness of this planet,
and the swiftness of its motion, probably first attracted the notice of
the inquisitive: and one wandering star being discovered, more
would naturally be looked for. The splendor of Jupiter, the very
changeable appearance of Mars, and the glittering of Mercury by day
light, would distinguish them. And lastly, Saturn would be discovered
by a close attention to the heavens. But how often would the curious
eye be directed in vain, to the regions of the north and south, before
there was reason to conclude that the orbits of all the planets lay
nearly in the same plane; and that they had but narrow limits
assigned them in the visible heavens.

From a careful attendance to those newly discovered celestial


travellers, and their various motions, direct and retrograde, the great
discovery arose, that the sun is the centre of their motions; and that
by attributing a similar motion to the earth, and supposing the sun to
be at rest, all the phænomena will be solved. Hence a hint was taken
that opened a new and surprizing scene. The earth might be similar
to them in other respects. The planets too might be habitable worlds.
One cannot help greatly admiring the sagacity of minds, that first
formed conclusions so very far from being obvious; as well as the
indefatigable industry of astronomers, who originally framed rules for
predicting eclipses of sun and moon, which is said to have been
done as early as the time of Thales;[A14] and must have proved of
singular service to emancipate mankind from a thousand
superstitious fears and notions, which juggling impostors (the growth
of all ages and countries) would not fail to turn to their own
advantage.

For two or three centuries before and after the beginning of the
Christian era, astronomy appears to have been held in considerable
repute; yet very few discoveries of any consequence were made,
during that period and many ages following.

The ancients were not wanting in their endeavours to find out the
true dimensions of the planetary system. They invented several very
ingenious methods for the purpose; but none of them were at all
equal, in point of accuracy, to the difficulty of the problem. They were
therefore obliged to rest satisfied with supposing the heavenly
bodies much nearer to the earth than in fact they are, and
consequently much less in proportion to it. Add to this, that having
found the earth honoured with an attendant, while they could
discover none belonging to any of the other planets, they supposed it
of far greater importance in the Solar System than it appears to us to
be: And the more praise is due to those few, who nevertheless
conceived rightly of its relation to the whole.

Tycho took incredible pains to discover the parallax of Mars in


opposition; the very best thing he could have attempted in order to
determine the distances and magnitudes of the sun and planets. But
telescopes and micrometers were not yet invented! so that not being
able to conclude any thing satisfactory from his own observations, he
left the sun’s parallax as he found it settled by Ptolemy, about twenty
times too great. And even after he had reduced to rule the refraction
of the atmosphere, and applied it to astronomical observations,
rather than shock his imagination by increasing the sun’s distance,
already too great for his hypothesis, he chose to attribute a greater
refraction to the sun’s light, than that of the stars, altogether contrary
to reason; that so an excess of parallax might be balanced by an
excess of refraction. Thus when we willingly give room to one error,
we run the risk of having a whole troop of its relations quartered
upon us. But Kepler afterwards, on looking over Tycho’s
observations, found that he might safely reduce the sun’s parallax to
one minute; which was no inconsiderable approach to the truth.
Alhazen,[A15] an Arabian, had some time before, discovered the
refraction of light in passing through air; of which the ancients seem
to have been entirely ignorant. They were indeed very sensible of
the errors it occasioned in their celestial measures; but they, with
great modesty, attributed them to the imperfections of their
instruments or observations.

I must not omit, in honour of Tycho, to observe that he first proved,


by accurate observations, that the comets are not meteors floating in
our atmosphere, as Aristotle,[A16] that tyrant in Philosophy, had
determined them to be, but prodigious bodies at a vast distance from
us in the planetary regions; a discovery the lateness of which we
must regret, for if it had been made by the ancients, that part of
Astronomy (and perhaps every other, in consequence of the superior
attention paid to it), would have been in far greater perfection than it
is at this day.
I had almost forgot to take notice of one important discovery made
in the early times of Astronomy, the precession of the equinoxes. An
ancient astronomer, called Timocharis, observed an appulse of the
Moon to the Virgin’s Spike, about 280 years before the birth of
Christ. He thence took occasion to determine the place of this star,
as accurately as possible; probably with a view of perfecting the
lunar theory. About four hundred years afterwards, Ptolemy,
comparing the place of the same star, as he then found it, with its
situation determined by Timocharis,[A17] concluded the precession to
be at the rate of one degree in an hundred years; but later
astronomers have found it swifter.

Whatever other purposes this great law may answer, it will


produce an amazing change in the appearance of the heavens; and
so contribute to that endless variety which obtains throughout the
works of Nature. The seven stars that now adorn our winter skies,
will take their turn to shine in summer. Sirius, that now shines with
unrivalled lustre, amongst the gems of heaven, will sink below our
horizon, and rise no more for very many ages! Orion too, will
disappear, and no longer afford our posterity a glimpse of glories
beyond the skies! glittering Capella, that now passes to the north of
our zenith, will nearly describe the equator:[A18] And Lyra, one of the
brightest in the heavens, will become our Polar Star: Whilst the
present Pole Star, on account of its humble appearance, shall pass
unheeded; and all its long continued faithful services shall be
forgotten! All these changes, and many others, will certainly follow
from the precession of the equinoxes; the cause of which motion
was so happily discovered and demonstrated by the immortal
Newton: A portion of whose honors was nevertheless intercepted by
the prior sagacity of Kepler, to whom I return.

Kepler’s love of harmony encouraged him to continue his pursuits,


in spite of the most mortifying disappointments, until he discovered
that admirable relation which subsists between the periodic times of
the primary planets, and their distances from the sun; the squares of
the former being as the cubes of the latter. This discovery was of
great importance to the perfection of Astronomy; because the
periods of the planets are more easily found by observation, and
from them their several relative distances may be determined with
great accuracy by this rule. He likewise found from observation, that
the planets do not move in circles; but in elipses, having the sun in
one focus. But the causes lay hid from him, and it was left as the
glory of Sir Isaac, to demonstrate that both these things must
necessarily follow from one simple principle, which almost every
thing in this science tends to prove does really obtain in Nature: I
mean, that the planets are retained in their orbits by forces directed
to the sun; which forces decrease as the squares of their distances
encrease.

Kepler also discovered that the planets do not move equally in


their orbits, but sometimes swifter, sometimes slower; and that not
irregularly, but according to this certain rule; That in equal times, the
areas described by lines drawn from the planet to the sun’s centre,
are equal. This, Sir Isaac likewise demonstrated must follow, if the
planet be retained in its orbit by forces directed to the sun, and
varying with the distance in any manner whatsoever. These three
discoveries of Kepler, afterwards demonstrated by Newton, are the
foundation of all accuracy in astronomical calculations.[A19]

We now come to that great discovery, which lay concealed from


the most subtle and penetrating geniuses amongst mankind, until
these latter ages; which so prodigiously enlarged the fields of
astronomy, and with such rapidity handed down one curiosity after
another, from the heavens to astonished mortals, that no one
capable of raising his eyes and thoughts from the ground he trod on,
could forbear turning his attention, in some degree, to the subject
that engages us this evening.

Galileo, as he himself acknowledges, was not the first inventor of


the telescope, but he was the first that knew how to make a proper
use of it.[A20] If we consider that convex and concave lenses had
been in use for some centuries, we shall think it probable that
several persons might have chanced to combine them together, so
as to magnify distant objects; but that the small advantage
apparently resulting from such a discovery, either on account of the
badness of the glasses or the unskilfulness of the person in whose
hands they were, occasioned it to be neglected.

But Galileo, by great care in perfecting his telescope, and by


applying a judicious eye, happily succeeded; and with a telescope
magnifying but thirty times, discovered the moon to be a solid globe,
diversified with prodigious mountains and vallies, like our earth; but
without seas or atmosphere. The sun’s bright disk, he found
frequently shaded with spots, and by their apparent motions proved
it to be the surface of a globe, revolving on its axis in about five and
twenty days. This it seems was a mortifying discovery to the
followers of Aristotle; who held the sun to be perfect without spot or
blemish.[A21] Some of them, it is said, insisted that it was but an
illusion of the telescope and absolutely refused to look through one,
lest the testimony of their senses should prove too powerful for their
prejudices.

Galileo likewise discovered the four attendants of Jupiter,


commonly called his satellites:[A22] Which at first did not much please
that great ornament of his age, the sagacious Kepler. For by this
addition to the number of the planets, he found their Creator had not
paid that veneration to certain mystical numbers and proportions,
which he had imagined. Let us not blush at this remarkable instance
of philosophical weakness, but admire the candour of the man who
confessed it.

Galileo not only discovered these moons of Jupiter, but suggested


their use in determining the longitude of places on the earth; which
has since been so happily put in practice, that Fontenelle does not
hesitate to affirm, that they are of more use to Geography and
Navigation,[A23] than our own moon. He discovered the phases of
Mars and Venus; that the former appears sometimes round and
sometimes gibbous, and that the latter puts on the shapes of our
moon: And from this discovery, he proved to a demonstration, the
truth of the Copernican System.[A24] Nor did that wonderful ring,
which surrounds Saturn’s body, without touching it, and which we
know nothing in nature similar to, escape his notice; though his
telescope did not magnify sufficiently to give him a true idea of its
figure.

Amongst the fixed stars too, Galileo pursued his enquiries. The
Milky-Way, which had so greatly puzzled the ancient Philosophers,
and which Aristotle imagined to be vapours risen to an extraordinary
height, he found to consist of an innumerable multitude of small
stars; whose light appears indistinct and confounded together to the
naked eye. And in every part of the heavens, his telescope shewed
him abundance of stars, not visible without it. In short, with such
unabated ardour did this great man range through the fields of
Astronomy, that he seemed to leave nothing for others to glean after
him.

Nevertheless, by prodigiously encreasing the magnifying powers


of their telescopes, his followers made several great discoveries;
some of which I shall briefly mention. Mercury was found to become
bisected, and horned near its inferior conjunction, as well as Venus.
Spots were discovered in Mars, and from their apparent motion, the
time of his revolution on an axis nearly perpendicular to its orbit, was
determined. A sort of belts or girdles, of a variable or fluctuating
nature, were found to surround Jupiter, and likewise certain spots on
his surface, whence he was concluded to make one revolution in
about ten hours on his axis; which is likewise nearly perpendicular to
his orbit. Five[A25] moons or satellites were found to attend Saturn,
which Galileo’s telescope; on account of their prodigious distance,
could not reach:[A26] And the form of his ring was found to be a thin
circular plane, so situated as not to be far from parallel to the plane
of our equator; and always remaining parallel to itself. This ring, as
well as Saturn, evidently derives its light from the sun, as appears by
the shadows they mutually cast on each other.

Besides several other remarkable appearances, which


Hugenius[A27] discovered amongst the fixed stars, there is one in
Orion’s Sword, which, I will venture to say, whoever shall attentively
view, with a good telescope and experienced eye, will not find his
curiosity disappointed. “Seven small stars, (says he,) of which three
are very close together, seemed to shine through a cloud, so that a
space round them appeared much brighter than any other part of
heaven, which being very serene and black looked here as if there
was an opening, through which one had a prospect into a much
brighter region.” Here some have supposed old night to be entirely
dispossessed, and that perpetual daylight shines amongst
numberless worlds without interruption.

This is a short account of the discoveries made with the telescope.


Well might Hugenius congratulate the age he lived in, on such a
great acquisition of knowledge: And recollecting those great men,
Copernicus, Regiomontanus, and Tycho, so lately excluded from it
by death, what an immense treasure, says he, would they have
given for it. Those ancient philosophers too, Pythagoras,
Democritus, Anaxagoras, Philolaus, Plato, Hipparchus; would they
not have travelled over all the countries of the world, for the sake of
knowing such secrets of nature, and of enjoying such sights as
these?

Thus have we seen the materials collected, which were to


compose the magnificent edifice of astronomical Philosophy;
collected, indeed, with infinite labour and industry, by a few
volunteers in the service of human knowledge, and with an ardour
not to be abated by the weaknesses of human nature, or the
threatened loss of sight, one of the greatest of bodily misfortunes! It
was now time for the great master-builder to appear, who was to rear
up this whole splendid group of materials into due order and
proportion. And it was, I make no doubt, by a particular appointment
of Providence, that at this time the immortal Newton appeared. Much
had been done preparatory to this great work by others, without
which if he had succeeded, we should have been ready to
pronounce him something more than human. The doctrine of atoms
had been taught by some of the ancients. Kepler had suspected that
the planets gravitated towards each other, particularly the earth and
moon; and that their motion prevented their falling together: and
Galileo first of all applied geometrical reasoning to the motion of
projectiles. But the solid spheres of the ancients, or the vortices of
Des Cartes,[A28] were still found necessary to explain the planetary
motions; or if Kepler had discarded them, it was only to substitute
something else in their stead, by no means sufficient to account for
those grand movements of nature. It was Newton alone that
extended the simple principle of gravity, under certain just
regulations, and the laws of motion, whether rectilinear or circular,
which constantly take place on the surface of this globe, throughout
every part of the solar system; and from thence, by the assistance of
a sublime geometry, deduced the planetary motions, with the
strictest conformity to nature and observation.

Other systems of Philosophy have been spun out of the fertile


brain of some great genius or other; and for want of a foundation in
nature, have had their rise and fall, succeeding each other by turns.
But this will be durable as science, and can never sink into neglect,
until “universal darkness buries all.”

Other systems of Philosophy have ever found it necessary to


conceal their weakness, and inconsistency, under the veil of
unintelligible terms[A29] and phrases, to which no two mortals perhaps
ever affixed the same meaning: But the Philosophy of Newton
disdains to make use of such subterfuges; it is not reduced to the
necessity of using them, because it pretends not to be of nature’s
privy council, or to have free access to her most inscrutable
mysteries; but to attend carefully to her works, to discover the
immediate causes of visible effects, to trace those causes to others
more general and simple, advancing by slow and sure steps towards
the great First Cause of all things.

And now the Astronomy of our planetary system seemed


compleated. The telescope had discovered all the globes whereof it
is composed, at least as far as we yet know. Newton with more than
mortal sagacity had discovered those laws by which all their various,
yet regular, motions are governed, and reduced them to the most
beautiful simplicity: laws to which not only their great and obvious
variety of motions are conformable, but even their minute
irregularities; and not only planets but comets likewise. The busy
mind of man, never satiated with knowledge, now extended its views
further, and made use of every expedient that suggested itself, to
find the relation that this system of worlds bears to the whole visible
creation. Instruments were made with all possible accuracy, and the
most skilful observers applied themselves with great diligence to
discover an annual parallax, from which the distances of the fixed
stars would be known. They found unexpected irregularities, and
might have been long perplexed with them to little purpose, had not
Dr. Bradley happily accounted for them, by shewing that light from
the heavenly bodies strikes the eye with a velocity and direction,
compounded of the proper velocity and direction of light, and of the
eye, as carried about with the earth in its orbit; compared to which,
the diurnal motion and all other accidental motions of the eye, are
quite inconsiderable. Thus, instead of what he aimed at, he
discovered something still more curious, the real velocity of light, in a
way entirely new and unthought of.

All Astronomical knowledge being conveyed to us from the


remotest distances, by that subtle, swift and universal messenger of
intelligence, Light; it was natural for the curious to enquire into its
properties, and particularly to endeavour to know with what velocity it
proceeds, in its immeasurable journeys. Experimental Philosophy,
accustomed to conquer every difficulty, undertook the arduous
problem; but confessed herself unequal to the task.[A30] Here,
Astronomy itself revealed the secret; first in the discovery of Roemer,
who found that the farther Jupiter is distant from us, the later the light
of his satellites always reaches us; and afterwards in this of Dr.
Bradley, informed us, that light proceeds from the sun to us in about
eight minutes of time.[A31]

As the apparent motion of the fixed stars, arising from this cause,
was observed to complete the intire circle of its changes in the space
of a year, it was for some time supposed to arise from an annual
parallax, notwithstanding its inconsistency in other respects with
such a supposition. But this obstacle being removed, there followed
the discovery of another apparent motion in the heavens, arising
from the nutation of the earth’s axis; the period whereof is about
nineteen years. Had it not been so very different from the period of
the former, the causes of both must have been almost inexplicable.
This latter discovery is an instance of the superior advantages of
accurate observation: For it was well known that such a nutation
must take place from the principles of the Newtonian Philosophy; yet
a celebrated astronomer had concluded from hypothetical reasoning,
that its quantity must be perfectly insensible.

The way being cleared thus far, Dr. Bradley assures us, from his
most accurate observations, that the annual parallax cannot exceed
two seconds, he thinks not one; and we have the best reason to
confide in his judgment and accuracy. From hence then we draw this
amazing conclusion; that the diameter of the earth’s orb bears no
greater proportion to the distance of the stars which Bradley
observed, than one second does to the radius; which is less than as
one to 200,000. Prodigiously great as the distance of the fixed stars
from our sun appears to be, and probably their distances from each
other are no less, the Newtonian Philosophy will furnish us with a
reason for it: That the several systems may be sufficiently removed
from each other’s attraction, which we are very certain must require
an immense distance; especially if we consider that the cometic part,
of our system at least, appears to be the most considerable though
so little known to us. The dimensions of the several parts of the
planetary system, had been determined near the truth by the
astronomers of the last age, from the parallax of Mars. But from that
rare phenomenon the transit of Venus over the sun’s disk, which has
twice happened within a few years past, the sun’s parallax is now
known beyond dispute to be 8 seconds and an half, nearly; and
consequently, the sun’s distance almost 12,000 diameters of the
earth.

If from the distances of the several planets, and their apparent


diameters taken with that excellent instrument, the micrometer, we
compare their several magnitudes, we shall find the Moon, Mercury,
and Mars, to be much less than our Earth, Venus a little less, but
Saturn many hundred times greater, and Jupiter above one thousand
times. This prodigious globe, placed at such a vast distance from the
other planets, that the force of its attraction might the less disturb
their motions, is far more bulky and ponderous than all the other
planets taken together. But even Jupiter, with all his fellows of our
system, are as nothing compared to that amazing mass of matter the
Sun. How much are we then indebted to Astronomy, for correcting
our ideas of the visible creation! Wanting its instruction, we should
infallibly have supposed the earth by far the most important body in
the universe, both for magnitude and use. The sun and moon would
have been thought two little bodies nearly equal in size, though
different in lustre, created solely for the purpose of enlightening the
earth; and the fixed stars, so many sparks of fire, placed in the
concave vault of heaven, to adorn it, and afford us a glimmering light
in the absence of the sun and moon.

But how does Astronomy change the scene!—Take the miser from
the earth, if it be possible to disengage him; he whose nightly rest
has been long broken by the loss of a single foot of it, useless
perhaps to him; and remove him to the planet Mars, one of the least
distant from us: Persuade the ambitious monarch to accompany him,
who has sacrificed the lives of thousands of his subjects to an
imaginary property in certain small portions of the earth; and now
point it out to them, with all its kingdoms and wealth, a glittering star
“close by the moon,” the latter scarce visible and the former less
bright than our Evening Star:—Would they not turn away their
disgusted sight from it, as not thinking it worth their smallest
attention, and look for consolation in the gloomy regions of Mars?[A32]

But dropping the company of all those, whether kings or misers,


whose minds and bodies are equally affected by gravitation, let us
proceed to the orb of Jupiter; the Earth and all the inferior planets will
vanish, lost in the sun’s bright rays, and Saturn only remain; He too
sometimes so diminished in lustre, as not to be easily discovered.
But a new and beautiful system will arise. The four moons of Jupiter
will become very conspicuous; some of them perhaps appearing
larger, others smaller than our moon; and all of them performing their
revolutions with incredible swiftness, and the most beautiful

You might also like