Mastering C A Beginners Guide Mohamed Musthafa Mc Divya Sachdeva
Mastering C A Beginners Guide Mohamed Musthafa Mc Divya Sachdeva
Mastering C A Beginners Guide Mohamed Musthafa Mc Divya Sachdeva
Mastering C A Beginners Guide Mohamed Musthafa Mc Divya Sachdeva
1. Mastering C A Beginners Guide Mohamed Musthafa
Mc Divya Sachdeva download
https://ebookbell.com/product/mastering-c-a-beginners-guide-
mohamed-musthafa-mc-divya-sachdeva-46703824
Explore and download more ebooks at ebookbell.com
2. Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Mastering C A Comprehensive Beginners Guide To Programming Chloe
Annable
https://ebookbell.com/product/mastering-c-a-comprehensive-beginners-
guide-to-programming-chloe-annable-54665400
Mastering Objectivec A Beginners Guide Sufyan Bin Uzayr
https://ebookbell.com/product/mastering-objectivec-a-beginners-guide-
sufyan-bin-uzayr-51419856
Mastering C Programming Language A Beginners Guide Sufyan Bin Uzayr
https://ebookbell.com/product/mastering-c-programming-language-a-
beginners-guide-sufyan-bin-uzayr-46703826
Mastering C Programming Language A Beginners Guide Sufyan Bin Uzayr
https://ebookbell.com/product/mastering-c-programming-language-a-
beginners-guide-sufyan-bin-uzayr-42282602
3. Mastering Gnome A Beginners Guide 1st Edition Sufyan Bin Uzayr
https://ebookbell.com/product/mastering-gnome-a-beginners-guide-1st-
edition-sufyan-bin-uzayr-46082774
Mastering Flutter A Beginners Guide 1st Edition Sufyan Bin Uzayr
https://ebookbell.com/product/mastering-flutter-a-beginners-guide-1st-
edition-sufyan-bin-uzayr-46082778
Mastering Rust A Beginners Guide 1st Edition Sufyan Bin Uzayr
https://ebookbell.com/product/mastering-rust-a-beginners-guide-1st-
edition-sufyan-bin-uzayr-46151622
Mastering Rust A Beginners Guide 1st Edition Sufyan Bin Uzayr
https://ebookbell.com/product/mastering-rust-a-beginners-guide-1st-
edition-sufyan-bin-uzayr-46191750
Mastering Kde A Beginners Guide 1st Edition Sufyan Bin Uzayr
https://ebookbell.com/product/mastering-kde-a-beginners-guide-1st-
edition-sufyan-bin-uzayr-46257566
7. Mastering Computer Science
Series Editor: Sufyan bin Uzayr
Mastering C#: A Beginner’s Guide
Mohamed Musthafa MC, Divya Sachdeva, and Reza Nafim
Mastering GitHub Pages: A Beginner’s Guide
Sumanna Kaul and Shahryar Raz
Mastering Unity: A Beginner’s Guide
Divya Sachdeva and Aruqqa Khateib
Mastering Unreal Engine: A Beginner’s Guide
Divya Sachdeva and Aruqqa Khateib
Mastering Java: A Beginner’s Guide
Divya Sachdeva and Natalya Ustukpayeva
Mastering Python for Web: A Beginner’s Guide
Mathew Rooney and Madina Karybzhanova
For more information about this series, please visit: https://
www.routledge.com/Mastering-Computer-Science/
book-series/MCS
The “Mastering Computer Science” series of books are
authored by the Zeba Academy team members, led by
Sufyan bin Uzayr.
Zeba Academy is an EdTech venture that develops
courses and content for learners primarily in STEM
fields, and offers education consulting to Universities and
Institutions worldwide. For more info, please visit https://
zeba.academy
10. v
Contents
About the Editor, xvii
Chapter 1
◾
Mastering C# Programming
Language—A Beginner’s Guide 1
INTRODUCTION TO C# PROGRAMMING
LANGUAGE 3
WHAT IS C# 3
WHY C# MATTERS 5
HISTORY OF C# 6
C# Version 1.0 8
C# Version 1.2 8
C# Version 2.0 9
C# Version 3.0 9
C# Version 4.0 10
C# Version 5.0 11
C# Version 6.0 12
C# Version 7.0 13
11. vi ◾ Contents
C# Version 7.1 14
C# Version 7.2 14
C# Version 7.3 15
C# Version 8.0 16
C# Version 9.0 17
UNDERSTANDING THE BASIC STRUCTURE
OF THE C# PROGRAM 18
USING KEYWORD 19
NAMESPACE 19
CLASS 20
Access Modifiers 20
METHOD 21
CONSTRUCTOR 22
DATA TYPES 22
CURLY BRACES 23
Chapter 2
◾
Building Blocks of C# 27
MEMBERS 27
Accessibility 28
Fields 29
Methods 29
Parameters 30
Method Body and Local Variables 30
Static and Instance Methods 31
Method Overloading 31
Other Function Members 33
12. Contents ◾ vii
Constructors 33
Events 34
Operators 34
Finalizers 34
Expressions 34
Statements 35
UNDERSTANDING THE CLI 35
Common Type System 35
Common Language Specification 36
Metadata 36
Virtual Execution System 36
THE .NET FRAMEWORKS 37
CLR 37
Framework Class Library (FCL) 37
App Models 37
Why Do Companies Use .NET? 39
.NET Framework for Users 40
Important Points 42
What Languages Do Developers Have Access
to While Working with .NET? 43
ASSEMBLIES IN .NET 44
GAC 45
Assembly Manifest 46
What Are the Benefits of Using
Assemblies? 47
Versioning Problems 47
13. viii ◾ Contents
DLL Conflicts 48
The Solution 48
How Does It Work? 49
Chapter 3
◾
Data Types and Operators 51
VALUE DATA TYPE 52
REFERENCE DATA TYPE 53
Pointer Data Type 54
Operators 54
BASIC DATA TYPES IN C# 55
Integer 55
Double 56
Boolean 57
String 58
VARIABLES 59
Local Variables 59
Instance Variables or Non-Static Variables 61
Static Variables or Class Variables 64
Difference between Instance Variable and
Static Variable 65
Constants Variables 66
Read-Only Variables 68
CONSTANTS 70
Which Types Can Be Used as a Constant? 72
A Constant Alternative: The Read-Only Field 73
REFERENCE TYPE AND VALUE TYPES 75
14. Contents ◾ ix
ARRAYS AND OPERATORS 77
OPERATORS 80
Arithmetic Operators 80
Relational Operators 83
Logical Operators 84
Assignment Operators 84
Chapter 4
◾
Exploring User-Defined Types 89
CLASSES AND OBJECTS 90
System Classes 93
Creating and Using Objects 94
Releasing the Objects 95
Access to Fields of an Object 96
Access to the Memory and Properties of an
Object—Example 96
Calling Methods of Objects 97
Calling Methods of Objects—Example 97
CONSTRUCTORS 98
Constructor with Parameters 98
Calling Constructors—Example 99
When to Use Static Fields and Methods 101
Static Fields and Methods—Example 102
STRUCTURES 103
Structs with Methods 104
Structs and Constructors 105
Nested Structs 106
15. x ◾ Contents
ENUMERATION 110
NAMESPACES 118
Nested Namespaces 123
Chapter 5
◾
Object-Oriented Programming
in C# 127
WHAT IS OOP 129
Basic Principles Concept in
C# Programming 129
Structure of OOP 130
Class 131
Objects 132
Method 133
Encapsulation 135
Abstract Classes 138
Inheritance 140
Polymorphism 142
IMPLEMENTATION OF OOP 146
Encapsulation 146
Inheritance 146
Polymorphism 147
Reusability 147
Compiling the Program 148
Classes and Objects 149
Multiple Class Declaration 150
Partial Classes 151
16. Contents ◾ xi
Static Classes 154
Constructor and Destructor 154
Static Constructor 156
Destructors 158
Function Overloading 160
Virtual Methods 162
Hiding Methods 163
Abstract Classes 165
Sealed Classes 166
Interface 167
ENCAPSULATION AND INHERITANCE 169
Advantages of Encapsulation 172
Inheritance 173
Types of Inheritance in C# 173
Advantages of Inheritance in C# 176
Why Use Inheritance and How It Makes It
Easy to Work? 177
CONCLUSION 177
Chapter 6
◾
Generics in C# 179
WHAT ARE GENERICS 180
Characteristics of Generics 181
Type Safety 182
Performance 183
Binary Code Reuse 184
17. xii ◾ Contents
Generic Methods 185
Generic Class and Methods 186
C# Constraint 189
C# Multiple Constraints 191
GENERIC TYPES AND METHODS 193
Generic Types 193
Constraints 196
Type Constraints 198
Reference Type Constraints 201
Value Type Constraints 203
Value Types Down with Unmanaged
Constraints 204
Not Null Constraints 204
Other Special Type Constraints 204
Multiple Constraints 205
Type Inference 206
COVARIANCE AND CONTRAVARIANCE IN
GENERICS 206
Generic Interfaces with Contravariant Type
Parameters 210
Chapter 7
◾
Functional Programming and
Lambdas in C# 213
FUNCTIONAL PROGRAMMING 214
Benefits of Functional Programming 215
Function Types 218
18. Contents ◾ xiii
Function Arithmetic 223
C# Functional Programming 225
Higher-Order Functions 226
Asynchronous Functions 227
Asynchronous Functions with
Callbacks 229
Tuples 230
Closures 233
LAMBDA EXPRESSION 234
Async Lambdas 236
Variable Scope in Lambda Expression 238
Statement Lambda 240
LINQ 242
Advantages of LINQ Include the Following: 243
Namespace 245
Filtering 247
Distinct 248
Aggregation 250
Method Chaining 250
Existence Operations 251
Intersection 253
Union 253
Except 253
Grouping 254
19. xiv
◾ Contents
Chapter 8
◾
Dynamic Programming and
Reflection 257
ADVANTAGES OF DYNAMIC AND STATIC
LANGUAGES 259
Recursion vs. Dynamic Programming 263
Recursion vs. Iteration 263
Approaches of Dynamic Programming 263
Top-Down Approach 263
Advantages 264
Bottom-Up Approach 266
Key Points 266
DYNAMIC PROGRAMMING IN C# 266
How to Use Dynamic 267
Dynamic and Overloading of Methods 272
Conclusion 274
UNDERSTANDING REFLECTION 275
Defining Reflection in C# 275
A Simple Use Case 276
How Reflection in C# Works 278
Uses for Reflection C# 280
USING DYNAMIC TYPE 281
How Does Dynamic Type Work? 281
Short Overview of DLR 283
Call Ste Caching 283
Expression Trees 284
Dynamic Object Interoperability 284
20. Contents ◾ xv
Why Should We Use the Dynamic Type 284
Dynamic vs. Reflection 285
Var vs. Object vs. Dynamic 287
Var Keyword 288
Object Keyword 288
Dynamic Keyword 289
APPRAISAL, 291
INDEX, 299
22. xvii
About the Editor
Sufyan bin Uzayr is a writer, coder, and entrepreneur with
more than a decade of experience in the industry. He has
authored several books in the past, pertaining to a diverse
range of topics, ranging from History to Computers/IT.
Sufyan is the Director of Parakozm, a multinational IT
company specializing in EdTech solutions. He also runs
Zeba Academy, an online learning and teaching vertical
with a focus on STEM fields.
Sufyan specializes in a wide variety of technologies,
such as JavaScript, Dart, WordPress, Drupal, Linux, and
Python. He holds multiple degrees, including ones in
Management, IT, Literature, and Political Science.
Sufyan is a digital nomad, dividing his time between
four countries. He has lived and taught in universities and
educational institutions around the globe. Sufyan takes a
keen interest in technology, politics, literature, history and
sports, and in his spare time, he enjoys teaching coding
and English to young students.
Learn more at sufyanism.com.
24. 1
DOI: 10.1201/9781003214779-1
C h a p t e r 1
Mastering C#
Programming
Language—
A Beginner’s Guide
IN THIS CHAPTER
➢ What is C#?
➢ Basic Introduction to C#
➢ Evolution of C#
In this fast-moving world of digital transformation, almost
everyone has access to the Internet and smartphones. The
use of the Internet is all about browsing websites and several
25. 2 ◾ Mastering C#
kinds of mobile apps. Interestingly, you may not count the
number of apps that you use per day. Whether it’s most
rampantly used microblogging apps like Twitter, stream-
ing services like Netflix, messaging apps like WhatsApp,
the coding stays at the foundation of everything. There
are over 1.7 billion websites on the Internet today, all of
which are powered by some programming language. It
continues to evolve in both industry and research as sys-
tems and applications change. Programming is the pro-
cess that makes it possible to create software, applications,
and websites. It is a kind of artificial language that can be
used to control the behavior of a machine, particularly a
computer or other gadget like a mobile. We already know
that computers or any other similar technologies cannot
think themselves; they require users to give sets of ordered
instructions to know what to do. So programming works
here. It is used to facilitate communication about organiz-
ing and manipulating information and express algorithms
precisely. Its languages are entirely different from most
other forms of human expression in that they require a
greater degree of precision and completeness.
This sort of language is referred to as “code.” Most of
the resources you use on the computer and Internet are
made with code. Learning this sort of coding is simple. All
you need is some idea and the right tool. Coding an app
involves taking a picture, designing the app, testing it, and
releasing it. There is never a better ideal time to develop an
app than today. Surprisingly, you have an enormous mar-
ket for your app once it hits Google Play and App Store. If
you are newer to the mobile app development world but
ardently want to be part of it somehow by yourself, this
26. Mastering C# Programming Language ◾ 3
book is a detailed guide that will help learners get started
with C# programming. It firstly talks about the basics and
then moves on to practical exercises to help readers quickly
gain the required knowledge.
INTRODUCTION TO C# PROGRAMMING
LANGUAGE
C# is a general-purpose, advanced and Object-Oriented
Programming Language pronounced as “C sharp” cre-
ated by Microsoft that runs on the .NET Framework. C#
has roots in the C family, and the language is close to
other popular languages like C++ and Java. The first ver-
sion was released in the year 2002. The latest version, C#
8, was released in September 2019. C# is recognized as a
standard by ECMA and ISO. C# is specifically designed
for Common Language Infrastructure (CLI). It’s a stan-
dard for describing executable code and the environment
in which it runs. C# was initially known as C-like Object-
Oriented Language (COOL) but altered the name to pre-
vent trademark concerns. Since the C# is formed within
the .Net Framework initiative by Microsoft, it provides
various integrated development environments (IDEs) to
run C# programs smoothly.
While C# can be put to better use in the hands of all
sorts of programmers, a large part of the language’s user
base comprises those who are partial to the Microsoft
platform.
WHAT IS C#
C# (pronounced “C-sharp”) is an object-based program-
ming language from Microsoft that significantly focuses
27. 4 ◾ Mastering C#
on combining the computing power of C++ with the
programming ease of Visual Basic. C# is based on C++
and includes features similar to those of Java. It’s a blend
between C and C++. C# is commonly used for backend
services, windows applications, website development, and
game development.
C# is arranged to work with Microsoft’s .NET platform.
Microsoft’s main aim is to facilitate exchanging informa-
tion and services over the web and let developers build
highly portable applications. C# smoothen programming
by using Extensible Markup Language (XML) and Simple
Object Access Protocol (SOAP), which allowed access to
a programming object or method without requiring the
programmer to write additional code for each step. That
is something quite interesting. Do you know one thing?
Programmers here can build on existing code rather than
repeatedly duplicating it. C# is expected to make it faster
and less expensive to market new products and services.
C# programs run on .NET and a virtual execution system
called the common language runtime (CLR) and included
many class libraries. The CLR is the implementation of the
CLI by Microsoft, an international standard. The CLI is
the ground for creating execution and development envi-
ronments in which languages and libraries work together
continuously.
Source code written in C# is compiled into an inter-
mediate language (IL) that matches the CLI specification.
The IL code and its resources, like bitmaps and strings, are
saved in an assembly, which usually ends in.dll. A pack
includes a manifest that provides information about the
assembly’s types, genre, and culture.
28. Mastering C# Programming Language ◾ 5
When the C# program is carried out, the assembly is
filled into the CLR. The CLR performs Just-In-Time (JIT)
compilation to change the IL code to native machine
instructions. The CLR gives other services related to
automatic garbage collection, exception handling, and
resource management. Code carried out by the CLR is
sometimes referred to as “managed code,” in comparison
with “unmanaged code,” which is composed into native
machine language that selects a specific platform.
Language interoperability is a crucial feature .NET.
IL code produced by the C# compiler conforms to the
Common Type Specification (CTS). IL code generated
from C# can simply interact with code generated from the
.NET versions of F#, Visual Basic, C++, or any of more than
20 other CTS-compliant languages. A single assembly may
include different modules written in different .NET lan-
guages, and the types can reference each other as if they
were written in the same, unique language.
Besides the runtime services, .NET also includes com-
prehensive libraries. These libraries support many differ-
ent kinds of workloads. They’re organized into namespaces
that give a wide variety of proper functionality for every-
thing from file input and output to string manipulation to
XML parsing, web application frameworks, and Windows
Forms controls. The typical C# application utilizes the
.NET class library considerably to handle every day
“plumbing” chores.
WHY C# MATTERS
As a beginner, it’s pretty simple to learn C#; to know C#,
you should have at least a basic idea of writing code, even if
29. 6 ◾ Mastering C#
you have yet to build your first application or program. The
learning curve for C# is comparatively low when compared
to more complex languages.
C# is an excellent choice for developers with moderate
to advanced experience with writing code. While experts
admit the language is one of the reasonable complexities,
they agree that it’s relatively simple to grasp and outper-
form. Once you’re introduced to C# and put in the time to
get the hang of it, you can expect to advance quickly from
an amateur to an expert.
This is since C# is a first-class language, which means
it’s relatably easy to grasp and write, making it a splendid
choice for beginners and a convenient option for experts.
In addition to readability, C# can also automate complex
tasks that require a lot of time to achieve minor results.
This programming language is also statistically typed,
which means that errors are identified before the applica-
tion goes live. This makes it simple to detect minor flaws in
your stack that would otherwise be almost.
HISTORY OF C#
In 2000, Microsoft announced its initial version of C#
as a part of the .NET Framework. VB.NET was also an
alternative, but VB.NET stuck to the standard Microsoft
Visual Basic syntax, while C# was close to Java, a C-style
language. The name was given to C# firstly was “Cool.”
Microsoft was conscious of working with a language very
approximately to C++, so they wanted to specify that
its new language was one step higher than C++. C# is a
newly discovered language on the market developed by
Microsoft. Initially, Microsoft advanced and deployed the
30. Mastering C# Programming Language ◾ 7
Active Server Pages (ASP) language. This language is now
labeled Classic ASP, and its support has been discontinued.
ASP lets programmers generate VB-like scripts to enlarge
dynamic web pages. These sort of web pages continued on
aged Internet information Services (IIS) servers running
Windows. Some Linux providers also supported Classic
ASP, but it was routinely a nonstandard way to create web
pages. In the late 1990s, Microsoft decided to make a lan-
guage that fought a tight-spirited fight with Java. During
this course of time, Java was the most common language,
and its popularity was rising. Classic ASP had its place,
but the software required to create the product was a paid
application. Java was used to develop web applications, and
it was favored among developers who understood C and
C++. Instead of label the new language C+++, they decided
to use the name C# (pronounced C sharp), which attributes
the musical notation that a note should be higher in pitch.
The C# team is continuing to innovate and add new spe-
cific features.
This chapter provides a history of a significant release
of the C# language as they are meticulously focusing on
remarkable innovation and adding spectacular features to
this.
• C# version 1.0.
• C# version 1.2.
• C# version 2.0.
• C# version 3.0.
• C# version 4.0.
31. 8 ◾ Mastering C#
• C# version 5.0.
• C# version 6.0.
• C# version 7.0.
• C# version 7.1.
• C# version 7.2.
• C# version 7.3.
• C# version 8.0.
• C# version 9.0.
C# Version 1.0
Microsoft released the first version of C# with Visual Studio
2002. Use of managed code was introduced with this ver-
sion. C# 1.0 was the first language that developers adopted
to build .NET applications.
The significant features of C# 1.0 include:
• Classes.
• Structs.
• Interfaces.
• Events.
• Properties.
• Delegates.
C# Version 1.2
This version was introduced with Visual Studio .NET
2003. It mainly includes a few minor enhancements to the
32. Mastering C# Programming Language ◾ 9
language. The most significant is that the code generated
a for each loop called Dispose on an IEnumerator when
IEnumerator implemented IDisposable.
C# Version 2.0
With Visual Studio 2005 (formerly codenamed Whidbey),
C# is back with some innovations. The C# language has
successfully been updated to version 2.0 and comes with
several language extensions. Besides generic types, the
C# language introduces other exciting features such as
Iterators, Partial Classes, Anonymous methods, partial
types, and Nullable value types.
Other C# 2.0 features essentially added capabilities to
existing features:
• Getter/setter separate accessibility.
• Method group conversions (delegates).
• Static classes.
• Delegate inference.
While C# may have started as a generic OOL, C# version
2.0 changed that hastily. Once they had complete control
over them, they went after some complicated developer
pain points. And they even went after them in a significant
way.
C# Version 3.0
C# version 3.0 was released as part of .Net version 3.5.
Many of the features added explicitly with this version sup-
ported Language Integrated Queries (LINQ).
33. 10 ◾ Mastering C#
List of added features:
• LINQ.
• Lambda expressions.
• Extension methods.
• Anonymous types.
• Implicitly typed variables.
• Object and collection initializers.
• Automatically implemented properties.
• Expression trees.
In retrospect, many of these features above seem both inev-
itable and inseparable. They all fit together strategically. It’s
generally thought that the C# version’s killer feature was
the query expression, also popularly known as Language-
Integrated Query (LINQ).
A more nuanced view examines expression trees, lambda
expressions, and anonymous types as the foundation of
LINQ. But, in either case, C# 3.0 introduced a breathtaking
concept.C#3.0hadbeguntolaythegroundworkforturning
C# into a hybrid OOL/Functional language. Importantly,
you could now write SQL-style declarative queries to per-
form operations on collections, among other things.
C# Version 4.0
Microsoft introduced this version of the C# in April 2010
with Visual Studio 2010. Mono C# compiler fully sup-
ported the new version by October 2010 with the release of
34. Mastering C# Programming Language ◾ 11
Mono 2.8. The next version did introduce some interesting
new features:
• Dynamic binding
• Named/optional arguments
• Generic covariant and contravariant
• Embedded interop types
The new version of the C# language brought a new type
of dynamic. Once a variable is declared as having type
dynamic, operations on these values are not done or veri-
fied at compile-time but instead happen entirely at run-
time. This is also known as duck typing.
Embedded interop types eased the deployment pain
of creating COM interop assemblies for your applica-
tion. Generic and contravariance provide you with more
power to use generics, but they’re a bit academic and prob-
ably most appreciated by framework and library authors.
Named and optional parameters let you eliminate many
method overloads and provide convenience. But none of
those features are precisely paradigm-altering.
C# Version 5.0
C# version 5.0, released with Visual Studio 2012, was a
focused version of the language. Almost all of the effort for
that version went into another disruptive language concept:
the async and await model for asynchronous programming.
Here’s the list of the significant features:
• Asynchronous methods.
• Caller info attributes.
35. 12 ◾ Mastering C#
The Async feature establishes two keywords, async and
await, which allows you to write asynchronous code more
quickly and intuitively like synchronous code. Before C#
5.0, for writing an asynchronous code, you have to define
callbacks (also known as continuations) to capture what
happens after an asynchronous process completes. This
makes your code and another routine task such as excep-
tion handling complicated. Caller information can help
you out in tracing, debugging, and creating diagnosis
tools. It will help you avoid duplicate codes that are gener-
ally invoked in many methods for the same purpose, such
as logging and tracing.
C# Version 6.0
With versions 3.0 and 5.0, C# had added significant and
outstanding new features in an OOL. With unique version
6.0, released with Visual Studio 2015, it would wane from
doing a dominant killer feature and, in lieu, release many
more minor features that made C# programming more
productive. The C# 6.0 version contains many essential ele-
ments which will improve the productivity of developers.
Here are some of them:
• Using static.
• Exception filters.
• Auto-property initializers.
• Expression bodied members.
• Null propagator.
• String interpolation.
36. Mastering C# Programming Language ◾ 13
• Name of operator.
• Index initializers.
• Await in catch/finally blocks.
• Default values for getter-only properties.
Each of these features is quite interesting in its own right.
But if you gaze at them all together, you see an inter-
esting pattern. In this version, C# eliminated language
boilerplate to make code more terse and readable. So for
fans of clean, simple code, this language version was a
huge win.
C# Version 7.0
With Visual Studio 2017 (March 7, 2017), we got a new ver-
sion of C#—C# 7.0. There is a lot of new exciting features
that nicely build on top of existing ones.
Here is an overview of new features in C#:
• Out variables.
• Pattern matching.
• Tuples.
• Deconstruction.
• Discards.
• Local functions.
• Binary literals.
• Digit separators.
37. 14 ◾ Mastering C#
All of these features provide extraordinary new capabilities
for developers and the opportunity to write even cleaner
code than ever. A highlight is condensing the declaration
of variables to use with the out keyword and allowing mul-
tiple return values via tuple.
But C# is being put to ever broader use. .NET Core now
targets any operating system and has its eyes firmly on
the cloud and portability. These new capabilities indeed
occupy the language designers’ thoughts and time and
come up with new features.
C# Version 7.1
C# 7.1 was released in August 2017 as part of the 15.3
updates for Visual Studio 2017. The most notable new fea-
ture in C# 7.1 is the ability to have an async Main method.
With C# 7.0, we started seeing point releases on C#, start-
ing with version 7.1. This marked an increased release
cadence for C#. New language features for this release were:
• Async Main method,
• Default literal expressions,
• Inferred tuple element names, and
• Pattern matching on generic type parameters.
C# 7.1 also added the language version selection configura-
tion element, as well as new compiler behavior.
C# Version 7.2
C# 7.2 added a few more minor language features to C#.
These were:
38. Mastering C# Programming Language ◾ 15
• The addition of code enhancements allowing devel-
opers to write safe, efficient code,
• The in modifier on parameters,
• The ref read-only modifier on method returns,
• The read-only struct declaration,
• The ref struct declaration,
• Non-trailing named arguments,
• Leading underscores in numeric literals,
• Private protected access modifier, and
• Conditional ref expressions.
C# Version 7.3
The point releases of C# 7 allowed developers to get their
hands on new language features sooner rather than later. It
was the release of C# 7.3 that had two main themes. One
theme allowed safe code to perform unsafe code, and the
otherprovidedadditionalimprovementstoexistingfeatures.
From a better performant, safe code perspective, we saw:
• The accessing of fields without pinning;
• Reassigning ref local variables;
• On stackalloc arrays, initializers are used;
• Fix statements can be used with any type that sup-
ports a pattern; and
• Additional generic constraints.
39. 16 ◾ Mastering C#
C# Version 8.0
C# 8.0 is the first major C# release that explicitly targets
.NET Core. Some features rely on new CLR capabilities,
others on library types added only in .NET Core. C# 8.0
added up the following specifications and enhancements
to the C# language:
• Default interface methods.
• Nullable reference types.
• Pattern matching enhancements.
• Asynchronous streams/Asynchronous disposable.
• Using declarations.
• Enhancement of interpolated verbatim strings.
• Null-coalescing assignment.
• Static local functions.
• Indices and ranges.
• Unmanaged constructed types.
• Read-only member.
Nullable reference types are perhaps the most significant
feature in C# 8.0. It introduces a configurable change
whereby reference types are non-nullable by default but
can explicitly allow null with a nullable modifier. Of
course, the new feature list doesn’t stop there. Other more
prominent features include support for data and pattern
matching improvements. The latter provides a terse syntax
40. Mastering C# Programming Language ◾ 17
instead of switch expressions (yes, expressions) that enable
conditional checks to evaluate the shape and data within
an object to determine a result. In addition, there are sev-
eral miscellaneous enhancements such as default interface
implementations, using declarations, static local func-
tions, indices/ranges, and a null-coalescing assignment
operator.
C# Version 9.0
C# 9.0 was released with .NET 5. It’s the default language
version for any assembly that targets the .NET 5 release.
Many C# 9.0 features rely on new features in the .NET 5.0
libraries and updates to the .NET CLR that’s part of .NET
5.0. Therefore, C# 9.0 is supported only on .NET 5.0. C#
9.0 focuses on features that help native cloud applications,
modern software engineering practices, and more concise
readable code.
C# 9.0 adds the following features and enhancements to
the C# language:
• Top-level statements.
• Record types.
• Init-only setters.
• Enhancements to pattern matching.
• Natural-sized integers.
• Function pointers.
• Omit localsinit.
• Target type new.
41. 18 ◾ Mastering C#
• Target type conditional.
• Static anonymous methods.
• Covariant return types.
• Lambda discard parameters.
• Attributes on local functions.
C# 9.0 continues three themes from previous releases:
removing ceremony, separating data from algorithms, and
providing more patterns in more places. The introduction
of the record offers a concise syntax for reference types that
follow value semantics for equality. You’ll use these types
to define data containers that typically define minimal
behavior. Init-only setters provide the capability for the
nondestructive mutation (with expressions) in records. C#
9.0 also adds covariant return types so that derived forms
can override virtual methods and return a style derived
from the base method’s return type.
UNDERSTANDING THE BASIC
STRUCTURE OF THE C# PROGRAM
A typical C# program includes several different parts as
shown below:
• Namespace.
• Class.
• The main method.
• Methods inside the class.
42. Mastering C# Programming Language ◾ 19
• Class definition or class attributes.
• Statements.
• Comments.
Few things need to be kept in your mind while writing a
C# program. C# programs are case-sensitive, which does
mean “string” is different from “String.” All the statements
you write in the program should be concluded with a semi-
colon, i.e., “;” a semicolon tells the program explicitly that
the current line of the statement has ended.
USING KEYWORD
The using keyword is importantly used to handle any
object used to carry out the namespace. It is mainly used
to bring in a namespace. Because a namespace is a collec-
tion of classes, each of which has its functionality, we can
use the keyword to implement various features from the
namespace that has been imported.
NAMESPACE
A namespace is a logical grouping of similar classes and
objects. Its purpose is to keep a diverse group of items apart
from one another. This allows programmers to define
one class in one namespace and another in a different
namespace without generating any problems.
Let’spretendwe’recreatingtwonamespaces:“fruits”and
“colors.” Both of these namespaces can have an “Orange”
class without interfering with any other. A namespace is
created by entering the name of the namespace followed by
the term namespace.
Namespace ConsoleApplication, for example.
43. 20 ◾ Mastering C#
CLASS
Defining a class is analogous to defining a data type’s blue-
print. The data is not described by style; instead, it is orga-
nized as a significant entity.
For instance, if we have a class called “Fruit,” we may
create many related objects within it, such as mango, apple,
grapes, and so on. Thus, the class fruit will contain differ-
ent objects with other properties such as color, smell, taste
edible, etc. Each of these items and property will be a part
of the class.
Similar to the example mentioned above, the Object-
Oriented Programming Language such as C# also defines
different properties inside, i.e., fields, methods, conditions,
events, etc. The objects inside the class include a definition
of the operations that can be performed. Objects are an
instance of the class and the methods or the variables that
are the class members. In summary, the course enables you
to create unique objects by combining different techniques,
events, and object kinds.
A class is defined by preceding the course name with
the keyword “class.” A pair of curly braces determine the
class body.
class program1
{
//body
of the class
}
Access Modifiers
It defines the accessibility of an object, and it is very com-
ponents. All C# components have an access level that may
44. Mastering C# Programming Language ◾ 21
be controlled using access modifiers to restrict access to
member objects inside the class.
To define the accessibility level of the object, we have
got to declare it by using one of the keywords provided by
C# language, i.e., Public, Private, Protected, and Internal.
Access modifier is expressed by using either of the key-
words mentioned above before the class or a method.
Example:
public class program//Set the access
modifier
to public.
{
}
METHOD
It is a collection of statements that work together to com-
plete a job. At least one class with one Main method will be
present in every C# application.
It includes the following definition. It starts with an
access modifier declaration, then a return type, and later,
we define the method name, and inside the round bracket,
we have the parameters specified.
{Access Modifiers} {return type definition}
Method Name({parameter})
public static void Main(String[] args){
}
After the method has been defined, commands or state-
ments can be written within the curly braces. Arguments
can be passed within the round bracket just after the
method name.
45. 22 ◾ Mastering C#
These arguments are helpful while calling a method
with specific parameters. In the above example, we have
crossed only one parameter, “args,” with the argument
type as an array of strings.
CONSTRUCTOR
Constructors are the unique class methods that are auto-
matically invoked whenever an instance of a specific type
is created. The main advantage of the constructor is that it
can initialize the private fields of a class. A class can have
some constructors, and it doesn’t need to have any return
type.
Only one static constructor is allowed inside a class, and
that cannot be parameterized. Constructors are declared
by using any access modifier and then using the class name
in which it is created. For Example, a constructor defini-
tion will look something like this.
class program1
{
public class(){ //This is a constructor
}
}
DATA TYPES
Data types are used in almost all programming languages.
A data type tells the compiler what kind of value a variable
will hold. C# has several built-in data types such as String,
Integer, Float, Boolean, etc. Each data type has its own set
of definitions for the values it can hold.
A data type is used to declare a variable by the primary
variable with the data type keyword.
46. Mastering C# Programming Language ◾ 23
class program1
{
static void Main(string[] args)
{
string stringValue = Hello;
int integerValue = 10;
float floatValue = 13.2f;
bool booleanValue = false;
}
}
CURLY BRACES
It defines the beginning and the end of any logical state-
ment in a program block. The curly braces are restricted to
the C# language, but they are also found in several other
languages like Java, C++, etc. You can see our first “Hello
World” code used to wrap multiple lines of code together.
It marks the starting and the end point of the logical state-
ment for the compiler.
Any logical entity like Namespace, Class, Method,
Conditional statement, Loops, etc., should be enclosed
inside braces to mark the start and end of the report for the
compiler. For a better grasp of the overall structure of a C#
program, below is the simplest C# program:
* C# Program Structure - Example */
using System;
namespace HelloEveryoneApp
{
class HelloEveryoneClass
{
static void Main(string[] args)
{
47. 24 ◾ Mastering C#
/* this is first program in C#
language */
Console.WriteLine(Hello Everyone);
Console.ReadKey();
}
}
When the above code is compiled and executed, it will pro-
duce the following output:
• Hello Everyone
Here is the explanation of the above C# program:
• /* C# Program Structure - Example program */: The
C# compiler ignores this line; this is the comment in
the program.
• using System;: The using keyword includes the sys-
tem namespace in the C# program.
• namespace HelloEveryoneApp: This is the
namespace declaration. It is simply a collection of
classes. The HelloEveryoneApp namespace contains
the class named HelloEveryoneClassclass—Here, the
class HelloEveryoneClass includes the data and the
method definitions that your C# program uses.
• static void Main(string[] args): This line defined the
Main method, which is the entry point for all the C#
programs.
• */: The C# compiler also ignores this line; this is also
a comment in the program.
48. Mastering C# Programming Language ◾ 25
• Console.WriteLine(“Hello Everyone”);: This is
the same behavior of the Main method. Here the
WriteLine() is the method of the Console class,
which is defined in the system namespace. This state-
ment causes the message “Hello Everyone” to be dis-
played on the output screen.
• Console.ReadKey();: This is for the VS.NET users.
This statement makes the C# program wait for a key-
press, and it prevents the sudden closing of the output
screen when the program is launched from the Visual
Studio .NET.
To compile and to run the above C# program using Visual
Studio.NET (VS.NET), follow these steps:
• open visual studio
• on the menu bar
• choose FILE - NEW - PROJECT
• choose visual C# from templates
• choose windows
• choose console application
• specify a name for your project
• Click OK
After processing the above-given steps, your new project
in the Solution Explorer is created. Now just write the
above code in the Code Editor. After writing the code, to
49. 26 ◾ Mastering C#
run your C# program, just press the F5 key or click on the
RUN button to execute the project. After performing this,
a command prompt window will appear, containing the
line, Hello World.
50. 27
DOI: 10.1201/9781003214779-2
C h a p t e r 2
Building Blocks of C#
IN THIS CHAPTER
➢
➢ Building Blocks of C#
➢
➢ Understanding the CLI
➢
➢ Methods and Operators
We learned about the basic notion of C# programming
in the previous chapter, and now we’ll study the building
blocks of C#.
MEMBERS
The members of a class are of two types.
1. Static members: Static members belong to classes.
2. Instance members: Instance members allied to
objects (instances of classes).
51. 28 ◾ Mastering C#
The following is the outline for the kinds of members a
class can contain:
• Fields: Variables that are related to the class.
• Types: Nested types declared by the class.
• Properties: Actions related to reading and writing
named properties of the class.
• Constants: Constant values associated with the class.
• Indexers: Actions related to indexing instances of the
class like an array.
• Events: Notifications that the class can create.
• Operators: Conversions and expression operators
aided by the class.
• Constructors: Actions need to initialize instances of
the class or the class itself.
• Methods: Actions that the class can simply perform.
• Finalizers: Actions taken before the permanent dele-
tion of instances of the class.
Accessibility
Each class member has associated accessibility, which con-
trols the regions of program text that can access the member.
Six forms of possible accessibility can be summarised as
below:
1. Protected: Access is confined to this class or classes
derived from this class.
2. Private protected: Access is confined to this class or
classes derived from this type within the same assembly.
52. Building Blocks of C# ◾ 29
3. Protected internal: Access is confined to this class,
classes derived from this class, or classes within the
same assembly.
4. Public: Access isn’t limited.
5. Private: Access is limited to this class.
6. Internal: Access is confined to the current assembly.
Fields
A field is a variable that is related to a class or with an
instance of a class.
A field stated with the static modifier expounds a static
field. It precisely identifies one storage location. It is not a
problem how many instances of classes are created. Only
one copy of a static field would be there.
A field announced without the static modifier clearly
defines an instance field. Every instance of a class includes
a separate copy of all the instance fields of that class.
Methods
A method is a member that introduces a computation or
action that an object or class can perform. Static methods
are acquired through the class while instance methods are
acquired through instances of the class.
Methods may have a bunch of parameters, which includes
values or variable references given to the technique. Methods
have a return type, which describes the type of the value
computed and returned by the method. A method’s return
type is invalid if it doesn’t return a value.
53. 30 ◾ Mastering C#
Like types, methods may also have many parameters,
for which type arguments must be emphasized when the
method is called. Unlike types, the type arguments can be
understood from the arguments of a method call and need
not be given.
The signature of a method should be unique in the class
in which the method is declared. The signature of a method
always includes the name of the method, the number of
type parameters, and the modifiers, number, and types of
its parameters. The signature of a method doesn’t contain
the return type.1
Parameters
Parameters are typically used to pass values or variable
references to methods. The parameters of a method get
their exact values from the arguments specified when the
method is invoked. There are four kinds of parameters:
1. Value parameters.
2. Reference parameters.
3. Output parameters.
4. Parameter arrays.
Method Body and Local Variables
The body of a method highlights the statements that should
be executed whenever the method is called.
1 Bill Wagner and Aren Windham (2021).Program building blocks.Microsoft
54. Building Blocks of C# ◾ 31
Variables unique to the method invocation can be
declared in the method body. It is called local variables. A
local variable declaration specifies a variable name, a type
name, and possibly an initial value.
Static and Instance Methods
A static method is a kind of method declared with a static
modifier. It can only directly access static members and
can’t operate on a specific instance.
An instance method is a method declared without a
static modifier. It runs on a specific instance and can eas-
ily acquire both static and instance members. The exam-
ple on which an instance method was invoked can be
accessed like this. It’s a mistake to refer to this in a static
method.
Method Overloading
Because of method overloading, various methods in the
same class can have the same name as long as their signa-
tures are distinct. The compiler uses overload resolution
to find the exact method to invoke when compiling an
invocation of an overloaded method. Overload resolution
finds the one method that appropriately suits the argu-
ments. An error will be reported if no single best match
can be found.
The following example indicates overload resolu-
tion in effect. The comment for each of the invocations
in the UsageExample method invokes which method is
invoked.
56. Battle of Ramillies 466
The pursuit after the Action 472
Fruits of the Victory 473
Ostend and Menin taken 474
Close of the Campaign 475
C H A P T E R V I
The War in the Peninsula 476
Peterborough in San Mateo 477
His Capture of Nules 479
His Relief of Valencia 481
Galway's Advance from Portugal to Madrid 482
He is cut off from his base and marches for Valencia 483
Peninsula Campaign of 1707 484
Galway defeated at Almanza 485
Peterborough leaves the Peninsula 488
C H A P T E R V I I
Marlborough's Campaign of 1707 490
His only chance ruined by Dutch Deputies 491
His Difficulties in England 492
His Campaign of 1708 493
Ghent and Bruges betrayed to the French 494
His march to Oudenarde 495
Battle of Oudenarde 496
The Siege of Lille 503
Marlborough shifts his base to Ostend 507
Action of Wynendale 507
57. The Elector of Bavaria invests Brussels 509
Marlborough's march to relieve it 509
Fall of Lille; recovery of Ghent and Bruges 510
Capture of Minorca 511
C H A P T E R V I I I
Unsuccessful Negotiations for Peace 512
Campaign of 1709; Villars in command of the French 513
Siege of Tournay 513
The march upon Mons 515
Indecisive Action of the Allies 517
Battle of Malplaquet 517
Fall of Mons 526
C H A P T E R I X
The Peninsular Campaign of 1709; Siege of Alicante 528
Death of General Richards 529
Campaign in Portugal; Action of the Caya 529
Catalonian Campaign of 1710 530
Combat of Almenara 531
Action at Saragossa 531
Reinforcement of the French; Evacuation of Madrid 532
The Defence of Brihuega 532
British forced to Capitulate 534
Action of Villa Viciosa 534
Virtual close of the War in the Peninsula 535
Political Changes in England 536
Marlborough's Campaign of 1710 537
58. Fall of the Government in England 538
Insults offered to Marlborough 538
C H A P T E R X
The ne plus ultra of Villars 540
Death of the Emperor Joseph 541
Opening of the Campaign of 1711 541
Eugene's Army withdrawn 541
Marlborough's Stratagem for passing the French Lines 542
Despair in his Army 544
The French Lines passed 545
Perversity of the Dutch Deputies 547
Capture of Bouchain 548
Marlborough dismissed from all Public Employment 549
The Command for 1712 given to the Duke of Ormonde 549
Rage of the British Troops at their withdrawal from the Allied Army 550
Mutiny 551
Peace of Utrecht; Virtual Banishment of Marlborough 552
Honour paid to him in the Low Countries 553
C H A P T E R X I
Growth of the British Army during the War 554
Apparent defects in its Organisation 556
Opposition of Marlborough to the System of Drafting 557
The chief Causes of Waste in Men 558
Unpopularity of Colonial Service 560
Neglect of Soldiers' Welfare in England 562
The sources of Recruiting 563
59. The Recruiting Acts 564
Introduction of Short Service 566
Abuses under the Recruiting Acts 567
Desertion 569
Reforms for the Soldiers' Benefit 570
The Board of General Officers 571
Good Discipline of Marlborough's Army 572
Officers 572
Colonel Chartres 573
Hardships of Officers; Recruits 574
Remounts 575
Dishonesty of Agents 576
Contributions to Pensions 577
Infant Officers 577
Order for Abolition of Purchase 578
Marlborough's Intervention 578
General Administration; Effects of the Union with Scotland 580
Marines made Subject to the Admiralty 581
Enhanced Powers and Change of Status of the Secretary-at-War 581
The Office of Ordnance 582
Armament; Disappearance of the Pike 584
The British Musket; Marlborough's Fire-discipline 585
Drill and Discipline of the Infantry 585
The Cavalry; Shock Action; Defensive Armour 586
The Artillery 587
The Duke of Marlborough 587
60. MAPS AND PLANS
The Campaign of 1346 To face page 36
The Campaign of 1356 40
The Campaign of 1367 46
The Campaign of 1415 62
Dunbar, 1650 244
Dunkirk Dunes, 1658 272
Steenkirk, 1692 366
Landen, 1693 376
Namur, 1695 378
Schellenberg, 1704 426
Blenheim, 1704 442
Gibraltar, 1705 450
Lines of the Geete 454
Barcelona, 1705 462
Ramillies, 1706 472
Oudenarde, 1708 500
Malplaquet, 1709 524
The Campaign of 1711 548
The British Islands and Northern France: Map 1 End of volume
The Netherlands in the 18th Century Map 2
Spain and Portugal Map 3
Germany, 1600-1763 Map 4
64. C H A P T E R I
The history of the British Army is commonly supposed to begin with
the year 1661, and from the day, the 14th of February, whereon
King Charles the Second took over Monk's Regiment of Foot from the
Commonwealth's service to his own, and named it the Coldstream
Guards. The assumption is unfortunately more convenient than
accurate. The British standing army dates not from 1661 but from
1645, not from Monk's regiment but from the famous New Model,
which was established by Act of the Long Parliament and
maintained, in substance, until the Restoration. The continuity of the
Coldstream regiment's existence was practically unbroken by the
ceremony of Saint Valentine's day, and this famous corps therefore
forms the link that binds the New Model to the Army of Queen
Victoria.
But we are not therefore justified in opening the history of the
army with the birth of the New Model. The very name indicates the
existence of an earlier model, and throws us back to the outbreak of
the Civil War. There then confronts us the difficulty of conceiving
how an organised body of trained fighting men could have been
formed without the superintendence of experienced officers. We are
forced to ask whence came those officers, and where did they learn
their profession. The answer leads us to the Thirty Years' War and
the long struggle for Dutch Independence, to the English and Scots,
numbered by tens, nay, hundreds of thousands, who fought under
Gustavus Adolphus and Maurice of Nassau. Two noble regiments still
abide with us as representatives of these two schools, a standing
record of our army's 'prentice years.
But though we go back two generations before the Civil War to
find the foundation of the New Model Army, it is impossible to pause
there. In the early years of Queen Elizabeth's reign we are brought
face to face with an important period in our military history, with a
break in old traditions, an unwilling conformity with foreign
65. standards, in a word, with the renascence in England of the art of
war. For there were memories to which the English clung with
pathetic tenacity, not in Elizabeth's day only but even to the midst of
the Civil War, the memories of King Harry the Fifth, of the Black
Prince, of Edward the Third, and of the unconquerable infantry that
had won the day at Agincourt, Poitiers, and Creçy. The passion of
English sentiment over the change is mirrored to us for all time in
the pages of Shakespeare; for no nation loves military reform so
little as our own, and we shrink from the thought that if military
glory is not to pass from a possession into a legend, it must be
eternally renewed with strange weapons and by unfamiliar methods.
This was the trouble which afflicted England under the Tudors, and
she comforted herself with the immortal prejudice that is still her
mainstay in all times of doubt,
I tell thee herald,
I thought upon one pair of English legs
Did march three Frenchmen.
The origin of the new departures in warfare must therefore be
briefly traced through the Spaniards, the Landsknechts, and the
Swiss, and the old English practice must be followed to its source.
Creçy gives us no resting-place, for Edward the Third's also was a
time of military reform; the next steps are to the Battle of Falkirk,
the Statute of Winchester, and the Assize of Arms; and still the
English traditions recede before us, till at last at the Conquest we
can seize a great English principle which forced itself upon the
conquering Normans, and ultimately upon all Europe.
This then is the task that is first attempted in this book: to
follow, however briefly and imperfectly, the growth of the English as
a military power to the time of its first manifestation at Creçy, and
onward to the supreme day of Agincourt; then through the decay
under the blight of the Wars of the Roses to the revival under the
Tudors, and to the training in foreign schools which prepared the
way for the New Model and the Standing Army. The period is long,
and the conditions of warfare vary constantly from stage to stage,
66. but we shall find the Englishman, through all the changes of the art
of war unchangeable, a splendid fighting man.
The primitive national army of the English, as of other Teutonic
nations, consisted of the mass of free landowners between the ages
of sixteen and sixty; it was called in the Karolingian legislation by the
still existing name of landwehr, and known in England as the fyrd.
Its term of service was fixed by custom at two months in the year.
The force was reorganised by King Alfred or by his son through the
division of the country into military districts, every five hides of land
being required to provide an armed man at the king's summons, and
to provide him with victuals and with pay. Further, all owners of five
hides of land and upwards were required to do thane's service, that
is to say, to appear in the field as heavily-armed men at their own
charge, and to serve for the entire campaign. The organisation of
the thanes was by shires. With the conquest of England by Canute a
new military element was introduced by the establishment of the
royal body-guard, a picked force of from three to six thousand
Danish troops, which were retained by him after the rest of the army
had been sent back to Denmark, and were known as the house-
carles.
It was with an army framed on this model—the raw levies of the
fyrd and the better trained men of the body-guard—that King
Harold, flushed with the victory of Stamford Bridge, marched down
to meet the invasion of William of Normandy. The heavily-armed
troops wore a shirt of ringed or chain-mail, and a conical helmet
with a bar protecting the nose; their legs were swathed in bandages
not wholly unlike the putties of the present day, and their arms
were left free to swing the Danish axe. They carried also a sword,
five missile darts, and a shield, but the axe was the weapon that
they loved, for the Teutonic races, unlike the Latin, have ever
preferred to cut rather than to thrust. The light-armed men, who
could not afford defensive armour, came into the field with spear and
67. shield only. Yet the force was homogeneous in virtue of a single
custom, wherein lies the secret of the rise of England's prowess as a
military nation. Though the wealthy thanes might ride horses on the
march, they dismounted one and all for action, and fought, even to
the king himself, on their own feet.[2]
The force was divided into large bands or battalions, of which
the normal formation for battle was a wedge broadening out from a
front of two men to a base of uncertain number; the officers and the
better armed men forming the point, backed by a dense column of
inferior troops. It was with a single line of such wedges, apparently
from five-and-twenty to thirty of them, that Harold took up his
position to bar the advance of the Norman army. Having no cavalry,
he had resolved to stand on the defensive, and had chosen his
ground with no little skill. His line occupied the crest of a hill, his
flanks were protected by ravines, and he had dug across the plain
on his front a trench which was sufficient to check a rapid advance
of cavalry. Moreover, he had caused each battalion to ring itself
about with sharp stakes, planted into the ground at intervals with
the points slanting outwards, as a further protection against the
attack of horse.[3] The reader should take note of these stakes, for
he will find them constantly reappearing up to the seventeenth
century. There then the English waited in close compact masses, a
wall of shields within a hedge of stakes, the men of nine-and-twenty
shires under a victorious leader. There is no need to enter into
details of the battle. The English, as has been well said,[4] were
subjected to the same trial as the famous squares at Waterloo,
alternate rain of missiles and charges of cavalry, and as yet they
were unequal to it. Harold's orders had been that not a man should
move, but when the Normans, after many fruitless attacks, at last
under William's direction simulated flight, the order was forgotten
and one wing broke its ranks in headlong pursuit of the fugitives.
Possibly, if Harold had been equal to the occasion, a general advance
might have saved the day, but he made no such effort, and he was
in the presence of a man who overlooked no blunder. The pursuing
wing was enveloped by the Normans and annihilated; and then
68. William turned the whole of his force against the fragment of the line
that remained upon the hill. The English stood rooted to the ground
enduring attack after attack, until at last, worn out with fatigue and
choked with dead and wounded, they were broken and cut down,
fighting desperately to the end. Indiscipline had brought ruin to the
nation; and England now passed, to her great good fortune, under
the sway of a race that could teach her to obey.
But the English had still one more lesson to learn. Many of the
nobles, chafing against the rule of a foreigner, forsook their country
and, taking service with the Byzantine emperors, joined the famous
Varangian Guard of the Emperor Alexius Comnenus. At Durazzo they
for the second time met the Normans, under the command of Robert
Guiscard. True to their custom, they dismounted and fought on foot,
a magnificent corps, the choicest of the whole army. As at Hastings,
the Normans attacked and were repulsed, and as at Hastings, the
undisciplined English broke their ranks in pursuit. Robert Guiscard
saw his opportunity, hurled his cavalry on to their flank, and then
surrounding them on all sides cut them down, in spite of a furious
resistance, to the very last man. So perished these untameable,
unteachable spirits, the last of the unconquered English.
The Conquest was immediately followed by the institution of
knight-service. But this system, as introduced into England, differed
in many material respects from that which reigned on the continent
of Europe. It was less distinctly military in character, and far less
perfect as an organisation for national defence. The distribution of
England into knight's fees, however clearly it might be mapped out
on paper, was a work of time and not to be accomplished in a day.
Moreover, there was disloyalty to be reckoned with; for the English
were a stiff-necked people, and were not readily reconciled to the
yoke of their new masters. We find, therefore, that in very early days
the practice of accepting money in lieu of personal service crept in,
and enabled the Norman kings to fight their battles with hired
mercenaries. For this reason England has been called the cradle of
the soldier; the soldier being the man who fights for pay, solde,
69. solidus, or, as we may say by literal translation of the Latin, the man
who fights for a shilling.
The sole military interest therefore of the reigns of the Norman
kings is to follow the breakdown of the feudal system for military
purposes, and the rapid reversion to the Saxon methods and
organisation. William Rufus was the first to appeal to the English to
arm in his cause, and he did so twice with success. But in the
seventh year of his reign he played them a trick which lost him their
confidence for ever. The fyrd had furnished twenty thousand men for
service against the Norman rebels in France, and had provided every
man, at the cost of his shire, with ten shillings for the expenses of
his journey or, to use a later expression, for his conduct-money.
William met them at the rendezvous, took their two hundred
thousand shillings from them to hire mercenaries withal, and
dismissed them to their homes. This Rufus has been selected by an
historian of repute as the earliest example of an officer and a
gentleman; he should also be remembered as the first officer who
set the fashion, soon to become sadly prevalent, of misappropriating
the pay of his men. The reader should note in passing this early
instance of conduct-money, for we shall find in it the germ of the
Queen's shilling.
1106.
1116.
1125, 25th March.
The reign of Henry the First is interesting in that it shows us
English knights serving in the field against Robert of Normandy
under the walls of Tenchbrai. We find that the old order of battle,
the single line of Hastings,[5] has disappeared and has given place to
the three lines of the Byzantine school, but that, strange to say, the
Saxons have forced their peculiar principle upon the Normans. Henry
caused his English and Norman knights to dismount, formed them
into a solid battalion and placed himself at their head, keeping but
one small body still on their horses. The enemy's cavalry attacked
Henry's mounted men and dispersed them; but the phalanx of the
70. dismounted remained unbroken, pressed on against the rabble of
hostile infantry, broke it down and almost annihilated it. The victory
was hailed by the English as atonement for the defeat at Hastings,
so bitter even then was the rivalry between ourselves and our
gallant neighbours across the channel. Ten years later the English
were again in France, fighting not only against rebellious Norman
barons but against their ally, the French King Louis the Sixth. A long
and desultory war was closed by the action of Brenville. Again Henry
dismounted four hundred out of five hundred of his knights and
following the tactics of Tenchbrai won, though not without hard
fighting, a second victory. A third engagement, known as the battle
of Beaumont, saw the old English practice repeated for the third
time with signal success; but here must be noticed the entry of a
new force, a company of archers, which contributed not a little to
the fortunate issue of the day. For as the Norman cavalry came
thundering down on the English battalion, the archers moved off to
their left flank and poured in such a shower of arrows that the
horsemen were utterly overthrown. These archers must not be
confounded with the famous English bowmen of a later time, for
most probably they were merely copied, like the order of battle,
from the Byzantine model; but they taught the English the second of
two useful lessons. Henry had already discovered that dismounted
knights could hold their own against the impetuous cavalry of
France; he now learned that the attack of horse could be weakened
almost to annihilation by the volley of archers. This, at a time when
cavalry held absolute supremacy in war, was a secret of vital
importance, a secret indeed which laid the foundation of our military
power. Henry, evidently alive to it, encouraged the practice of
archery by ordaining that, if any man should by accident slay
another at the butts, the misadventure should not be reckoned to
him as a crime.
1141.
The miserable reign of Stephen, so unsatisfactory to the general
historian, possesses through the continued development of English
71. tactical methods a distinct military interest. The year 1138 is
memorable for the Battle of the Standard, the first of many actions
fought against the Scots, and typical of many a victory to come. The
English knights as usual fought on foot, and aided by archers made
havoc of the enemy. Here is already the germ of the later infantry;
we shall find lances and bows give way to pikes and muskets, but
for five whole centuries we shall see the foot compounded of two
elements, offensive and defensive, until the invention of the bayonet
slowly welds them into one. At the battle of Lincoln, on the other
hand, we find the defensive element acting alone and suffering
defeat, though not disgrace; for the dismounted knights who stood
round Stephen fought with all the old obstinacy and yielded only to
overwhelming numbers. Thus, though two generations had passed
since the Conquest, the English methods of fighting were still in full
vigour, and the future of English infantry bade fair to be assured.
Nor was the cavalry neglected; for amid all the earnest of this
turbulent reign there was introduced the mimic warfare known as
the tournament. This was an invention of the hot-blooded,
combative French, and had been originally so close an imitation of
genuine battle, that the Popes had intervened to prohibit the
employment therein of any but blunt weapons. The tournament
being not a duel of man against man, but a contest of troop against
troop, was a training not only for individual gallantry, but for tactics,
drill, discipline, and leadership; victory turning mainly on skilful
handling and on the preservation of compact order. Thus by the
blending of English foot and Norman horse was laid, earlier than in
any other country of Europe, the foundation of an army wherein
both branches took an equal share of work in the day of action.
1181.
The next in succession of our kings was a great soldier and a
great administrator, yet the work that he did for the army was
curiously mixed. Engaged as he was incessantly in war, he felt more
than others the imperfection of the feudal as a military system. The
number of knights that could be summoned to his standard was very
72. small, and was diminished still further by constant evasion of
obligations. He therefore regulated the commutation of personal
military service for payment in money, and formed it, under the old
name of scutage, into a permanent institution. Advantage was
generally taken of the system, and with the money thus obtained he
took Brabançon mercenaries, the prototypes of the landsknechts of a
later time, permanently into his pay. When he needed the feudal
force to supplement these mercenaries, he fell back on the device of
ordering every three knights to furnish and equip one of their
number for service; and finally, driven to extremity, he re-established
the old English fyrd as a National Militia by the Assize of Arms. This,
the earliest of enactments for the organisation of our national forces,
and the basis of all that followed down to the reign of Philip and
Mary, contained the following provisions:—
Every holder of one knight's fee shall have a coat of mail,[6] a
helmet, a shield, and a lance; and every knight as many coats of
mail, helmets, shields, and lances as there are fees in his domain.
Every free layman having in chattels or rent to the value of
sixteen marks shall keep the same equipment.
Every free layman having in chattels or rent ten marks, shall
keep an habergeon,[7] a chaplet[8] of iron, and a lance.
All burgesses and the whole community of freemen shall have a
wambais,[9] a chaplet of iron, and a lance.
It is noteworthy that neither the bow nor the axe appear in this
list of the national weapons, an omission for which it is difficult to
account, since the bow was evidently in full use at the time. Possibly
the temptation to employ it for purposes of poaching may have been
so strong as to make the authorities hesitate to enjoin the keeping
of a bow in every poor freeman's house. The influence of the
poacher will be found equally potent when the time comes for the
introduction of firearms.
73. Richard the Lion-Heart, like his predecessors, preferred to
employ mercenaries for his wars, while even the knights who
accompanied him to the Crusade were in receipt of pay. Were it not
that his achievements in the Holy Land had left little mark on English
military history they would be well worthy of a detailed narrative, for
Richard was beyond dispute a really great soldier, a good engineer,
and a remarkably able commander. The story of his march from
Joppa to Jerusalem and of his victory at Arsouf is known to few, but
it remains to all time an example of consummate military skill. A
mixed force compounded of many nations is never very easy to
control, and it was doubly difficult when the best of it was composed
of knights who hated the very name of subordination. Yet it was with
such material, joined to a huge body of half-disciplined infantry, that
Richard executed a flank march in the presence of the most
formidable of living generals, and repulsed him brilliantly when he
ventured, at an extremely trying moment, to attack. The plan of the
campaign, the arrangements and orders for the march, the drill and
discipline imposed on the knights, and the handling of the troops in
the action are all alike admirable. Yet, as has been already stated,
the lessons of the Crusades wrought little influence in England,
mainly because she had already learned from her own experience
the value of a heavily armed infantry, and of the tactical combination
of missile and striking weapons. In the rest of Europe they were for
a time remembered but very soon forgotten;[10] and England was
then once more left alone with her secret.
Two small relics of the Crusades must however find mention in
this place. The first is the employment of the cross as a mark for
distinguishing the warriors of different nations, which became in due
time the recognised substitute for uniform among European soldiers.
Each nation took a different colour for its cross, that of the English
being at first white, which, curiously enough, is now the regular
facing for English regiments of infantry. The second relic is the
military band which, there seems to be little doubt, was copied from
the Saracens. In their armies trumpets and drums, the latter
decidedly an Oriental instrument, were used to indicate a rallying-
74. point; for though at ordinary times the standards sufficed to show
men the places of their leaders, yet in the dust of battle these were
often hidden from sight; and it was therefore the rule to gather the
minstrels (such was the English term) around the standards, and bid
them blow and beat strenuously and unceasingly during the action.
The silence of the band was taken as a proof that a battalion had
been broken and that the colours were in danger; and the fashion
lasted so long that even in the seventeenth century the bandsmen in
all pictures of battles are depicted, drawn up at a safe distance and
energetically playing.
1214.
The reign of King John accentuated still further the weak points
of the English feudal system as a military organisation. The principle
introduced by the Conqueror had been to claim for the sovereign
direct feudal authority over every landholder in the country, suffering
no intermediate class of virtually independent vassals, such as
existed in France, to intercept the service of those who owed duty to
him. Of the advantages of this innovation mention shall presently be
made elsewhere, but at this point it is necessary to dwell only on its
military defects. The whole efficiency of the feudal system turned on
the creation of a caste of warriors; and such a caste can obviously
be built up only by the grant of certain exclusive privileges. The
English knights possessed no such privileges. There were no special
advantages bound up with the tenure of a fief. Far from enjoying
immunity from taxation, as in France and Germany, the knights were
obliged to pay not only the imposts required of all classes, but
scutage into the bargain. Again the winning of a knight's fee lay
open to all ranks of freemen, so that it could not be regarded as the
hereditary possession of a proud nobility. Yet again, the grant of the
honour of knighthood was the exclusive right of the sovereign, who
converted it simply into an instrument of extortion. Briefly, there was
no inducement to English knights faithfully to perform their service;
the sovereign took everything and gave nothing; and at last they
would endure such oppression no longer. When John required a
75. feudal force, in the year 1205, he was obliged to arrange that every
ten knights should equip one of their number for service. Moreover,
the knights who did serve him showed no merit; the English
contingent at Bouvines having covered itself with anything but glory.
Finally, came mutiny and rebellion and the Great Charter, wherein
the express stipulation that fiefs should be both alienable and
divisible crushed all hopes of an hereditary caste of warriors for ever.
1252.
After the Charter the national force was composed nominally of
three elements, the tenants in chief with their armed vassals, the
minor tenants in chief, and the freemen subject to the Assize of
Arms, the last two being both under the orders of the sheriffs. It
made an imposing show on paper, but was difficult to bring efficient
into the field. No man was more shameless than Henry the Third in
forcing knighthood, for the sake of the fees, upon all free
landholders whom he thought rich enough to support the dignity;
yet, when the question became one not of money but of armed
men, he was forced to fall back on the same resource as his greater
namesake. He simply issued a writ for the enforcement of the Assize
of Arms, and ordered the sheriffs to furnish a fixed contingent of
men-at-arms, to be provided by the men of the county who were
subject thereto.
1282.
The defects of feudal influence in military matters were now so
manifest, that Edward the First tried hard to do away with them
altogether. Strictly speaking the feudal force was summoned by a
special writ addressed to the barons, ordering them to appear with
their due proportion of men and horses, and by similar directions to
the sheriffs to warn the tenants in chief within their bailiwicks. The
system was however, so cumbrous and ineffective that Edward
superseded it by issuing commissions to one or two leading men of
the county to muster and array the military forces. These
76. Commissions of Array, as they were called, will come before us again
so late as in the reign of Charles the First.
1285.
But, like all his predecessors, Edward was careful to cherish the
national militia which had grown out of the fyrd. The Statute of
Winchester re-enacted the Assize of Arms and redistributed the force
into new divisions armed with new weapons. The wealthiest class of
freemen was now required to keep a hauberk[11] of iron, a sword
and a knife, and a horse. The two lower classes were now
subdivided into four, whereof the first was to keep the same arms as
the wealthiest, the horse excepted; the second a sword, bow and
arrows, and a knife; the third battle-axes, knives, and other less
weapons, in which last are included bills;[12] and the rest bows and
arrows, or if they lived in the forest, bows and bolts, the latter being
probably less deadly to the king's deer than arrows. Here then was
the axe of Harold's day revived, and the archers established by
statute. It is evident, from the fact that they wore no defensive
armour, that the archers were designed to be light infantry, swift and
mobile in their limbs, skilful and deadly with their weapons. The
name of Edward the First must be ever memorable in our history for
the encouragement that he gave to the long-bow; but we seek in
vain for the man, if such there was, who founded the tradition, still
happily strong among us, that the English whatever their missile
weapon shall always be good shots. Even at the siege of Messina by
Richard the First the archers drove the Sicilians from the walls; for
no man could look out of doors but he would have an arrow in his
eye before he could shut it.
1297.
1298.
The bowmen had not long been a statutory force before they
were called upon for active service. The defeat of the English by
William Wallace at Cambuskenneth had summoned Edward from
France to take the field in person against the Scots; and he met
77. them on the field of Falkirk. The Scottish army consisted for the
most part of infantry armed with pikes, not yet the long pikes of
eighteen feet which they were to wield so gallantly under Gustavus
Adolphus, but still a good and formidable weapon. Wallace drew
them up behind a marsh in four circular battalions ringed in with
stakes, posting his light troops, which were armed principally with
the short-bow, in the intervals between them, and his one weak
body of horse in rear. The English knights were formed as usual in
column of three divisions, vanguard, battle and rearguard, and with
them was a strong force of archers. Untrue to its old traditions, the
English cavalry did not dismount, but galloped straight to the attack.
The first division plunged headlong into the swamp (for the
mediæval knight, in spite of a hundred warnings, rarely took the
trouble to examine the ground before him), did no execution, and
suffered heavy loss. The second division, under the Bishop of
Durham, then skirted the swamp and came in sight of the Scottish
horse. The Bishop hesitated and called a halt. Back to your mass,
Bishop, answered one contemptuous knight. His comrades charged,
dispersed the Scottish cavalry, and drove away the archers between
the pikemen; but the four battalions stood firm and unbroken, and
the knights surged round them in vain. Then the king brought up the
archers and the third division of horse. Pushing the archers forward,
he held the cavalry back in support until an incessant rain of arrows
had riddled the Scottish battalions through and through, and then
hurling the knights forward into the broken ranks, he fairly swept
them from the field. It was the old story, heavy fire of artillery
followed by charges of cavalry, the training of the Scots as Hastings
had been of the English, for the trial of Waterloo.
1314.
It is interesting to note that Edward made an effort even then
for the constitutional union of the two countries which had so
honourably lost and won the day at Falkirk, but he was four
centuries before his time. The war continued with varying fortune
during the ensuing years. The maker of the English archers died,
78. and under his feeble son the English army learned at Bannockburn
an ignominious lesson in tactics. The Scotch army, forty thousand
strong, was composed principally of pikemen, who were drawn up,
as at Falkirk, in four battalions, with the burn in their front and
broken ground on either flank. Their cavalry, numbering a thousand,
a mere handful compared to the host of the English men-at-arms,
was kept carefully in hand. Edward opened the action by advancing
his archers to play on the Scottish infantry, but omitted to support
them; and Bruce, seeing his opportunity, let loose his thousand
horse on their flank and rolled them up in confusion. The English
cavalry then dashed in disorder against the serried pikes, failed,
partly from want of space and partly from bad management, to
make the slightest impression on them, and were driven off in
shameful and humiliating defeat. So the English learned that their
famous archers could not hold their own against cavalry without
support,[13] and they took the lesson to heart. The old system of
dismounting the men-at-arms had been for the moment abandoned
with disastrous results; the man who was to revive it had been born
at Windsor Castle just two years before the fight.
1327.
1333.
Thirteen years later this boy ascended the throne of England as
King Edward the Third, and almost immediately marched with a
great host against the Scots. The campaign came to an end without
any decisive engagement, but on the one occasion when an action
seemed imminent, the English men-at-arms dismounted and put off
their spurs after the old English fashion. Peace was made, but only
to be broken by the Scots, and then Edward took his revenge for
Bannockburn at Halidon Hill. The English men-at-arms alighted from
their horses, and were formed into four battalions, each of them
flanked by wings of archers, the identical formation adopted two
centuries later for the pikemen and musketeers. The Scots, whose
numbers were far superior, were also formed on foot in four
battalions, but without the strength of archers. And then, says the
79. old historian,[14] the English minstrels blew aloud their trumpets
and sounded their pipes and other instruments of martial music, and
marched furiously to meet the Scots. The archers shot so thick and
fast that the enemy, unable to endure it, broke their ranks, and then
the English men-at-arms leaped on to their horses for the pursuit.
The Scotch strove gallantly to rally in small bodies, but they were
borne down or swept away; they are said to have lost ten thousand
slain out of sixty thousand that entered the battle.
The mounting of the men-at-arms for the pursuit gave the
finishing touch to the English tactical methods, and the nation was
now ready for war on a grander scale. Moreover, there was playing
round the knees of good Queen Philippa a little boy of three years
old who was destined to be the victor of Poitiers. It is therefore time,
while the quarrel which led to the Hundred Years' War is maturing,
to observe the point to which two centuries and a half of progress
had brought English military organisation.
Authorities.—By far the best, so far as I know the only, account of the
rise of English tactics and of English military power is to be found in Die
Entwickelung des Kriegswesens in der Ritterzeit, by Major-General Köhler, vol.
ii. pp. 356 sq., and vol. v. pp. 97 sq., a work to which my obligations must be
most gratefully acknowledged. The authorities are faithfully and abundantly
quoted. Freeman's Norman Conquest, Mr. J. H. Round's Feudal England,
Hewitt's Ancient Armour, Oman's Art of War in the Middle Ages, Grose's
Military Antiquities, and Rymer's Fœdera are authorities which will occur to
every one, as also the Constitutional Histories of Hallam, Stubbs, and Gneist.
81. Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com