100% found this document useful (5 votes)
126 views

Full Pro C# 8 With .NET Core 3: Foundational Principles and Practices in Programming - Ninth Edition Andrew Troelsen Ebook All Chapters

Principles

Uploaded by

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

Full Pro C# 8 With .NET Core 3: Foundational Principles and Practices in Programming - Ninth Edition Andrew Troelsen Ebook All Chapters

Principles

Uploaded by

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

Download the full version of the textbook now at textbookfull.

com

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/

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


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

Pro C 9 with NET 5 Foundational Principles and Practices


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

Pro C 9 with NET 5 Foundational Principles and Practices


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

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

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

textbookfull.com

The Data Industry The Business and Economics of


Information and Big Data 1st Edition Chunlei Tang

https://textbookfull.com/product/the-data-industry-the-business-and-
economics-of-information-and-big-data-1st-edition-chunlei-tang/

textbookfull.com
Body and Text Cultural Transformations in New Media
Environments David Callahan

https://textbookfull.com/product/body-and-text-cultural-
transformations-in-new-media-environments-david-callahan/

textbookfull.com

Heterogeneous Reconfigurable Processors for Real Time


Baseband Processing From Algorithm to Architecture 1st
Edition Chenxin Zhang
https://textbookfull.com/product/heterogeneous-reconfigurable-
processors-for-real-time-baseband-processing-from-algorithm-to-
architecture-1st-edition-chenxin-zhang/
textbookfull.com

The Best Next Thing ((Un)Professionally Yours #1) 1st


Edition Natasha Anders

https://textbookfull.com/product/the-best-next-thing-unprofessionally-
yours-1-1st-edition-natasha-anders/

textbookfull.com

Absolute Dermatology Review: Mastering Clinical Conditions


on the Dermatology Recertification Exam 1st Edition Hugh
Morris Gloster
https://textbookfull.com/product/absolute-dermatology-review-
mastering-clinical-conditions-on-the-dermatology-recertification-
exam-1st-edition-hugh-morris-gloster/
textbookfull.com

Rough Ride Men of Valor MC Book 1 1st Edition Mila


Crawford & Aria Cole [Crawford

https://textbookfull.com/product/rough-ride-men-of-valor-mc-
book-1-1st-edition-mila-crawford-aria-cole-crawford/

textbookfull.com
Wireless Computing in Medicine From Nano to Cloud with
Ethical and Legal Implications 1st Edition Mary Mehrnoosh
Eshaghian-Wilner
https://textbookfull.com/product/wireless-computing-in-medicine-from-
nano-to-cloud-with-ethical-and-legal-implications-1st-edition-mary-
mehrnoosh-eshaghian-wilner/
textbookfull.com
Pro C# 8 with
.NET Core 3
Foundational Principles and Practices
in Programming

Ninth Edition

Andrew Troelsen
Phil Japikse
Pro C# 8 with .NET
Core 3
Foundational Principles and Practices
in Programming

Ninth Edition

Andrew Troelsen
Phil Japikse
Pro C# 8 with .NET Core 3: Foundational Principles and Practices in Programming
Andrew Troelsen Phil Japikse
Minneapolis, MN, USA West Chester, OH, USA

ISBN-13 (pbk): 978-1-4842-5755-5 ISBN-13 (electronic): 978-1-4842-5756-2


https://doi.org/10.1007/978-1-4842-5756-2

Copyright © 2020 by Andrew Troelsen and Phil 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.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Joan Murray
Development Editor: Laura Berendson
Coordinating Editor: Jill Balzano
Cover image designed by Freepik (www.freepik.com)
Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street,
6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-
sbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member
(owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a
Delaware corporation.
For information on translations, please e-mail [email protected]; for reprint,
paperback, or audio rights, please e-mail [email protected].
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 http://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/9781484257555. For more
detailed information, please visit http://www.apress.com/source-code.
Printed on acid-free paper
To my family, Amy (wife), Conner (son), Logan (son), and Skylar (daughter),
thank you for all of the support and patience you have given me. Also, to my father (Cor);
father, husband, inventor, and my center of excellence.

—Phil
Table of Contents

About the Authors���������������������������������������������������������������������������������������������������xlv


About the Technical Reviewer������������������������������������������������������������������������������xlvii
Acknowledgments�������������������������������������������������������������������������������������������������xlix
Introduction�������������������������������������������������������������������������������������������������������������� li


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

■Chapter 1: Introducing .NET Core�������������������������������������������������������������������������� 3
Some Key Benefits of the .NET Core Platform������������������������������������������������������������������ 4
The .NET Core Support Lifecycle�������������������������������������������������������������������������������������� 4
Introducing the Building Blocks of the .NET Core Platform
(CoreCLR, CoreFX, CTS, and CLS)������������������������������������������������������������������������������������� 5
The Role of the Base Class Libraries������������������������������������������������������������������������������������������������������ 6
What C# Brings to the Table������������������������������������������������������������������������������������������������������������������� 6
Managed vs. Unmanaged Code������������������������������������������������������������������������������������������������������������ 10

Additional .NET Core Aware Programming Languages��������������������������������������������������� 10


An Overview of .NET Assemblies������������������������������������������������������������������������������������ 10
The Role of the Common Intermediate Language�������������������������������������������������������������������������������� 11
Benefits of CIL�������������������������������������������������������������������������������������������������������������������������������������� 14
Compiling CIL to Platform-Specific Instructions����������������������������������������������������������������������������������� 14
The Role of .NET Core Type Metadata��������������������������������������������������������������������������������������������������� 15
The Role of the Assembly Manifest������������������������������������������������������������������������������������������������������ 15
Understanding the Common Type System���������������������������������������������������������������������� 16
CTS Class Types������������������������������������������������������������������������������������������������������������������������������������ 16
CTS Interface Types������������������������������������������������������������������������������������������������������������������������������ 17
■ Table of Contents

CTS Structure Types����������������������������������������������������������������������������������������������������������������������������� 18


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

Understanding the Common Language Specification���������������������������������������������������� 20


Ensuring CLS Compliance��������������������������������������������������������������������������������������������������������������������� 22

Understanding the CoreCLR and CoreFX������������������������������������������������������������������������ 22


The Assembly/Namespace/Type Distinction������������������������������������������������������������������ 23
Accessing a Namespace Programmatically����������������������������������������������������������������������������������������� 24
Referencing External Assemblies��������������������������������������������������������������������������������������������������������� 25

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


Summary������������������������������������������������������������������������������������������������������������������������ 26

■Chapter 2: Building C# Applications�������������������������������������������������������������������� 27
Installing .NET Core�������������������������������������������������������������������������������������������������������� 27
Confirm the .NET Core Install���������������������������������������������������������������������������������������������������������������� 28

Building .NET Core Applications with Visual Studio�������������������������������������������������������� 28


Installing Visual Studio 2019���������������������������������������������������������������������������������������������������������������� 29
Taking Visual Studio 2019 for a Test-Drive������������������������������������������������������������������������������������������� 30
The .NET Framework Documentation��������������������������������������������������������������������������������������������������� 40
Building .NET Core Applications on a Non-Windows OS������������������������������������������������ 41
Summary������������������������������������������������������������������������������������������������������������������������ 41

■Part II: Core C# Programming����������������������������������������������������������� 43

■Chapter 3: Core C# Programming Constructs, Part 1������������������������������������������ 45
The Anatomy of a Simple C# Program���������������������������������������������������������������������������� 45
Variations on the Main() Method (Updated 7.1)������������������������������������������������������������������������������������ 47
Specifying an Application Error Code��������������������������������������������������������������������������������������������������� 48
Processing Command-Line Arguments������������������������������������������������������������������������������������������������ 49
Specifying Command-Line Arguments with Visual Studio�������������������������������������������������������������������� 51

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


vi
■ Table of Contents

The System.Console Class��������������������������������������������������������������������������������������������� 53


Basic Input and Output with the Console Class������������������������������������������������������������������������������������ 54
Formatting Console Output������������������������������������������������������������������������������������������������������������������� 55
Formatting Numerical Data������������������������������������������������������������������������������������������������������������������ 55
Formatting Numerical Data Beyond Console Applications������������������������������������������������������������������� 57

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


Variable Declaration and Initialization�������������������������������������������������������������������������������������������������� 58
Intrinsic Data Types and the new Operator������������������������������������������������������������������������������������������� 60
The Data Type Class Hierarchy������������������������������������������������������������������������������������������������������������� 61
Members of Numerical Data Types������������������������������������������������������������������������������������������������������� 62
Members of System.Boolean���������������������������������������������������������������������������������������������������������������� 63
Members of System.Char��������������������������������������������������������������������������������������������������������������������� 63
Parsing Values from String Data����������������������������������������������������������������������������������������������������������� 64
Using TryParse to Parse Values from String Data��������������������������������������������������������������������������������� 64
System.DateTime and System.TimeSpan��������������������������������������������������������������������������������������������� 65
The System.Numerics Namespace������������������������������������������������������������������������������������������������������� 66
Digit Separators (New 7.0)������������������������������������������������������������������������������������������������������������������� 67
Binary Literals (New 7.0/7.2)���������������������������������������������������������������������������������������������������������������� 67

Working with String Data����������������������������������������������������������������������������������������������� 68


Basic String Manipulation�������������������������������������������������������������������������������������������������������������������� 68
String Concatenation���������������������������������������������������������������������������������������������������������������������������� 69
Escape Characters�������������������������������������������������������������������������������������������������������������������������������� 70
String Interpolation������������������������������������������������������������������������������������������������������������������������������� 71
Defining Verbatim Strings (Updated 8)������������������������������������������������������������������������������������������������� 72
Strings and Equality����������������������������������������������������������������������������������������������������������������������������� 72
Strings Are Immutable�������������������������������������������������������������������������������������������������������������������������� 75
The System.Text.StringBuilder Type����������������������������������������������������������������������������������������������������� 76

Narrowing and Widening Data Type Conversions����������������������������������������������������������� 77


The checked Keyword�������������������������������������������������������������������������������������������������������������������������� 80
Setting Project-Wide Overflow Checking���������������������������������������������������������������������������������������������� 81
The unchecked Keyword���������������������������������������������������������������������������������������������������������������������� 82

vii
■ Table of Contents

Understanding Implicitly Typed Local Variables������������������������������������������������������������� 83


Declaring Numerics Implicitly��������������������������������������������������������������������������������������������������������������� 84
Restrictions on Implicitly Typed Variables�������������������������������������������������������������������������������������������� 85
Implicit Typed Data Is Strongly Typed Data������������������������������������������������������������������������������������������� 86
Usefulness of Implicitly Typed Local Variables������������������������������������������������������������������������������������� 86

C# Iteration Constructs��������������������������������������������������������������������������������������������������� 87
The for Loop������������������������������������������������������������������������������������������������������������������������������������������ 88
The foreach Loop���������������������������������������������������������������������������������������������������������������������������������� 88
Use of Implicit Typing Within foreach Constructs��������������������������������������������������������������������������������� 89
The while and do/while Looping Constructs���������������������������������������������������������������������������������������� 89

A Quick Discussion About Scope������������������������������������������������������������������������������������ 90


Decision Constructs and the Relational/Equality Operators������������������������������������������� 91
The if/else Statement��������������������������������������������������������������������������������������������������������������������������� 91
Equality and Relational Operators�������������������������������������������������������������������������������������������������������� 91
if/else with Pattern Matching (New 7.0)����������������������������������������������������������������������������������������������� 92
The Conditional Operator (Updated 7.2)����������������������������������������������������������������������������������������������� 93
Logical Operators��������������������������������������������������������������������������������������������������������������������������������� 94
The switch Statement��������������������������������������������������������������������������������������������������������������������������� 94
Switch Statement Pattern Matching (New 7.0)������������������������������������������������������������������������������������ 97
Switch Expressions (New 8.0)������������������������������������������������������������������������������������������������������������ 100

Summary���������������������������������������������������������������������������������������������������������������������� 101

■Chapter 4: Core C# Programming Constructs, Part 2���������������������������������������� 103
Understanding C# Arrays���������������������������������������������������������������������������������������������� 103
C# Array Initialization Syntax�������������������������������������������������������������������������������������������������������������� 104
Implicitly Typed Local Arrays�������������������������������������������������������������������������������������������������������������� 105
Defining an Array of Objects��������������������������������������������������������������������������������������������������������������� 106
Working with Multidimensional Arrays����������������������������������������������������������������������������������������������� 107
Arrays As Arguments or Return Values����������������������������������������������������������������������������������������������� 108
The System.Array Base Class������������������������������������������������������������������������������������������������������������� 109
Indices and Ranges (New 8.0)������������������������������������������������������������������������������������������������������������ 111

viii
■ Table of Contents

Methods����������������������������������������������������������������������������������������������������������������������� 112
Expression-Bodied Members�������������������������������������������������������������������������������������������������������������� 113
Local Functions (New 7.0)������������������������������������������������������������������������������������������������������������������ 113
Static Local Functions (New 8.0)�������������������������������������������������������������������������������������������������������� 114

Method Parameters������������������������������������������������������������������������������������������������������ 115


Method Parameter Modifiers�������������������������������������������������������������������������������������������������������������� 115
The Default Parameter-Passing Behavior������������������������������������������������������������������������������������������� 116
The out Modifier (Updated 7.0)����������������������������������������������������������������������������������������������������������� 117
The ref Modifier���������������������������������������������������������������������������������������������������������������������������������� 119
The in Modifier (New 7.2)������������������������������������������������������������������������������������������������������������������� 120
The params Modifier�������������������������������������������������������������������������������������������������������������������������� 121
Defining Optional Parameters������������������������������������������������������������������������������������������������������������� 122
Using Named Arguments (Updated 7.2)���������������������������������������������������������������������������������������������� 123
Understanding Method Overloading��������������������������������������������������������������������������������������������������� 125

Understanding the enum Type�������������������������������������������������������������������������������������� 128


Controlling the Underlying Storage for an enum�������������������������������������������������������������������������������� 129
Declaring enum Variables������������������������������������������������������������������������������������������������������������������� 130
The System.Enum Type���������������������������������������������������������������������������������������������������������������������� 131
Dynamically Discovering an enum’s Name-Value Pairs��������������������������������������������������������������������� 131

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


Creating Structure Variables��������������������������������������������������������������������������������������������������������������� 135
Readonly Structs (New 7.2)���������������������������������������������������������������������������������������������������������������� 136
Readonly members (New 8.0)������������������������������������������������������������������������������������������������������������ 137
ref Structs (New 7.2)�������������������������������������������������������������������������������������������������������������������������� 137
Disposable ref Structs (New 8.0)�������������������������������������������������������������������������������������������������������� 138

Understanding Value Types and Reference Types�������������������������������������������������������� 139


Value Types, Reference Types, and the Assignment Operator������������������������������������������������������������ 140
Value Types Containing Reference Types�������������������������������������������������������������������������������������������� 141
Passing Reference Types by Value������������������������������������������������������������������������������������������������������ 143
Passing Reference Types by Reference���������������������������������������������������������������������������������������������� 144
Final Details Regarding Value Types and Reference Types����������������������������������������������������������������� 145

ix
■ Table of Contents

Understanding C# Nullable Types��������������������������������������������������������������������������������� 146


Nullable Value Types��������������������������������������������������������������������������������������������������������������������������� 147
Nullable Reference Types (New 8.0)��������������������������������������������������������������������������������������������������� 148
The Null-Coalescing Operator������������������������������������������������������������������������������������������������������������� 151
The Null-Coalescing Assignment Operator (New 8.0)������������������������������������������������������������������������� 152
The Null Conditional Operator������������������������������������������������������������������������������������������������������������� 152

Tuples (New/Updated 7.0)�������������������������������������������������������������������������������������������� 153


Getting Started with Tuples���������������������������������������������������������������������������������������������������������������� 153
Inferred Variable Names (Updated 7.1)����������������������������������������������������������������������������������������������� 154
Tuple Equality/Inequality (New 7.3)���������������������������������������������������������������������������������������������������� 154
Tuples As Method Return Values�������������������������������������������������������������������������������������������������������� 155
Discards with Tuples��������������������������������������������������������������������������������������������������������������������������� 156
Tuple Pattern Matching Switch Expressions (New 8.0)���������������������������������������������������������������������� 156
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������������������������������������������������������������������������������������������������������ 168

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


Chaining Constructor Calls Using this������������������������������������������������������������������������������������������������ 171
Observing Constructor Flow��������������������������������������������������������������������������������������������������������������� 173
Revisiting Optional Arguments����������������������������������������������������������������������������������������������������������� 175

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


Defining Static Field Data������������������������������������������������������������������������������������������������������������������� 177
Defining Static Methods��������������������������������������������������������������������������������������������������������������������� 178

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

Defining Static Constructors��������������������������������������������������������������������������������������������������������������� 180


Defining Static Classes����������������������������������������������������������������������������������������������������������������������� 182
Importing Static Members via the C# using Keyword������������������������������������������������������������������������ 183

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


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

C# Access Modifiers (Updated 7.2)������������������������������������������������������������������������������ 188


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

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


Encapsulation Using Traditional Accessors and Mutators������������������������������������������������������������������ 191
Encapsulation Using Properties���������������������������������������������������������������������������������������������������������� 193
Using Properties Within a Class Definition����������������������������������������������������������������������������������������� 197
Read-Only and Write-Only Properties������������������������������������������������������������������������������������������������� 198
Mixing Private and Public Get/Set Methods on Properties����������������������������������������������������������������� 199
Pattern Matching with Property Patterns (New 8.0)��������������������������������������������������������������������������� 199
Revisiting the static Keyword: Defining Static Properties������������������������������������������������������������������ 201

Understanding Automatic Properties���������������������������������������������������������������������������� 201


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

Understanding Object Initialization Syntax������������������������������������������������������������������� 206


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

Working with Constant Field Data�������������������������������������������������������������������������������� 210


Understanding Read-Only Fields�������������������������������������������������������������������������������������������������������� 211
Static Read-Only Fields���������������������������������������������������������������������������������������������������������������������� 212

Understanding Partial Classes������������������������������������������������������������������������������������� 213


Use Cases for Partial Classes?����������������������������������������������������������������������������������������������������������� 214

Summary���������������������������������������������������������������������������������������������������������������������� 214

xi
■ Table of Contents


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

Revisiting Visual Studio Class Diagrams���������������������������������������������������������������������� 219


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

Programming for Containment/Delegation������������������������������������������������������������������� 226


Understanding Nested Type Definitions���������������������������������������������������������������������������������������������� 228

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


The virtual and override Keywords����������������������������������������������������������������������������������������������������� 231
Overriding Virtual Members Using the Visual Studio IDE�������������������������������������������������������������������� 233
Sealing Virtual Members�������������������������������������������������������������������������������������������������������������������� 233
Understanding Abstract Classes��������������������������������������������������������������������������������������������������������� 234
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 7.0)������������������������������������������������������������������������������������������������������� 244
Pattern Matching Revisited (New 7.0)������������������������������������������������������������������������������������������������ 246

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


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

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

xii
■ Table of Contents


■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

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


Throwing a General Exception������������������������������������������������������������������������������������������������������������ 261
Catching Exceptions��������������������������������������������������������������������������������������������������������������������������� 262
Throw As Expression (New 7.0)���������������������������������������������������������������������������������������������������������� 264

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)�������������������������������������� 269
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������������������������������������������������������������������������������������������������������������������ 275
Rethrowing Exceptions����������������������������������������������������������������������������������������������������������������������� 276
Inner Exceptions��������������������������������������������������������������������������������������������������������������������������������� 276
The finally Block��������������������������������������������������������������������������������������������������������������������������������� 278
Exception Filters��������������������������������������������������������������������������������������������������������������������������������� 278

Debugging Unhandled Exceptions Using Visual Studio������������������������������������������������ 279


Summary���������������������������������������������������������������������������������������������������������������������� 280

xiii
■ Table of Contents


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

Defining Custom Interfaces������������������������������������������������������������������������������������������ 285


Implementing an Interface������������������������������������������������������������������������������������������� 287
Invoking Interface Members at the Object Level���������������������������������������������������������� 289
Obtaining Interface References: The as Keyword������������������������������������������������������������������������������� 290
Obtaining Interface References: The is Keyword (Updated 7.0)��������������������������������������������������������� 290

Default Implementations (New 8.0)������������������������������������������������������������������������������ 291


Static Constructors and Members (New 8.0)��������������������������������������������������������������� 292
Interfaces As Parameters��������������������������������������������������������������������������������������������� 292
Interfaces As Return Values����������������������������������������������������������������������������������������� 294
Arrays of Interface Types���������������������������������������������������������������������������������������������� 295
Implementing Interfaces Using Visual Studio��������������������������������������������������������������� 296
Explicit Interface Implementation�������������������������������������������������������������������������������� 298
Designing Interface Hierarchies����������������������������������������������������������������������������������� 300
Interface Hierarchies with Default Implementations (New 8.0)���������������������������������������������������������� 302
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���������������������������������������������������������������������������������������������� 312


A More Elaborate Cloning Example���������������������������������������������������������������������������������������������������� 314

The IComparable Interface������������������������������������������������������������������������������������������� 317


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

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

xiv
■ Table of Contents


■Chapter 9: Understanding Object Lifetime��������������������������������������������������������� 323
Classes, Objects, and References�������������������������������������������������������������������������������� 323
The Basics of Object Lifetime��������������������������������������������������������������������������������������� 325
The CIL of new������������������������������������������������������������������������������������������������������������������������������������ 325
Setting Object References to null������������������������������������������������������������������������������������������������������� 327

Determining If an Object Is Live����������������������������������������������������������������������������������� 328


Understanding Object Generations������������������������������������������������������������������������������� 329
Ephemeral Generations and Segments���������������������������������������������������������������������������������������������� 330

Garbage Collection Types��������������������������������������������������������������������������������������������� 331


Background Garbage Collection��������������������������������������������������������������������������������������������������������� 331

The System.GC Type����������������������������������������������������������������������������������������������������� 332


Forcing a Garbage Collection�������������������������������������������������������������������������������������������������������������� 333

Building Finalizable Objects����������������������������������������������������������������������������������������� 336


Overriding System.Object.Finalize()���������������������������������������������������������������������������������������������������� 337
Detailing the Finalization Process������������������������������������������������������������������������������������������������������ 339

Building Disposable Objects����������������������������������������������������������������������������������������� 339


Reusing the C# using Keyword����������������������������������������������������������������������������������������������������������� 341
Using Declarations (New 8.0)������������������������������������������������������������������������������������������������������������� 343

Building Finalizable and Disposable Types������������������������������������������������������������������� 344


A Formalized Disposal Pattern����������������������������������������������������������������������������������������������������������� 345

Understanding Lazy Object Instantiation���������������������������������������������������������������������� 347


Customizing the Creation of the Lazy Data����������������������������������������������������������������������������������������� 349

Summary���������������������������������������������������������������������������������������������������������������������� 350


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

■Chapter 10: Collections and Generics���������������������������������������������������������������� 353
The Motivation for Collection Classes�������������������������������������������������������������������������� 353
The System.Collections Namespace�������������������������������������������������������������������������������������������������� 355
A Survey of System.Collections.Specialized Namespace������������������������������������������������������������������� 357

xv
■ Table of Contents

The Problems of Nongeneric Collections��������������������������������������������������������������������� 358


The Issue of Performance������������������������������������������������������������������������������������������������������������������� 358
The Issue of Type Safety��������������������������������������������������������������������������������������������������������������������� 361
A First Look at Generic Collections����������������������������������������������������������������������������������������������������� 364

The Role of Generic Type Parameters�������������������������������������������������������������������������� 365


Specifying Type Parameters for Generic Classes/Structures������������������������������������������������������������� 366
Specifying Type Parameters for Generic Members����������������������������������������������������������������������������� 368
Specifying Type Parameters for Generic Interfaces���������������������������������������������������������������������������� 368

The System.Collections.Generic Namespace��������������������������������������������������������������� 369


Understanding Collection Initialization Syntax����������������������������������������������������������������������������������� 371
Working with the List<T> Class��������������������������������������������������������������������������������������������������������� 372
Working with the Stack<T> Class������������������������������������������������������������������������������������������������������ 374
Working with the Queue<T> Class����������������������������������������������������������������������������������������������������� 375
Working with the SortedSet<T> Class����������������������������������������������������������������������������������������������� 376
Working with the Dictionary<TKey, TValue> Class����������������������������������������������������������������������������� 377

The System.Collections.ObjectModel Namespace������������������������������������������������������� 378


Working with ObservableCollection<T>��������������������������������������������������������������������������������������������� 379

Creating Custom Generic Methods������������������������������������������������������������������������������� 381


Inference of Type Parameters������������������������������������������������������������������������������������������������������������� 383

Creating Custom Generic Structures and Classes�������������������������������������������������������� 384


Default Value Expressions with Generics������������������������������������������������������������������������������������������� 385
Default Literal Expressions (New 7.1)������������������������������������������������������������������������������������������������� 386
Pattern Matching with Generics (New 7.1)����������������������������������������������������������������������������������������� 387

Constraining Type Parameters�������������������������������������������������������������������������������������� 387


Examples Using the where Keyword�������������������������������������������������������������������������������������������������� 388
The Lack of Operator Constraints������������������������������������������������������������������������������������������������������� 389

Summary���������������������������������������������������������������������������������������������������������������������� 390

■Chapter 11: Advanced C# Language Features��������������������������������������������������� 391
Understanding Indexer Methods���������������������������������������������������������������������������������� 391
Indexing Data Using String Values������������������������������������������������������������������������������������������������������ 393
Overloading Indexer Methods������������������������������������������������������������������������������������������������������������� 394
xvi
■ Table of Contents

Indexers with Multiple Dimensions���������������������������������������������������������������������������������������������������� 395


Indexer Definitions on Interface Types������������������������������������������������������������������������������������������������ 396

Understanding Operator Overloading��������������������������������������������������������������������������� 396


Overloading Binary Operators������������������������������������������������������������������������������������������������������������� 397
And What of the += and –= Operators?��������������������������������������������������������������������������������������������� 399
Overloading Unary Operators������������������������������������������������������������������������������������������������������������� 400
Overloading Equality Operators���������������������������������������������������������������������������������������������������������� 401
Overloading Comparison Operators���������������������������������������������������������������������������������������������������� 402
Final Thoughts Regarding Operator Overloading�������������������������������������������������������������������������������� 403

Understanding Custom Type Conversions�������������������������������������������������������������������� 403


Recall: Numerical Conversions����������������������������������������������������������������������������������������������������������� 403
Recall: Conversions Among Related Class Types�������������������������������������������������������������������������������� 403
Creating Custom Conversion Routines����������������������������������������������������������������������������������������������� 404
Additional Explicit Conversions for the Square Type�������������������������������������������������������������������������� 407
Defining Implicit Conversion Routines������������������������������������������������������������������������������������������������ 408

Understanding Extension Methods������������������������������������������������������������������������������� 409


Defining Extension Methods��������������������������������������������������������������������������������������������������������������� 409
Invoking Extension Methods��������������������������������������������������������������������������������������������������������������� 411
Importing Extension Methods������������������������������������������������������������������������������������������������������������� 411
Extending Types Implementing Specific Interfaces���������������������������������������������������������������������������� 412

Understanding Anonymous Types�������������������������������������������������������������������������������� 413


Defining an Anonymous Type�������������������������������������������������������������������������������������������������������������� 414
The Internal Representation of Anonymous Types������������������������������������������������������������������������������ 415
The Implementation of ToString() and GetHashCode()������������������������������������������������������������������������ 416
The Semantics of Equality for Anonymous Types������������������������������������������������������������������������������� 417
Anonymous Types Containing Anonymous Types������������������������������������������������������������������������������� 419

Working with Pointer Types������������������������������������������������������������������������������������������ 419


The unsafe Keyword��������������������������������������������������������������������������������������������������������������������������� 421
Working with the * and & Operators��������������������������������������������������������������������������������������������������� 423
An Unsafe (and Safe) Swap Function������������������������������������������������������������������������������������������������� 424
Field Access via Pointers (the -> Operator)���������������������������������������������������������������������������������������� 425

xvii
■ Table of Contents

The stackalloc Keyword���������������������������������������������������������������������������������������������������������������������� 425


Pinning a Type via the fixed Keyword������������������������������������������������������������������������������������������������� 426
The sizeof Keyword���������������������������������������������������������������������������������������������������������������������������� 427

Summary���������������������������������������������������������������������������������������������������������������������� 427

■Chapter 12: Delegates, Events, and Lambda Expressions��������������������������������� 429
Understanding the Delegate Type��������������������������������������������������������������������������������� 430
Defining a Delegate Type in C#����������������������������������������������������������������������������������������������������������� 430
The System.MulticastDelegate and System.Delegate Base Classes�������������������������������������������������� 432

The Simplest Possible Delegate Example�������������������������������������������������������������������� 434


Investigating a Delegate Object���������������������������������������������������������������������������������������������������������� 435

Sending Object State Notifications Using Delegates���������������������������������������������������� 437


Enabling Multicasting������������������������������������������������������������������������������������������������������������������������� 440
Removing Targets from a Delegate’s Invocation List�������������������������������������������������������������������������� 442
Method Group Conversion Syntax������������������������������������������������������������������������������������������������������ 443

Understanding Generic Delegates�������������������������������������������������������������������������������� 444


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

Understanding C# Events��������������������������������������������������������������������������������������������� 447


The C# event Keyword������������������������������������������������������������������������������������������������������������������������ 449
Events Under the Hood����������������������������������������������������������������������������������������������������������������������� 450
Listening to Incoming Events������������������������������������������������������������������������������������������������������������� 451
Simplifying Event Registration Using Visual Studio���������������������������������������������������������������������������� 453
Creating Custom Event Arguments����������������������������������������������������������������������������������������������������� 454
The Generic EventHandler<T> Delegate�������������������������������������������������������������������������������������������� 456

Understanding C# Anonymous Methods���������������������������������������������������������������������� 457


Accessing Local Variables������������������������������������������������������������������������������������������������������������������ 459

Understanding Lambda Expressions���������������������������������������������������������������������������� 460


Dissecting a Lambda Expression�������������������������������������������������������������������������������������������������������� 463
Processing Arguments Within Multiple Statements���������������������������������������������������������������������������� 464
Lambda Expressions with Multiple (or Zero) Parameters������������������������������������������������������������������� 465

xviii
■ Table of Contents

Retrofitting the CarEvents Example Using Lambda Expressions�������������������������������������������������������� 466


Lambdas and Expression-Bodied Members (Updated 7.0)����������������������������������������������������������������� 467

Summary���������������������������������������������������������������������������������������������������������������������� 468

■Chapter 13: LINQ to Objects������������������������������������������������������������������������������� 469
LINQ-Specific Programming Constructs����������������������������������������������������������������������� 469
Implicit Typing of Local Variables������������������������������������������������������������������������������������������������������� 470
Object and Collection Initialization Syntax����������������������������������������������������������������������������������������� 471
Lambda Expressions��������������������������������������������������������������������������������������������������������������������������� 471
Extension Methods����������������������������������������������������������������������������������������������������������������������������� 472
Anonymous Types������������������������������������������������������������������������������������������������������������������������������� 473

Understanding the Role of LINQ����������������������������������������������������������������������������������� 473


LINQ Expressions Are Strongly Typed������������������������������������������������������������������������������������������������� 474
The Core LINQ Assemblies������������������������������������������������������������������������������������������������������������������ 475

Applying LINQ Queries to Primitive Arrays������������������������������������������������������������������� 475


Once Again, Using Extension Methods����������������������������������������������������������������������������������������������� 476
Once Again, Without LINQ������������������������������������������������������������������������������������������������������������������� 477
Reflecting Over a LINQ Result Set������������������������������������������������������������������������������������������������������ 478
LINQ and Implicitly Typed Local Variables������������������������������������������������������������������������������������������ 479
LINQ and Extension Methods�������������������������������������������������������������������������������������������������������������� 481
The Role of Deferred Execution���������������������������������������������������������������������������������������������������������� 481
The Role of Immediate Execution������������������������������������������������������������������������������������������������������� 483
Returning the Result of a LINQ Query��������������������������������������������������������������������������� 484
Returning LINQ Results via Immediate Execution������������������������������������������������������������������������������ 485

Applying LINQ Queries to Collection Objects���������������������������������������������������������������� 486


Accessing Contained Subobjects������������������������������������������������������������������������������������������������������� 486
Applying LINQ Queries to Nongeneric Collections������������������������������������������������������������������������������ 487
Filtering Data Using OfType<T>()������������������������������������������������������������������������������������������������������� 488

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


Basic Selection Syntax����������������������������������������������������������������������������������������������������������������������� 490
Obtaining Subsets of Data������������������������������������������������������������������������������������������������������������������ 491
Projecting New Data Types����������������������������������������������������������������������������������������������������������������� 492

xix
■ Table of Contents

Projecting to Different Data Types������������������������������������������������������������������������������������������������������ 493


Obtaining Counts Using Enumerable�������������������������������������������������������������������������������������������������� 494
Reversing Result Sets������������������������������������������������������������������������������������������������������������������������� 494
Sorting Expressions���������������������������������������������������������������������������������������������������������������������������� 494
LINQ As a Better Venn Diagramming Tool������������������������������������������������������������������������������������������� 495
Removing Duplicates�������������������������������������������������������������������������������������������������������������������������� 497
LINQ Aggregation Operations�������������������������������������������������������������������������������������������������������������� 497

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


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

Summary���������������������������������������������������������������������������������������������������������������������� 503

■Chapter 14: Processes, AppDomains, and Load Contexts��������������������������������� 505
The Role of a Windows Process����������������������������������������������������������������������������������� 505
The Role of Threads���������������������������������������������������������������������������������������������������������������������������� 506

Interacting with Processes Using .NET Core���������������������������������������������������������������� 507


Enumerating Running Processes�������������������������������������������������������������������������������������������������������� 509
Investigating a Specific Process��������������������������������������������������������������������������������������������������������� 510
Investigating a Process’s Thread Set�������������������������������������������������������������������������������������������������� 511
Investigating a Process’s Module Set������������������������������������������������������������������������������������������������� 513
Starting and Stopping Processes Programmatically�������������������������������������������������������������������������� 514
Controlling Process Startup Using the ProcessStartInfo Class����������������������������������������������������������� 515
Leveraging OS Verbs with ProcessStartInfo��������������������������������������������������������������������������������������� 517

Understanding .NET Application Domains�������������������������������������������������������������������� 518


The System.AppDomain Class������������������������������������������������������������������������������������������������������������ 518
Interacting with the Default Application Domain�������������������������������������������������������������������������������� 518
Enumerating Loaded Assemblies������������������������������������������������������������������������������������������������������� 519

Assembly Isolation with Application Load Contexts����������������������������������������������������� 521


Summarizing Processes, AppDomains, and Load Contexts������������������������������������������ 524
Summary���������������������������������������������������������������������������������������������������������������������� 524
xx
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
■ Table of Contents


■Chapter 15: Multithreaded, Parallel, and Async Programming������������������������� 525
The Process/AppDomain/Context/Thread Relationship������������������������������������������������ 525
The Problem of Concurrency�������������������������������������������������������������������������������������������������������������� 526
The Role of Thread Synchronization��������������������������������������������������������������������������������������������������� 527

The System.Threading Namespace������������������������������������������������������������������������������ 527


The System.Threading.Thread Class���������������������������������������������������������������������������� 528
Obtaining Statistics About the Current Thread of Execution��������������������������������������������������������������� 529
The Name Property����������������������������������������������������������������������������������������������������������������������������� 530
The Priority Property��������������������������������������������������������������������������������������������������������������������������� 530

Manually Creating Secondary Threads������������������������������������������������������������������������� 531


Working with the ThreadStart Delegate���������������������������������������������������������������������������������������������� 531
Working with the ParameterizedThreadStart Delegate���������������������������������������������������������������������� 533
The AutoResetEvent Class������������������������������������������������������������������������������������������������������������������ 534
Foreground Threads and Background Threads����������������������������������������������������������������������������������� 535

The Issue of Concurrency��������������������������������������������������������������������������������������������� 536


Synchronization Using the C# lock Keyword�������������������������������������������������������������������������������������� 538
Synchronization Using the System.Threading.Monitor Type��������������������������������������������������������������� 540
Synchronization Using the System.Threading.Interlocked Type��������������������������������������������������������� 541

Programming with Timer Callbacks����������������������������������������������������������������������������� 542


Using a Stand-Alone Discard�������������������������������������������������������������������������������������������������������������� 544

Understanding the ThreadPool������������������������������������������������������������������������������������� 544


Parallel Programming Using the Task Parallel Library (TPL)���������������������������������������� 546
The System.Threading.Tasks Namespace������������������������������������������������������������������������������������������ 546
The Role of the Parallel Class������������������������������������������������������������������������������������������������������������� 546
Data Parallelism with the Parallel Class��������������������������������������������������������������������������������������������� 547
Accessing UI Elements on Secondary Threads����������������������������������������������������������������������������������� 550
The Task Class������������������������������������������������������������������������������������������������������������������������������������ 551
Handling Cancellation Request����������������������������������������������������������������������������������������������������������� 552
Task Parallelism Using the Parallel Class������������������������������������������������������������������������������������������� 553

xxi
■ Table of Contents

Parallel LINQ Queries (PLINQ)��������������������������������������������������������������������������������������� 556


Opting in to a PLINQ Query����������������������������������������������������������������������������������������������������������������� 557
Cancelling a PLINQ Query������������������������������������������������������������������������������������������������������������������� 558

Async Calls with the async/await (Updated 7.0/7.1)���������������������������������������������������� 559


A First Look at the C# async and await Keywords������������������������������������������������������������������������������ 559
Naming Conventions for Asynchronous Methods������������������������������������������������������������������������������� 561
Async Methods Returning Void����������������������������������������������������������������������������������������������������������� 562
Async Methods with Multiple Awaits�������������������������������������������������������������������������������������������������� 562
Calling Async Methods from Non-async Methods������������������������������������������������������������������������������ 563
Await in catch and finally Blocks�������������������������������������������������������������������������������������������������������� 564
Generalized Async Return Types (New 7.0)���������������������������������������������������������������������������������������� 565
Local Functions (New 7.0)������������������������������������������������������������������������������������������������������������������ 565
Cancelling Async/Await Operations���������������������������������������������������������������������������������������������������� 566
Asynchronous Streams (New 8.0)������������������������������������������������������������������������������������������������������ 568
Wrapping Up async and await������������������������������������������������������������������������������������������������������������ 569

Summary���������������������������������������������������������������������������������������������������������������������� 570


■Part V: Programming with .NET Core Assemblies�������������������������� 571

■Chapter 16: Building and Configuring Class Libraries��������������������������������������� 573
Defining Custom Namespaces������������������������������������������������������������������������������������� 573
Resolving Name Clashes with Fully Qualified Names������������������������������������������������������������������������ 575
Resolving Name Clashes with Aliases������������������������������������������������������������������������������������������������ 576
Creating Nested Namespaces������������������������������������������������������������������������������������������������������������ 578
Change the Root Namespace of Visual Studio������������������������������������������������������������������������������������ 579

The Role of .NET Core Assemblies������������������������������������������������������������������������������� 580


Assemblies Promote Code Reuse������������������������������������������������������������������������������������������������������� 580
Assemblies Establish a Type Boundary���������������������������������������������������������������������������������������������� 581
Assemblies Are Versionable Units������������������������������������������������������������������������������������������������������ 581
Assemblies Are Self-Describing��������������������������������������������������������������������������������������������������������� 581

Understanding the Format of a .NET Core Assembly���������������������������������������������������� 582


Installing the C++ Profiling Tools������������������������������������������������������������������������������������������������������� 582
The Operating System (Windows) File Header����������������������������������������������������������������������������������� 583
xxii
■ Table of Contents

The CLR File Header��������������������������������������������������������������������������������������������������������������������������� 584


CIL Code, Type Metadata, and the Assembly Manifest������������������������������������������������������������������������ 585
Optional Assembly Resources������������������������������������������������������������������������������������������������������������ 586

Class Libraries vs. Console Applications���������������������������������������������������������������������� 586


.NET Standard vs. .NET Core Class Libraries���������������������������������������������������������������� 586
Configuring Applications���������������������������������������������������������������������������������������������� 587
Building and Consuming a .NET Core Class Library����������������������������������������������������� 588
Exploring the Manifest������������������������������������������������������������������������������������������������������������������������ 590
Exploring the CIL��������������������������������������������������������������������������������������������������������������������������������� 593
Exploring the Type Metadata�������������������������������������������������������������������������������������������������������������� 593
Building a C# Client Application���������������������������������������������������������������������������������������������������������� 594
Building a Visual Basic Client Application������������������������������������������������������������������������������������������� 596
Cross-Language Inheritance in Action������������������������������������������������������������������������������������������������ 596
Exposing internal Types to Other Assemblies������������������������������������������������������������������������������������� 597

NuGet and .NET Core���������������������������������������������������������������������������������������������������� 599


Packaging Assemblies with NuGet����������������������������������������������������������������������������������������������������� 599
Referencing NuGet Packages������������������������������������������������������������������������������������������������������������� 599

How .NET Core Locates Assemblies����������������������������������������������������������������������������� 600


Summary���������������������������������������������������������������������������������������������������������������������� 602

■Chapter 17: Type Reflection, Late Binding, and
Attribute-Based Programming����������������������������������������������������������������������������� 603
The Necessity of Type Metadata����������������������������������������������������������������������������������� 603
Viewing (Partial) Metadata for the EngineState Enumeration������������������������������������������������������������ 604
Viewing (Partial) Metadata for the Car Type��������������������������������������������������������������������������������������� 605
Examining a TypeRef�������������������������������������������������������������������������������������������������������������������������� 606
Documenting the Defining Assembly�������������������������������������������������������������������������������������������������� 607
Documenting Referenced Assemblies������������������������������������������������������������������������������������������������ 607
Documenting String Literals��������������������������������������������������������������������������������������������������������������� 607

Understanding Reflection��������������������������������������������������������������������������������������������� 608


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

xxiii
■ Table of Contents

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


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

Building a Custom Metadata Viewer���������������������������������������������������������������������������� 611


Reflecting on Methods������������������������������������������������������������������������������������������������������������������������ 611
Reflecting on Fields and Properties���������������������������������������������������������������������������������������������������� 612
Reflecting on Implemented Interfaces����������������������������������������������������������������������������������������������� 613
Displaying Various Odds and Ends����������������������������������������������������������������������������������������������������� 613
Implementing Main()�������������������������������������������������������������������������������������������������������������������������� 613
Reflecting on Static Types������������������������������������������������������������������������������������������������������������������ 615
Reflecting on Generic Types��������������������������������������������������������������������������������������������������������������� 616
Reflecting on Method Parameters and Return Values������������������������������������������������������������������������ 616

Dynamically Loading Assemblies��������������������������������������������������������������������������������� 617


Reflecting on Framework Assemblies�������������������������������������������������������������������������� 619
Understanding Late Binding����������������������������������������������������������������������������������������� 621
The System.Activator Class���������������������������������������������������������������������������������������������������������������� 621
Invoking Methods with No Parameters����������������������������������������������������������������������������������������������� 623
Invoking Methods with Parametersng ng ������������������������������������������������������������������������������������������ 624

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


Attribute Consumers��������������������������������������������������������������������������������������������������������������������������� 625
Applying Attributes in C#�������������������������������������������������������������������������������������������������������������������� 626
C# Attribute Shorthand Notation��������������������������������������������������������������������������������������������������������� 627
Specifying Constructor Parameters for Attributes������������������������������������������������������������������������������ 627
The Obsolete Attribute in Action��������������������������������������������������������������������������������������������������������� 628

Building Custom Attributes������������������������������������������������������������������������������������������� 629


Applying Custom Attributes���������������������������������������������������������������������������������������������������������������� 629
Named Property Syntax���������������������������������������������������������������������������������������������������������������������� 630
Restricting Attribute Usage����������������������������������������������������������������������������������������������������������������� 630

Assembly-Level Attributes������������������������������������������������������������������������������������������� 631


Using the Project File for Assembly Attributes����������������������������������������������������������������������������������� 632

xxiv
■ Table of Contents

Reflecting on Attributes Using Early Binding���������������������������������������������������������������� 633


Reflecting on Attributes Using Late Binding����������������������������������������������������������������� 634
Putting Reflection, Late Binding, and Custom Attributes in Perspective���������������������� 636
Building an Extendable Application������������������������������������������������������������������������������ 637
Building the Multiproject ExtendableApp Solution����������������������������������������������������������������������������� 637
Building CommonSnappableTypes.dll������������������������������������������������������������������������������������������������ 638
Adding Projects to the Solution���������������������������������������������������������������������������������������������������������� 639
Building the C# Snap-In���������������������������������������������������������������������������������������������������������������������� 639
Building the Visual Basic Snap-In������������������������������������������������������������������������������������������������������� 640
Create the Console Application����������������������������������������������������������������������������������������������������������� 640

Summary���������������������������������������������������������������������������������������������������������������������� 644

■Chapter 18: Dynamic Types and the Dynamic Language Runtime�������������������� 645
The Role of the C# dynamic Keyword��������������������������������������������������������������������������� 645
Calling Members on Dynamically Declared Data�������������������������������������������������������������������������������� 647
The Scope of the dynamic Keyword��������������������������������������������������������������������������������������������������� 649
Limitations of the dynamic Keyword�������������������������������������������������������������������������������������������������� 649
Practical Uses of the dynamic Keyword��������������������������������������������������������������������������������������������� 650

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


The Role of Expression Trees�������������������������������������������������������������������������������������������������������������� 651
Dynamic Runtime Lookup of Expression Trees����������������������������������������������������������������������������������� 651

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


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

Simplifying COM Interoperability Using Dynamic Data (Windows Only)����������������������� 655


The Role of Primary Interop Assemblies��������������������������������������������������������������������������������������������� 656
Embedding Interop Metadata������������������������������������������������������������������������������������������������������������� 656
Common COM Interop Pain Points������������������������������������������������������������������������������������������������������ 657

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


Summary���������������������������������������������������������������������������������������������������������������������� 660

xxv
Random documents with unrelated
content Scribd suggests to you:
Oropus, on the north-eastern frontier of Attica; a town which had
been wrested from Athens six years before, to the profound
mortification of the Athenians.
But ever and above allies without Bœotia, Thebes had
prodigiously increased the power of her city within Bœotia. She had
appropriated to herself the territories of Platæa and Thespiæ on her
southern frontier, and of Koroneia and Orchomenus near upon her
northern; by conquest and partial expulsion of their prior
inhabitants. How and when these acquisitions had been brought
about, has been explained in my preceding volume:[412] here I
merely recall the fact, to appreciate the position of Thebes in 359
B. C.—that these four towns, having been in 372 B. C. autonomous—
joined with her only by the definite obligations of the Bœotian
confederacy—and partly even in actual hostility against her—had
now lost their autonomy with their free citizens, and had become
absorbed into her property and sovereignty. The domain of Thebes
thus extended across Bœotia from the frontiers of Phokis[413] on the
north-west to the frontiers of Attica on the south.
The new position thus acquired by Thebes in Bœotia, purchased
at the cost of extinguishing three or four autonomous cities, is a fact
of much moment in reference to the period now before us; not
simply because it swelled the power and pride of the Thebans
themselves; but also because it raised a strong body of unfavorable
sentiment against them in the Hellenic mind. Just at the time when
the Spartans had lost nearly one-half of Laconia, the Thebans had
annexed to their own city one-third of the free Bœotian territory.
The revival of free Messenian citizenship, after a suspended
existence of more than two centuries, had recently been welcomed
with universal satisfaction. How much would that same feeling be
shocked when Thebes extinguished, for her own aggrandizement,
four autonomous communities, all of her own Bœotian kindred—one
of these communities too being Orchomenus, respected both for its
antiquity and its traditionary legends! Little pains was taken to
canvass the circumstances of the case, and to inquire whether
Thebes had exceeded the measure of rigor warranted by the war-
code of the time. In the patriotic and national conceptions of every
Greek, Hellas consisted of an aggregate of autonomous, fraternal,
city-communities. The extinction of any one of these was like the
amputation of a limb from the organized body. Repugnance towards
Thebes, arising out of these proceedings, affected strongly the
public opinion of the time, and manifests itself especially in the
language of Athenian orators, exaggerated by mortification on
account of the loss of Oropus.[414]
The great body of Thessalians, as well as the Magnetes and the
Phthiot Achæans, were among those subject to the ascendency of
Thebes. Even the powerful and cruel despot, Alexander of Pheræ,
was numbered in this catalogue.[415] The cities of fertile Thessaly,
possessed by powerful oligarchies with numerous dependent serfs,
were generally a prey to intestine conflict and municipal rivalry with
each other; disorderly as well as faithless.[416] The Aleuadæ, chiefs
at Larissa—and the Skopadæ, at Krannon—had been once the
ascendent families in the country. But in the hands of Lykophron and
the energetic Jason, Pheræ had been exalted to the first rank. Under
Jason as tagus (federal general), the whole force of Thessaly was
united, together with a large number of circumjacent tributaries,
Macedonian, Epirotic, Dolopian, etc., and a well-organized standing
army of mercenaries besides. He could muster eight thousand
cavalry, twenty thousand hoplites, and peltasts or light infantry in
numbers far more considerable.[417] A military power of such
magnitude, in the hands of one alike able and aspiring, raised
universal alarm, and would doubtless have been employed in some
great scheme of conquest, either within or without Greece, had not
Jason been suddenly cut off by assassination in 370 B. C., in the year
succeeding the battle of Leuktra.[418] His brothers Polyphron and
Polydorus succeeded to his position as tagus, but not to his abilities
or influence. The latter a brutal tyrant, put to death the former, and
was in his turn slain, after a short interval, by a successor yet worse,
his nephew Alexander, who lived and retained power at Pheræ, for
about ten years (368-358 B. C.).
During a portion of that time Alexander contended with success
against the Thebans, and maintained his ascendency in Thessaly.
But before the battle of Mantineia in 362 B. C., he had been reduced
into the condition of a dependent ally of Thebes, and had furnished
a contingent to the army which marched under Epaminondas into
Peloponnesus. During the year 362-361 B. C., he even turned his
hostilities against Athens, the enemy of Thebes; carrying on a naval
war against her, not without partial success, and damage to her
commerce.[419] And as the foreign ascendency of Thebes
everywhere was probably impaired by the death of her great leader
Epaminondas, Alexander of Pheræ recovered strength; continuing to
be the greatest potentate in Thessaly, as well as the most
sanguinary tyrant, until the time of his death in the beginning of 359
B. C.[420] He then perished, in the vigor of age and in the fulness of
power. Against oppressed subjects or neighbors he could take
security by means of mercenary guards; but he was slain by the
contrivance of his wife Thêbê and the act of her brothers:—a
memorable illustration of the general position laid down by
Xenophon, that the Grecian despot could calculate neither on
security nor on affection anywhere, and that his most dangerous
enemies were to be found among his own household or kindred.[421]
The brutal life of Alexander, and the cruelty of his proceedings, had
inspired his wife with mingled hatred and fear. Moreover she had
learnt from words dropped in a fit of intoxication, that he was
intending to put to death her brothers Tisiphonus, Pytholaus, and
Lykophron—and along with them herself; partly because she was
childless, and he had formed the design of re-marrying with the
widow of the late despot Jason, who resided at Thebes. Accordingly
Thêbê, apprising her brothers of their peril, concerted with them the
means of assassinating Alexander. The bed-chamber which she
shared with him was in an upper story, accessible only by a
removable staircase or ladder; at the foot of which there lay every
night a fierce mastiff in chains, and a Thracian soldier tattooed after
the fashion of his country. The whole house moreover was regularly
occupied by a company of guards; and it is even said that the
wardrobe and closets of Thêbê were searched every evening for
concealed weapons. These numerous precautions of mistrust,
however, were baffled by her artifice. She concealed her brothers
during all the day in a safe adjacent hiding-place. At night Alexander,
coming to bed intoxicated, soon fell fast asleep; upon which Thêbê
stole out of the room—directed the dog to be removed from the foot
of the stairs, under pretence that the despot wished to enjoy
undisturbed repose—and then called her armed brothers. After
spreading wool upon the stairs, in order that their tread might be
noiseless, she went again up into the bed-room, and brought away
the sword of Alexander, which always hung near him.
Notwithstanding this encouragement, however, the three young
men, still trembling at the magnitude of the risk, hesitated to mount
the stair; nor could they be prevailed upon to do so, except by her
distinct threat, that if they flinched, she would awaken Alexander
and expose them. At length they mounted, and entered the bed-
chamber, wherein a lamp was burning; while Thêbê, having opened
the door for them, again closed it, and posted herself to hold the
bar. The brothers then approached the bed: one seized the sleeping
despot by the feet, another by the hair of his head, and the third
with a sword thrust him through.[422]
After successfully and securely consummating this deed, popular
on account of the odious character of the slain despot, Thêbê
contrived to win over the mercenary troops, and to insure the
sceptre to herself and her eldest brother Tisiphonus. After this
change, it would appear that the power of the new princes was not
so great as that of Alexander had been, so that additional elements
of weakness and discord were introduced into Thessaly. This is to be
noted as one of the material circumstances paving the way for Philip
of Macedon to acquire ascendency in Greece—as will hereafter
appear.
It was in the year 360-359 B. C., that Perdikkas, elder brother and
predecessor of Philip on the throne of Macedonia, was slain, in the
flower of his age. He perished, according to one account, in a bloody
battle with the Illyrians, wherein four thousand Macedonians fell
also; according to another statement, by the hands of assassins and
the treacherous subornation of his mother Eurydikê.[423] Of the
exploits of Perdikkas during the five years of his reign we know little.
He had assisted the Athenian general Timotheus in war against the
Olynthian confederacy, and in the capture of Pydna, Potidæa,
Torônê, and other neighboring places; while on the other hand he
had opposed the Athenians in their attempt against Amphipolis,
securing that important place by a Macedonian garrison, both
against them and for himself. He was engaged in serious conflicts
with the Illyrians.[424] It appears too that he was not without some
literary inclinations—was an admirer of intellectual men, and in
correspondence with Plato at Athens. Distinguished philosophers or
sophists, like Plato and Isokrates, enjoyed renown, combined with a
certain measure of influence, throughout the whole range of the
Grecian world. Forty years before, Archelaus king of Macedonia had
shown favor to Plato,[425] then a young man, as well as to his master
Sokrates. Amyntas, the father both of Perdikkas and of Philip, had
throughout his reign cultivated the friendship of leading Athenians,
especially Iphikrates and Timotheus; the former of whom he had
even adopted as his son; Aristotle, afterwards so eminent as a
philosopher (son of Nikomachus the confidential physician of
Amyntas[426]), had been for some time studying at Athens as a pupil
of Plato; moreover Perdikkas during his reign had resident with him
a friend of the philosopher—Euphræus of Oreus. Perdikkas lent
himself much to the guidance of Euphræus, who directed him in the
choice of his associates, and permitted none to be his guests except
persons of studious habits; thus exciting much disgust among the
military Macedonians.[427] It is a signal testimony to the reputation
of Plato, that we find his advice courted, at one and the same time,
by Dionysius the younger at Syracuse, and by Perdikkas in
Macedonia.
On the suggestion of Plato, conveyed through Euphræus,
Perdikkas was induced to bestow upon his own brother Philip a
portion of territory or an appanage in Macedonia. In 368 B. C. (during
the reign of Alexander elder brother of Perdikkas and Philip),
Pelopidas had reduced Macedonia to partial submission and had
taken hostages for its fidelity; among which hostages was the
youthful Philip, then about fifteen years of age. In this character
Philip remained about two or three years at Thebes.[428] How or
when he left that city, we cannot clearly make out. He seems to
have returned to Macedonia after the murder of Alexander by
Ptolemy Alorites; probably without opposition from the Thebans,
since his value as a hostage was then diminished. The fact that he
was confided (together with his brother Perdikkas) by his mother
Eurydikê to the protection of the Athenian general Iphikrates, then
on the coast of Macedonia—has been recounted in a previous
chapter. How Philip fared during the regency of Ptolemy Alorites in
Macedonia, we do not know; we might ever suspect that he would
return back to Thebes as a safer residence. But when his brother
Perdikkas, having slain Ptolemy Alorites, became king, Philip resided
in Macedonia, and even obtained from Perdikkas (as already stated),
through the persuasion of Plato, a separate district to govern as
subordinate. Here he remained until the death of Perdikkas in 360-
359 B. C.; organizing a separate military force of his own (like Derdas
in 382 B. C., when the Lacedæmonians made war upon Olynthus;
[429]) and probably serving at its head in the wars carried on by his
brother.
The time passed by Philip at Thebes, however, from fifteen to
eighteen years of age, was an event of much importance in
determining his future character.[430] Though detained at Thebes,
Philip was treated with courtesy and respect. He resided with
Pammenes, one of the principal citizens; he probably enjoyed good
literary and rhetorical teaching, since as a speaker, in after life, he
possessed considerable talent;[431] and he may also have received
some instruction in philosophy, though he never subsequently
manifested any taste for it, and though the assertion of his having
been taught by Pythagoreans merits little credence. But the lesson,
most indelible of all, which he imbibed at Thebes, was derived from
the society and from the living example of men like Epaminondas
and Pelopidas. These were leading citizens, manifesting those
qualities which insured for them the steady admiration of a free
community—and of a Theban community, more given to action than
to speech; moreover they were both of them distinguished military
leaders—one of them the ablest organizer and the most scientific
tactician of his day. The spectacle of the Theban military force,
excellent both as cavalry and as infantry under the training of such a
man as Epaminondas, was eminently suggestive to a young
Macedonian prince; and became still more efficacious when
combined with the personal conversation of the victor of Leuktra—
the first man whom Philip learnt to admire, and whom he strove to
imitate in his military career.[432] His mind was early stored with the
most advanced strategic ideas of the day, and thrown into the track
of reflection, comparison, and invention, on the art of war.
When transferred from Thebes to the subordinate government of
a district in Macedonia under his elder brother Perdikkas, Philip
organized a military force; and in so doing had the opportunity of
applying to practice, though at first on a limited scale, the lessons
learnt from the illustrious Thebans. He was thus at the head of
troops belonging to and organized by himself—when the unexpected
death of Perdikkas opened to him the prospect of succeeding to the
throne. But it was a prospect full of doubt and hazard. Perdikkas had
left an infant son; there existed, moreover, three princes, Archelaus,
Aridæus, and Menelaus,[433] sons of Amyntas by another wife or
mistress Gygæa, and therefore half-brothers of Perdikkas and Philip:
there were also two other pretenders to the crown—Pausanias (who
had before aspired to the throne after the death of Amyntas),
seconded by a Thracian prince—and Argæus, aided by the
Athenians. To these dangers was to be added, attack from the
neighboring barbaric nations, Illyrians, Pæonians, and Thracians—
always ready[434] to assail and plunder Macedonia at every moment
of intestine weakness. It would appear that Perdikkas, shortly before
his death, had sustained a severe defeat, with the loss of four
thousand men, from the Illyrians: his death followed, either from a
wound then received, or by the machinations of his mother
Eurydikê. Perhaps both the wound in battle and the assassination,
may be real facts.[435]
Philip at first assumed the government of the country as guardian
of his young nephew Amyntas the son of Perdikkas. But the
difficulties of the conjuncture were so formidable, that the
Macedonians around constrained him to assume the crown.[436] Of
his three half-brothers he put to death one, and was only prevented
from killing the other two by their flight into exile; we shall find them
hereafter at Olynthus. They had either found, or were thought likely
to find, a party in Macedonia to sustain their pretensions to the
crown.[437]
The succession to the throne in Macedonia, though descending in
a particular family, was open to frequent and bloody dispute
between the individual members of that family, and usually fell to
the most daring and unscrupulous among them. None but an
energetic man, indeed, could well maintain himself there, especially
under the circumstances of Philip’s accession. The Macedonian
monarchy has been called a limited monarchy; and in a large sense
of the word, this proposition is true. But what the limitations were,
or how they were made operative, we do not know. That there were
some ancient forms and customs, which the king habitually
respected, we cannot doubt;[438] as there probably were also among
the Illyrian tribes, the Epirots, and others of the neighboring warlike
nations. A general assembly was occasionally convened, for the
purpose of consenting to some important proposition, or trying some
conspicuous accused person. But though such ceremonies were
recognized and sometimes occurred, the occasions were rare in
which they interposed any serious constitutional check upon the
regal authority.[439] The facts of Macedonian history, as far as they
come before us, exhibit the kings acting on their own feelings and
carrying out their own schemes—consulting whom they please and
when they please—subject only to the necessity of not offending too
violently the sentiments of that military population whom they
commanded. Philip and Alexander, combining regal station with
personal ability and unexampled success, were more powerful than
any of their predecessors. Each of them required extraordinary
efforts from their soldiers, whom they were therefore obliged to
keep in willing obedience and attachment; just as Jason of Pheræ
had done before with his standing army of mercenaries.[440] During
the reign of Alexander the army manifests itself as the only power
by his side to which even he is constrained occasionally to bow; after
his death, its power becomes for a time still more ascendent. But so
far as the history of Macedonia is known to us, I perceive no
evidence of coördinate political bodies, or standing apparatus (either
aristocratical or popular) to check the power of the king—such as to
justify in any way the comparison drawn by a modern historian
between the Macedonian and English constitutions.
The first proceeding of Philip, in dealing with his numerous
enemies, was to buy off the Thracians by seasonable presents and
promises; so that the competition of Pausanias for the throne
became no longer dangerous. There remained as assailants the
Athenians with Argæus from seaward, and the Illyrians from
landward.
But Philip showed dexterity and energy sufficient to make head
against all. While he hastened to reorganize the force of the country,
to extend the application of those improved military arrangements
which he had already been attempting in his own province, and to
encourage his friends and soldiers by collective harangues,[441] in a
style and spirit such as the Macedonians had never before heard
from regal lips—he contrived to fence off the attack of the Athenians
until a more convenient moment.
He knew that the possession of Amphipolis was the great
purpose for which they had been carrying on war against Macedonia
for some years, and for which they now espoused the cause of
Argæus. Accordingly he professed his readiness at once to give up to
them this important place, withdrawing the Macedonian garrison
whereby Perdikkas had held it against them, and leaving the town to
its own citizens. This act was probably construed by the Athenians
as tantamount to an actual cession; for even if Amphipolis should
still hold out against them, they doubted not of their power to
reduce it when unaided. Philip farther despatched letters to Athens,
expressing an anxious desire to be received into her alliance, on the
same friendly terms as his father Amyntas before him.[442] These
proceedings seem to have had the effect of making the Athenians
lukewarm in the cause of Argæus. For Mantias the Athenian admiral,
though he conveyed that prince by sea to Methônê, yet stayed in the
seaport himself, while Argæus marched inland—with some returning
exiles, a body of mercenaries, and a few Athenian volunteers—to
Ægæ or Edessa;[443] hoping to procure admission into that ancient
capital of the Macedonian kings. But the inhabitants refused to
receive him; and in his march back, to Methônê, he was attacked
and completely defeated by Philip. His fugitive troops found shelter
on a neighboring eminence, but were speedily obliged to surrender.
Philip suffered the greater part of them to depart on terms, requiring
only that Argæus and the Macedonian exiles should be delivered up
to him. He treated the Athenian citizens with especial courtesy,
preserved to them all their property, and sent them home full of
gratitude, with conciliatory messages to the people of Athens. The
exiles, Argæus among them, having become his prisoners, were
probably put to death.[444]
The prudent lenity exhibited by Philip towards the Athenian
prisoners, combined with his evacuation of Amphipolis, produced the
most favorable effect upon the temper of the Athenian public, and
disposed them to accept his pacific offers. Peace was accordingly
concluded. Philip renounced all claim to Amphipolis, acknowledging
that town as a possession rightfully belonging to Athens.[445] By
such renunciation he really abandoned no rightful possession; for
Amphipolis had never belonged to the Macedonian kings; nor had
any Macedonian soldiers ever entered it until three or four years
before, when the citizens had invoked aid from Perdikkas to share in
the defence against Athens. But the Athenians appeared to have
gained the chief prize for which they had been so long struggling.
They congratulated themselves in the hope, probably set forth with
confidence by the speakers who supported the peace, that the
Amphipolitans alone would never think of resisting the
acknowledged claims of Athens.
Philip was thus relieved from enemies on the coast, and had his
hands free to deal with the Illyrians and Pæonians of the interior. He
marched into the territory of the Pæonians (seemingly along the
upper course of the river Axius), whom he found weakened by the
recent death of their king Agis. He defeated their troops, and
reduced them to submit to Macedonian supremacy. From thence he
proceeded to attack the Illyrians—a more serious and formidable
undertaking. The names Illyrians, Pæonians, Thracians, etc., did not
designate any united national masses, but were applied to a great
number of kindred tribes or clans, each distinct, separately
governed, and having its particular name and customs. The Illyrian
and Pæonian tribes occupied a wide space of territory to the north
and north-west of Macedonia, over the modern Bosnia nearly to the
Julian Alps and the river Save. But during the middle of the fourth
century before Christ, it seems that a large immigration of Gallic
tribes from the westward was taking place, invading the territory of
the more northerly Illyrians and Pæonians, circumscribing their
occupancy and security, and driving them farther southward;
sometimes impelling them to find subsistence and plunder by
invasions of Macedonia or by maritime piracies against Grecian
commerce in the Adriatic.[446] The Illyrians had become more
dangerous neighbors to Macedonia than they were in the time of
Thucydides; and it seems that a recent coalition of their warriors, for
purposes of invasion and plunder, was now in the zenith of its force.
It was under a chief named Bardylis, who had raised himself to
command from the humble occupation of a charcoal burner; a man
renowned for his bravery, but yet more renowned for dealings rigidly
just towards his soldiers, especially in the distribution of plunder.[447]
Bardylis and his Illyrians had possessed themselves of a considerable
portion of Western Macedonia (west of Mount Bermius), occupying
for the most part the towns, villages, and plains,[448] and restricting
the native Macedonians to the defensible, yet barren hills. Philip
marched to attack them, at the head of a force which he had now
contrived to increase to the number of ten thousand foot and six
hundred horse. The numbers of Bardylis were about equal; yet on
hearing of Philip’s approach, he sent a proposition tendering peace,
on the condition that each party should retain what it actually
possessed. His proposition being rejected, the two armies speedily
met. Philip had collected around him on the right wing his chosen
Macedonian troops, with whom he made his most vigorous onset:
manœuvring at the same time with a body of cavalry so as to attack
the left flank of the Illyrians. The battle, contested with the utmost
obstinacy on both sides, was for some time undecided; nor could the
king of Macedon break the oblong square into which his enemies
had formed themselves. But at length his cavalry were enabled to
charge them so effectively in flank and rear, that victory declared in
his favor. The Illyrians fled, were vigorously pursued with the loss of
seven thousand men, and never again rallied. Bardylis presently
sued for peace, and consented to purchase it by renouncing all his
conquests in Macedonia; while Philip pushed his victory so
strenuously, as to reduce to subjection all the tribes eastward of
Lake Lychnidus.[449]
These operations against the inland neighbors of Macedonia must
have occupied a year or two. During that interval, Philip left
Amphipolis to itself, having withdrawn from it the Macedonian
garrison as a means of conciliating the Athenians. We might have
expected that they would forthwith have availed themselves of the
opening and taken active measures for regaining Amphipolis. They
knew the value of that city: they considered it as of right theirs; they
had long been anxious for its repossession, and had even besieged it
five years before, though seemingly only with a mercenary force,
which was repelled mainly by the aid of Philip’s predecessor
Perdikkas. Amphipolis was not likely to surrender to them
voluntarily; but when thrown upon its own resources, it might
perhaps have been assailed with success. Yet they remained without
making any attempt on the region at the mouth of the river
Strymon. We must recollect (as has been narrated in my last
preceding volume[450]), that during 359 B. C., and the first part of 358
B. C., they were carrying on operations in the Thracian Chersonese,
against Charidemus and Kersobleptes, with small success and
disgraceful embarrassment. These vexatious operations in the
Chersonese—in which peninsula many Athenians were interested as
private proprietors, besides the public claims of the city—may
perhaps have absorbed wholly the attention of Athens, so as to
induce her to postpone the acquisition of Amphipolis until they were
concluded; a conclusion which did not arrive (as we shall presently
see) until immediately before she became plunged in the dangerous
crisis of the Social War. I know no better explanation of the singular
circumstance, that Athens, though so anxious, both before and after,
for the possession of Amphipolis, made no attempt to acquire it
during more than a year after its evacuation by Philip; unless indeed
we are to rank this opportunity among the many which she lost
(according to Demosthenes[451]) from pure negligence; little
suspecting how speedily such opportunity would disappear.
In 358 B. C., an opening was afforded to the Athenians for
regaining their influence in Eubœa; and for this island, so near their
own shores, they struck a more vigorous blow than for the distant
possessions of Amphipolis. At the revival of the maritime
confederacy under Athens (immediately after 378 B. C.), most of the
cities in Eubœa had joined it voluntarily; but after the battle of
Leuktra (in 371 B. C.), the island passed under Theban supremacy.
Accordingly Eubœans from all the cities served in the army of
Epaminondas, both in his first and his last expedition into
Peloponnesus (369-362 B. C.).[452] Moreover, Orôpus, the frontier
town of Attica and Bœotia—immediately opposite to Eubœa, having
been wrested from Athens[453] in 366 B. C. by a body of exiles
crossing the strait from Eretria, through the management of the
Eretrian despot Themison—had been placed in the keeping of the
Thebans, with whom it still remained. But in the year 358 B. C.,
discontent began in the Eubœan cities, from what cause we know
not, against the supremacy of Thebes; whereupon a powerful
Theban force was sent into the island to keep them down. A severe
contest ensued, in which if Thebes had succeeded, Chalkis and
Eretria might possibly have shared the fate of Orchomenus.[454]
These cities sent urgent messages entreating aid from the
Athenians, who were powerfully moved by the apprehension of
seeing their hated neighbor Thebes reinforced by so large an
acquisition close to their borders. The public assembly, already
disposed to sympathize with the petitioners, was kindled into
enthusiasm by the abrupt and emphatic appeal of Timotheus son of
Konon.[455] “How! Athenians (said he), when you have the Thebans
actually in the island, are you still here debating what is to be done,
or how you shall deal with the case? Will you not fill the sea with
triremes? Will you not start up at once, hasten down to Peiræus, and
haul the triremes down to the water?” This animated apostrophe,
reported and doubtless heard by Demosthenes himself, was cordially
responded to by the people. The force of Athens, military as well as
naval, was equipped with an eagerness, and sent forth with a
celerity, seldom paralleled. Such was the general enthusiasm, that
the costly office of trierarchy was for the first time undertaken by
volunteers, instead of awaiting the more tardy process of singling
out those rich men whose turn it was to serve, with the chance of
still farther delay from the legal process called Antidosis or Exchange
of property,[456] instituted by any one of the persons so chosen who
might think himself hardly used by the requisition. Demosthenes
himself was among the volunteer trierarchs; he and a person named
Philinus being co-trierarchs of the same ship. We are told that in
three or in five days the Athenian fleet and army, under the
command of Timotheus,[457] were landed in full force on Eubœa;
and that in the course of thirty days the Thebans were so completely
worsted, as to be forced to evacuate it under capitulation. A body of
mercenaries under Chares contributed to the Athenian success. Yet it
seems not clear that the success was so easy and rapid as the
orators are fond of asserting.[458] However, their boast, often
afterwards repeated, is so far well-founded, that Athens fully
accomplished her object, rescued the Eubœans from Thebes, and
received the testimonial of their gratitude in the form of a golden
wreath dedicated in the Athenian acropolis.[459] The Eubœan cities,
while acknowledged as autonomous, continued at the same time to
be enrolled as members of the Athenian confederacy, sending
deputies to the synod at Athens; towards the general purposes of
which they paid an annual tribute, assessed at five talents each for
Oreus (or Histiæa) and Eretria.[460]
On the conclusion of this Eubœan enterprise, Chares with his
mercenaries was sent forward to the Chersonese, where he at length
extorted from Charidemus and Kersobleptes the evacuation of that
peninsula and its cession to Athens, after a long train of dilatory
manœuvres and bad faith on their part. I have in my last preceding
volume, described these events, remarking at the same time that
Athens attained at this moment the maximum of her renewed
foreign power and second confederacy, which had begun in 378 B. C.
[461] But this period of exaltation was very short. It was speedily
overthrown by two important events—the Social war and the
conquests of Philip in Thrace.
The Athenian confederacy, recently strengthened by the rescue
of Eubœa, numbered among its members a large proportion of the
islands in the Ægean as well as the Grecian seaports in Thrace. The
list included the islands Lesbos, Chios, Samos (this last now partially
occupied by a body of Athenian Kleruchs or settlers), Kos and
Rhodes; together with the important city of Byzantium. It was
shortly after the recent success in Eubœa, that Chios, Kos, Rhodes,
and Byzantium revolted from Athens by concert, raising a serious
war against her, known by the name of the Social War.
Respecting the proximate causes of this outbreak, we find,
unfortunately, little information. There was now, and had always
been since 378 B. C., a synod of deputies from all the confederate
cities habitually assembling at Athens; such as had not subsisted
under the first Athenian empire in its full maturity. How far the
Synod worked efficiently, we do not know. At least it must have
afforded to the allies, if aggrieved, a full opportunity of making their
complaints heard; and of criticising the application of the common
fund, to which each of them contributed. But I have remarked in the
preceding volume, that the Athenian confederacy, which had begun
(378 B. C.) in a generous and equal spirit of common maritime
defence,[462] had gradually become perverted, since the humiliation
of the great enemy Sparta at Leuktra, towards purposes and
interests more exclusively Athenian. Athens had been conquering the
island of Samos—Pydna, Potidæa, and Methônê, on the coast of
Macedonia and Thrace—and the Thracian Chersonese; all of them
acquisitions made for herself alone, without any advantage to the
confederate synod—and made, too, in great part, to become the
private property of her own citizens as kleruchs, in direct breach of
her public resolution, passed in 378 B. C., not to permit any
appropriation of lands by Athenian citizens out of Attica.
In proportion as Athens came to act more for her own separate
aggrandizement, and less for interests common to the whole
confederacy, the adherence of the larger confederate states grew
more and more reluctant. But what contributed yet farther to detach
them from Athens, was, the behavior of her armaments on service,
consisting in great proportion of mercenaries, scantily and irregularly
paid; whose disorderly and rapacious exaction, especially at the cost
of the confederates of Athens, are characterized in strong terms by
all the contemporary orators—Demosthenes, Æschines, Isokrates,
etc. The commander, having no means of paying his soldiers, was
often compelled to obey their predatory impulses, and conduct them
to the easiest place from whence money could be obtained; indeed,
some of the commanders, especially Chares, were themselves not
less ready than their soldiers to profit by such depredations.[463]
Hence the armaments sent out by Athens sometimes saw little of the
enemy whom they were sent to combat, preferring the easier and
more lucrative proceeding of levying contributions from friends, and
of plundering the trading-vessels met with at sea. Nor was it
practicable for Athens to prevent such misconduct, when her own
citizens refused to serve personally, and when she employed
foreigners, hired for the occasion, but seldom regularly paid.[464] The
suffering, alarm, and alienation arising from hence among the
confederates, was not less mischievous than discreditable to Athens.
We cannot doubt that complaints in abundance were raised in the
confederate synod; but they must have been unavailing, since the
abuse continued until the period shortly preceding the battle of
Chæroneia.
Amidst such apparent dispositions on the part of Athens to
neglect the interests of the confederacy for purposes of her own and
to tolerate or encourage the continued positive depredations of
unpaid armaments—discontent naturally grew up, manifesting itself
most powerfully among some of the larger dependencies near the
Asiatic coast. The islands of Chios, Kos, and Rhodes, together with
the important city of Byzantium on the Thracian Bosphorus, took
counsel together, and declared themselves detached from Athens
and her confederacy. According to the spirit of the convention, sworn
at Sparta, immediately before the battle of Leuktra, and of the
subsequent alliance, sworn at Athens, a few months afterwards[465]
—obligatory and indefeasible confederacies stood generally
condemned among the Greeks, so that these islands were justified in
simply seceding when they thought fit. But their secession, which
probably Athens would, under all circumstances, have resisted, was
proclaimed in a hostile manner, accompanied with accusations of
treacherous purposes on her part against them. It was moreover
fomented by the intrigues, as well as aided by the arms, of the
Karian prince Mausôlus.[466] Since the peace of Antalkidas, the whole
Asiatic coast had been under the unresisted dominion either of
satraps or subordinate princes dependent upon Persia, who were
watching for opportunities of extending their conquests in the
neighboring islands. Mausôlus appears to have occupied both
Rhodes and Kos; provoking in the former island a revolution which
placed it under an oligarchy, not only devoted to him, but farther
sustained by the presence of a considerable force of his mercenary
troops.[467] The government of Chios appears to have been always
oligarchical; which fact was one ground for want of sympathy
between the Chians and Athens. Lastly, the Byzantines had also a
special ground for discontent; since they assumed the privilege of
detaining and taxing the corn-ships from the Euxine in their passage
through the Bosphorus[468]—while Athens, as chief of the insular
confederacy, claimed that right for herself, and at any rate protested
against the use of such power by any other city for its own separate
profit.
This revolt, the beginning of what is termed the Social War, was a
formidable shock to the foreign ascendency of Athens. Among all her
confederates, Chios was the largest and most powerful, the entire
island being under one single government. Old men, like Plato and
Isokrates, might perhaps recollect the affright occasioned at Athens
fifty-four years before (B. C. 412) by the news of the former revolt of
Chios,[469] shortly after the great disaster before Syracuse. And
probably the alarm was not much less, when the Athenians were
now apprised of the quadruple defection among their confederates
near the Asiatic coast. The joint armament of all four was mustered
at Chios, whither Mausôlus also sent a reinforcement. The Athenians
equipped a fleet with land-forces on board, to attack the island; and
on this critical occasion we may presume that their citizens would
overcome the reluctance to serve in person. Chabrias was placed in
command of the fleet, Chares of the land-force; the latter was
disembarked on the island, and a joint attack upon the town of
Chios, by sea and land at the same moment, was concerted. When
Chares marched up to the walls, the Chians and their allies felt
strong enough to come forth and hazard a battle, with no decisive
result; while Chabrias at the same time attempted with the fleet to
force his way into the harbor. But the precautions for defence had
been effectively taken, and the Chian seamen were resolute.
Chabrias, leading the attack with his characteristic impetuosity,
became entangled among the enemy’s vessels, was attacked on all
sides, and fell gallantly fighting. The other Athenian ships either
were not forward in following him, or could make no impression.
Their attack completely failed, and the fleet was obliged to retire,
with little loss apparently, except that of the brave admiral. Chares
with his land-force having been again taken aboard, the Athenians
forthwith sailed away from Chios.[470]
This repulse at Chios was a serious misfortune to Athens. Such
was the dearth of military men and the decline of the military spirit,
in that city, that the loss of a warlike citizen, daring as a soldier and
tried as a commander, like Chabrias, was never afterwards repaired.
To the Chians and their allies, on the other hand, the event was
highly encouraging. They were enabled, not merely to maintain their
revolt, but even to obtain fresh support, and to draw into the like
defection other allies of Athens,—among them, seemingly, Sestos,
and other cities on the Hellespont. For some months they appear to
have remained masters of the sea, with a fleet of one hundred
triremes, disembarking and inflicting devastation on the Athenian
islands of Lemnos, Imbros, Samos, and elsewhere, so as to collect a
sum for defraying their expenses. They were even strong enough to
press the town of Samos, by close siege, until at length the
Athenians, not without delay and difficulty, got together a fleet of
one hundred and twenty triremes, under the joint command of
Chares, Iphikrates with his son Menestheus, and Timotheus.
Notwithstanding that Samos was under siege, the Athenian admirals
thought it prudent to direct their first efforts to the reduction of
Byzantium; probably from the paramount importance of keeping
open the two straits between the Euxine and the Ægean, in order
that the corn-ships, out of the former, might come through in safety.
[471] To protect Byzantium, the Chians and their allies raised the
siege of Samos, and sailed forthwith to the Hellespont, in which
narrow strait both fleets were collected,—as the Athenians and
Lacedæmonians had been during the closing years of the
Peloponnesian war. A plan of naval action had been concerted by the
three Athenian commanders, and was on the point of taking place,
when there supervened a sudden storm, which in the judgment both
of Iphikrates and Timotheus, rendered it rash and perilous to persist
in the execution. They therefore held off, while Chares, judging
differently, called upon the trierachs and seamen to follow him, and
rushed into the fight without his colleagues. He was defeated, or at
least was obliged to retire without accomplishing anything. But so
incensed was he against his two colleagues, that he wrote a
despatch to Athens accusing them of corruption and culpable
backwardness against the enemy.[472]
The three joint admirals were thus placed not merely in
opposition, but in bitter conflict, among themselves. At the trial of
accountability, undergone by all of them not long afterwards at
Athens, Chares stood forward as the formal accuser of his two
colleagues, who in their turn also accused him. He was seconded in
his attack by Aristophon, one of the most practised orators of the
day. Both of them charged Iphikrates and Timotheus with having
received bribes from the Chians and Rhodians,[473] and betrayed
their trust; by deserting Chares at the critical moment when it had
been determined beforehand to fight, and when an important
success might have been gained.
How the justice of the case stood, we cannot decide. The
characters of Iphikrates and Timotheus raise strong presumption
that they were in the right and their accuser in the wrong. Yet it
must be recollected that the Athenian public, (and probably every
other public,—ancient or modern,—Roman, English, or French),
would naturally sympathize with the forward and daring admiral,
who led the way into action, fearing neither the storm nor the
enemy, and calling upon his colleagues to follow. Iphikrates and
Timotheus doubtless insisted upon the rashness of his proceedings,
and set forth the violence of the gale. But this again would be
denied by Chares, and would stand as a point where the evidence
was contradictory; captains and seamen being produced as
witnesses on both sides, and the fleet being probably divided into
two opposing parties. The feelings of the Athenian Dikasts might
naturally be, that Iphikrates and Timotheus ought never to have let
their colleague go into action unassisted, even though they
disapproved of the proceeding. Iphikrates defended himself partly by
impeaching the behavior of Chares, partly by bitter retort upon his
other accuser Aristophon. “Would you (he asked), betray the fleet
for money?” “No,” was the reply. “Well, then, you, Aristophon, would
not betray the fleet; shall I, Iphikrates do so?”[474]
The issue of this important cause was, that Iphikrates was
acquitted, while Timotheus was found guilty and condemned to the
large fine of one hundred talents. Upon what causes such difference
of sentence turned, we make out imperfectly. And it appears that
Iphikrates, far from exonerating himself by throwing blame on
Timotheus, emphatically assumed the responsibility of the whole
proceeding; while his son, Menestheus tendered an accurate account
within his own knowledge, of all the funds received and disbursed by
the army.[475]
The cause assigned by Isokrates, the personal friend of
Timotheus, is, the extreme unpopularity of the latter in the city.
Though as a general and on foreign service, Timotheus conducted
himself not only with scrupulous justice to every one, but with rare
forbearance towards the maritime allies whom other generals vexed
and plundered,—yet at home his demeanor was intolerably arrogant
and offensive, especially towards the leading speakers who took part
in public affairs. While recognized as a man of ability and as a
general who had rendered valuable service, he had thus incurred
personal unpopularity and made numerous enemies; chiefly among
those most able to do him harm. Isokrates tells us that he had
himself frequently remonstrated with Timotheus (as Plato
admonished Dion), on this serious fault, which overclouded his real
ability, caused him to be totally misunderstood, and laid up against
him a fund of popular dislike sure to take melancholy effect on some
suitable occasion. Timotheus (according to Isokrates), though
admitting the justice of the reproof, was unable to conquer his own
natural disposition.[476] If such was the bearing of this eminent man,
as described by his intimate friend, we may judge how it would
incense unfriendly politicians and even indifferent persons who knew
him only from his obvious exterior. Iphikrates, though by nature a
proud man, was more discreet and conciliatory in his demeanor, and
more alive to the mischief of political odium.[477] Moreover, he seems
to have been an effective speaker[478] in public, and his popularity
among the military men in Athens was so marked, that on this very
trial many of them manifested their sympathy by appearing in arms
near the Dikastery.[479] Under these circumstances, we may easily
understand that Chares and Aristophon might find it convenient to
press their charge more pointedly against Timotheus than against
Iphikrates; and that the Dikastery, while condemning the former,
may have been less convinced of the guilt of the latter, and better
satisfied in every way to acquit him.[480]
A fine of one hundred talents is said to have been imposed upon
Timotheus, the largest fine (according to Isokrates), ever imposed at
Athens. Upon his condemnation he retired to Chalkis, where he died
three years afterwards, in 354 B. C. In the year succeeding his death,
his memory was still very unpopular; yet it appears that the fine was
remitted to his family, and that his son Konon was allowed to
compromise the demand by a disbursement of the smaller sum of
ten talents for the repairs of the city walls. It seems evident that
Timotheus by his retirement evaded payment of the full fine; so that
his son Konon appears after him as one of the richest citizens in
Athens.[481]
The loss of such a citizen as Timotheus was a fresh misfortune to
her. He had conducted her armies with signal success, maintained
the honor of her name throughout the eastern and western seas,
and greatly extended the list of her foreign allies. She had recently
lost Chabrias in battle; a second general, Timotheus, was now taken
from her; and the third, Iphikrates, though acquitted at the last trial,
seems, as far as we can make out, never to have been subsequently
employed on military command. These three were the last eminent
military citizens at Athens; for Phokion, though brave and deserving,
was not to be compared with either of them. On the other hand,
Chares, a man of great personal courage, but of no other merit, was
now in the full swing of reputation. The recent judicial feud between
the three Athenian admirals had been doubly injurious to Athens,
first as discrediting Iphikrates and Timotheus, next as exalting
Chares, to whom the sole command was now confided.
In the succeeding year, 356 B. C., Chares conducted another
powerful fleet to attack the revolted allies. Being however not
furnished with adequate funds from home to pay his troops, chiefly
foreign mercenaries, he thought it expedient, on his own
responsibility, to accept an offer from Artabazus (satrap of Daskylium
and the region south of the Propontis), then in revolt against the
Persian king.[482] Chares joined Artabazus with his own army,
reinforced by additional bodies of mercenaries recently disbanded by
the Persian satraps. With this entire force he gave battle to the
king’s troops under the command of Tithraustes, and gained a
splendid victory; upon which Artabazus remunerated him so liberally,
as to place the whole Athenian army in temporary affluence. The
Athenians at home were at first much displeased with their general,
for violating his instructions, and withdrawing his army from its
prescribed and legitimate task. The news of his victory, however, and
of the lucrative recompense following it, somewhat mollified them.
But presently they learned that the Persian king, indignant at such a
gratuitous aggression on their part, was equipping a large fleet to
second the operations of their enemies. Intimidated by the prospect
of Persian attack, they became anxious to conclude a peace with the
revolted allies; who, on their part, were not less anxious to
terminate the war. Embassies being exchanged, and negotiations
opened, in the ensuing year (355 B. C., the third of the war), a peace
was sworn, whereby the Athenians recognized the complete
autonomy, and severance from their confederacy, of the revolted
cities, Chios, Rhodes, Kos, and Byzantium.[483]
Such was the termination of the Social War, which fatally
impaired the power, and lowered the dignity, of Athens. Imperfectly
as we know the events, it seems clear that her efforts to meet this
formidable revolt were feeble and inadequate; evincing a sad
downfall of energy since the year 412 B. C., when she had contended
with transcendent vigor against similar and even greater calamities,
only a year after her irreparable disaster before Syracuse. Inglorious
as the result of the Social War was, it had nevertheless been costly,
and left Athens poor. The annual revenues of her confederacy were
greatly lessened by the secession of so many important cities, and
her public treasury was exhausted. It is just at this time that the
activity of Demosthenes as a public adviser begins. In a speech
delivered this year (355 B. C.), he notes the poverty of the treasury;
and refers back to it in discourses of after time as a fact but too
notorious.[484]
But the misfortunes arising to Athens from the Social War did not
come alone. It had the farther effect of rendering her less
competent for defence against the early aggressions of Philip of
Macedon.
That prince, during the first year of his accession (359 B. C.), had
sought to conciliate Athens by various measures, but especially by
withdrawing his garrison from Amphipolis, while he was establishing
his military strength in the interior against the Illyrians and
Pæonians. He had employed in this manner a period apparently
somewhat less than two years; and employed it with such success,
as to humble his enemies in the interior, and get together a force
competent for aggressive operations against the cities on the coast.
During this interval, Amphipolis remained a free and independent
city; formally renounced by Philip, and not assailed by the Athenians.
Why they let slip this favorable opportunity of again enforcing by
arms pretensions on which they laid so much stress—I have before
partially (though not very satisfactorily) explained. Philip was not the
man to let them enjoy the opportunity longer than he could help, or
to defer the moment of active operations as they did. Towards the
close of 358 B. C., finding his hands free from impediments in the
interior, he forthwith commenced the siege of Amphipolis. The
inhabitants are said to have been unfavorably disposed towards him,
and to have given him many causes for war.[485] It is not easy to
understand what these causes could have been, seeing that so short
a time before, the town had been garrisoned by Macedonians
invoked as protectors against Athens; nor were the inhabitants in
any condition to act aggressively against Philip.
Having in vain summoned Amphipolis to surrender, Philip
commenced a strenuous siege, assailing the walls with battering-
rams and other military engines. The weak points of the fortification
must have been well known to him, from his own soldiers who had
been recently in garrison. The inhabitants defended themselves with
vigor; but such was now the change of circumstances, that they
were forced to solicit their ancient enemy Athens for aid against the
Macedonian prince. Their envoys Hierax and Stratokles, reaching
Athens shortly after the successful close of the Athenian expedition
to Eubœa, presented themselves before the public assembly,
urgently inviting the Athenians to come forthwith and occupy
Amphipolis, as the only chance of rescue from Macedonian
dominion.[486] We are not certain whether the Social War had yet
broken out; if it had, Athens would be too much pressed with
anxieties arising out of so formidable a revolt, to have means
disposable even for the tempting recovery of the long-lost
Amphipolis. But at any rate Philip had foreseen and counterworked
the prayers of the Amphipolitans. He sent a courteous letter to the
Athenians, acquainting them that he was besieging the town, yet
recognizing it as belonging of right to them, and promising to restore
it to them when he should have succeeded in the capture.[487]
Much of the future history of Greece turned upon the manner in
which Athens dealt with these two conflicting messages. The
situation of Amphipolis, commanding the passage over the Strymon,
was not only all-important—as shutting up Macedonia to the
eastward and as opening the gold regions around Mount Pangæus—
but was also easily defensible by the Athenians from seaward, if
once acquired. Had they been clear-sighted in the appreciation of
chances, and vigilant in respect to future defence, they might now
have acquired this important place, and might have held it against
the utmost efforts of Philip. But that fatal inaction which had become
their general besetting sin, was on the present occasion encouraged
by some plausible, yet delusive, pleas. The news of the danger of
the Amphipolitans would be not unwelcome at Athens—where strong
aversion was entertained towards them, as refractory occupants of a
territory not their own, and as having occasioned repeated loss and
humiliation to the Athenian arms. Nor could the Athenians at once
shift their point of view, so as to contemplate the question on the
ground of policy alone, and to recognize these old enemies as
persons whose interests had now come into harmony with their own.
On the other hand, the present temper of the Athenians towards
Philip was highly favorable. Not only had they made peace with him
during the preceding year, but they also felt that he had treated
them well both in evacuating Amphipolis and in dismissing honorably
their citizens who had been taken prisoners in the army of his
competitor Argæus.[488] Hence they were predisposed to credit his
positive assurance, that he only wished to take the place in order to
expel a troublesome population who had wronged and annoyed him,
and that he would readily hand it over to its rightful owners the
Athenians. To grant the application of the Amphipolitans for aid,
would thus appear, at Athens, to be courting a new war and
breaking with a valuable friend, in order to protect an odious enemy,
and to secure an acquisition which would at all events come to
them, even if they remained still, through the cession of Philip. It is
necessary to dwell upon the motives which determined Athens on
this occasion to refrain from interference; since there were probably
few of her resolutions which she afterwards more bitterly regretted.
The letter of assurance from Philip was received and trusted; the
envoys from Amphipolis were dismissed with a refusal.
Deprived of all hope of aid from Athens, the Amphipolitans still
held out as long as they could. But a party in the town entered into
correspondence with Philip to betray it, and the defence thus
gradually became feebler. At length he made a breach in the walls,
sufficient, with the aid of partisans within, to carry the city by
assault, not without a brave resistance from those who still remained
faithful. All the citizens unfriendly to him were expelled or fled, the
rest were treated with lenity; but we are told that little favor was
shown by Philip towards those who had helped in the betrayal.[489]
Amphipolis was to Philip an acquisition of unspeakable
importance, not less for defence than for offence. It was not only
the most convenient maritime station in Thrace, but it also threw
open to him all the country east of the Strymon, and especially the
gold region near Mount Pangæus. He established himself firmly in
his new position, which continued from henceforward one of the
bulwarks of Macedonia, until the conquest of that kingdom by the
Romans. He took no steps to fulfil his promise of handing over the
place to the Athenians, who doubtless sent embassies to demand it.
The Social War, indeed, which just now broke out, absorbed all their
care and all their forces, so that they were unable, amidst their
disastrous reverses at Chios and elsewhere, to take energetic
measures in reference to Philip and Amphipolis. Nevertheless he still
did not peremptorily refuse the surrender, but continued to amuse
the Athenians with delusive hopes, suggested through his partisans,
paid or voluntary, in the public assembly.
It was the more necessary for him to postpone any open breach
with Athens, because the Olynthians had conceived serious alarm
from his conquest of Amphipolis, and had sent to negotiate a treaty
of amity and alliance with the Athenians. Such an alliance, had it
been concluded, would have impeded the farther schemes of Philip.
But his partisans at Athens procured the dismissal of the Olynthian
envoys, by renewed assurances that the Macedonian prince was still
the friend of Athens, and still disposed to cede Amphipolis as her
legitimate possession. They represented, however, that he had good
ground for complaining that Athens continued to retain Pydna, an
ancient Macedonian seaport.[490] Accordingly they proposed to open
negotiations with him for the exchange of Pydna against Amphipolis.
But as the Pydnæans were known to be adverse to the transfer,
secrecy was indispensable in the preliminary proceedings, so that
Antiphon and Charidemus, the two envoys named, took their
instructions from the Senate and made their reports only to the
Senate. The public assembly being informed that negotiations,
unavoidably secret, were proceeding, to ensure the acquisition of
Amphipolis—was persuaded to repel the advances of Olynthus, as
well as to look upon Philip still as a friend.[491]
The proffered alliance of the Olynthians was thus rejected, as the
entreaty of the Amphipolitans for aid had previously been. Athens
had good reason to repent of both. The secret negotiation brought
her no nearer to the possession of Amphipolis. It ended in nothing,
or in worse than nothing, as it amused her with delusive
expectations, while Philip opened a treaty with the Olynthians,
irritated, of course, by their recent repulse at Athens. As yet he had
maintained pacific relations with the Athenians, even while holding
Amphipolis contrary to his engagement. But he now altered his
policy, and contracted alliance with the Olynthians; whose friendship
he purchased not only by ceding to them the district of Anthemus
(lying between Olynthus and Therma, and disputed by the
Olynthians with former Macedonian kings), but also by conquering
and handing over to them the important Athenian possession of
Potidæa.[492] We know no particulars of these important
transactions. Our scanty authorities merely inform us, that during
the first two years (358-356 B. C.), while Athens was absorbed by her
disastrous Social War, Philip began to act as her avowed enemy. He
conquered from her not only Pydna and other places for himself, but
also Potidæa for the Olynthians. We are told that Pydna was
betrayed to Philip by a party of traitors in the town;[493] and he
probably availed himself of the secret propositions made by Athens
respecting the exchange of Pydna for Amphipolis, to exasperate the
Pydnæans against her bad faith; since they would have good ground
for resenting the project of transferring them underhand, contrary to
their own inclination. Pydna was the first place besieged and
captured. Several of its inhabitants, on the ground of prior offence
towards Macedonia,[494] are said to have been slain, while even
those who had betrayed the town were contemptuously treated. The
siege lasted long enough to transmit news to Athens, and to receive
aid, had the Athenians acted with proper celerity in despatching
forces. But either the pressure of the Social War—or the impatience
of personal service as well as of pecuniary payment—or both causes
operating together—made them behindhand with the exigency.
Several Athenian citizens were taken in Pydna and sold into slavery,
some being ransomed by Demosthenes out of his own funds; yet we
cannot make out clearly that any relief at all was sent from Athens.
[495] If any was sent, it came too late.
Equal tardiness was shown in the relief sent to Potidæa[496]—
though the siege, carried on jointly by Philip and the Olynthians, was
both long and costly[497]—and though there were a body of Athenian
settlers (Kleruchs) resident there, whom the capture of the place
expelled from their houses and properties.[498] Even for the rescue
of these fellow-citizens, it does not appear that any native Athenians
would undertake the burden of personal service; the relieving force
despatched seems to have consisted of a general with mercenary
foreigners; who, as no pay was provided for them, postponed the
enterprise on which they were sent to the temptation of plundering
elsewhere for their own profit.[499] It was thus that Philip, without
any express declaration of war, commenced a series of hostile
measures against Athens, and deprived her of several valuable
maritime possessions on the coast of Macedonia and Thrace, besides
his breach of faith respecting the cession of Amphipolis.[500] After
her losses from the Social War, and her disappointment about
Amphipolis, she was yet farther mortified by seeing Pydna pass into
his hands, and Potidæa (the most important possession in Thrace
next to Amphipolis) into those of Olynthus. Her impoverished settlers
returned home, doubtless with bitter complaint against the
aggression, but also with just vexation against the tardiness of their
countrymen in sending relief.
These two years had been so employed by Philip as to advance
prodigiously his power and ascendency. He had deprived Athens of
her hold upon the Thermaic gulf, in which she now seems only to
have retained the town of Methônê, instead of the series of ports
round the gulf acquired for her by Timotheus.[501] He had conciliated
the good-will of the Olynthians by his cession of Anthemus and
Potidæa; the latter place, from its commanding situation on the
isthmus of Pallenê, giving them the mastery of that peninsula,[502]
and ensuring (what to Philip was of great importance) their enmity
with Athens. He not only improved the maritime conveniences of
Amphipolis, but also extended his acquisitions into the auriferous
regions of Mount Pangæus eastward of the Strymon. He possessed
himself of that productive country immediately facing the island of
Thasos; where both Thasians and Athenians had once contended for
the rights of mining, and from whence, apparently, both had
extracted valuable produce. In the interior of this region he founded
a new city called Philippi, enlarged from a previous town called
Krenides, recently founded by the Thasians; and he took such
effective measures for increasing the metallic works in the
neighborhood, that they presently yielded to him a large revenue;
according to Diodorus, not less than one thousand talents per
annum.[503] He caused a new gold coin to be struck, bearing a name
derived from his own. The fresh source of wealth thus opened was
of the greatest moment to him, as furnishing means to meet the
constantly increasing expense of his military force. He had full
employment to keep his soldiers in training: for the nations of the
interior—Illyrians, Pæonians, and Thracians—humbled but not
subdued, rose again in arms, and tried again jointly to reclaim their
independence. The army of Philip—under his general Parmenio, of
whom we now hear for the first time—defeated them, and again
reduced them to submission.[504]
It was during this interval too that Philip married Olympias,
daughter of Neoptolemus prince of the Molossi,[505] and descended
from the ancient Molossian kings, who boasted of an heroic Æakid
genealogy. Philip had seen her at the religious mysteries in the island
of Samothrace, where both were initiated at the same time. In
violence of temper—in jealous, cruel, and vindictive disposition—she
forms almost a parallel to the Persian queens Amestris and Parysatis.
The Epirotic women, as well as the Thracian, were much given to
the Bacchanalian religious rites, celebrated with fierce ecstasy amid
the mountain solitudes in honor of Dionysius.[506] To this species of
religious excitement Olympias was peculiarly susceptible. She is said
to have been fond of tame snakes playing around her, and to have
indulged in ceremonies of magic and incantation.[507] Her temper
and character became, after no long time, repulsive and even
alarming to Philip. But in the year 356 B. C. she bore to him a son,
afterwards renowned as Alexander the Great. It was in the summer
of this year, not long after the taking of Potidæa, that Philip received

You might also like