SlideShare a Scribd company logo
Net 40 Generics Beginners Guide Sudipta
Mukherjee download
https://ebookbell.com/product/net-40-generics-beginners-guide-
sudipta-mukherjee-2518856
Explore and download more ebooks at ebookbell.com
Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Aspnet 40 In Practice Pappsc Daniele Bochicchio Stefano Mostarda
https://ebookbell.com/product/aspnet-40-in-practice-pappsc-daniele-
bochicchio-stefano-mostarda-2327468
Introducing Net 40 With Visual Studio 2010 Experts Voice In Net 1st
Edition Alex Mackey
https://ebookbell.com/product/introducing-net-40-with-visual-
studio-2010-experts-voice-in-net-1st-edition-alex-mackey-2527400
Aspnet 40 Projects Covers Net 35 And Net 40 Codes Black Book Kogent
Learning Solutions Inc
https://ebookbell.com/product/aspnet-40-projects-covers-net-35-and-
net-40-codes-black-book-kogent-learning-solutions-inc-231815770
Aspnet 40 Programming Joydip Kanjilal
https://ebookbell.com/product/aspnet-40-programming-joydip-
kanjilal-170487994
Sams Teach Yourself Aspnet 40 In 24 Hours Complete Starter Kit
Mitchell
https://ebookbell.com/product/sams-teach-yourself-
aspnet-40-in-24-hours-complete-starter-kit-mitchell-21995470
Pro Dynamic Net 40 Applications Datadriven Programming For The Net
Framework 1st Edition Carl Ganz Jr
https://ebookbell.com/product/pro-dynamic-net-40-applications-
datadriven-programming-for-the-net-framework-1st-edition-carl-ganz-
jr-2309974
Pro Dynamic Net 40 Applications 1st Edition Carl Ganz Jr
https://ebookbell.com/product/pro-dynamic-net-40-applications-1st-
edition-carl-ganz-jr-50640784
Comdex Net Programming Course Kit Covering Net Framework 40 Vb 2010 C
2010 And Aspnet 40 Vikas Gupta
https://ebookbell.com/product/comdex-net-programming-course-kit-
covering-net-framework-40-vb-2010-c-2010-and-aspnet-40-vikas-
gupta-231677358
Pro Vb 2010 And The Net 40 Platform 1st Edition Andrew Troelsen
https://ebookbell.com/product/pro-vb-2010-and-the-net-40-platform-1st-
edition-andrew-troelsen-2098406
Net 40 Generics Beginners Guide Sudipta Mukherjee
Net 40 Generics Beginners Guide Sudipta Mukherjee
.NET 4.0 Generics
Beginner's Guide
Enhance the type safety of your code and create applications
easily using Generics in the .NET 4.0 Framework
Sudipta Mukherjee
BIRMINGHAM - MUMBAI
.NET 4.0 Generics
Beginner's Guide
Copyright © 2012 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system,
or transmitted in any form or by any means, without the prior written permission of the
publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the
information presented. However, the information contained in this book is sold without
warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers
and distributors will be held liable for any damages caused or alleged to be caused directly or
indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals. However,
Packt Publishing cannot guarantee the accuracy of this information.
First published: January 2012
Production Reference: 1190112
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-84969-078-2
www.packtpub.com
Cover Image by Asher Wishkerman (a.wishkerman@mpic.de)
Credits
Author
Sudipta Mukherjee
Reviewers
Atul Gupta
WEI CHUNG, LOW
Antonio Radesca
Acquisition Editor
David Barnes
Lead Technical Editor
Meeta Rajani
Technical Editors
Veronica Fernandes
Copy Editor
Laxmi Subramanian
Project Coordinator
Vishal Bodwani
Proofreader
Joanna McMahon
Indexer
Monica Ajmera Mehta
Rekha Nair
Graphics
Manu Joseph
Production Coordinator
Alwin Roy
Cover Work
Alwin Roy
Net 40 Generics Beginners Guide Sudipta Mukherjee
Foreword
It is my pleasure to write the foreword to a book which will introduce you to the world of
generic programming with C# and other .NET languages. You will be able to learn a lot from
this book, as it introduces you to the elegant power of generic programming in C#. Through
it, you will become a better C# programmer, and a better programmer in all future languages
you might choose to use.
It is now almost 10 years since .NET Generics was first described in publications from
Microsoft Research, Cambridge, a project I was able to lead and contribute to, and six
years since it was released in product form in C# 2.0. In this foreword, I would like to
take a moment to review the importance of .NET Generics in the history of programming
languages, and the way it continues to inspire a new generation of programmers.
When we began the design of C# and .NET Generics, generic programming was not new.
However, it was considered to be outside the mainstream, and attempts to change that
with C++ templates and proposals for Java Generics were proving highly problematic for
practitioners. At Microsoft Research, we pride ourselves on solving problems at their core.
The three defining core features of .NET Generics as we designed them were efficient
generics over value types with code generation and sharing managed by the virtual machine,
reified run-time types, and language neutrality.
These technical features are now widely acknowledged to represent the "right" fundamental
design choices for programming language infrastructure. They are not easy to design or
build, and they are not easy to deliver, and when Microsoft Research embarked on this
project, we believe we put the .NET platform many years ahead of its rivals. The entire credit
goes to Microsoft and people such as Bill Gates, Eric Rudder, and Anders Hejlsberg for taking
the plunge to push this into our range of programming languages. However, without the
prototyping, research, engineering, and incessant advocacy by Microsoft Research, C# and
.NET Generics would never be in their current form.
Let's take some time to examine why this was important. First, .NET Generics represents
the moment where strongly typed and functional programming entered the mainstream.
.NET Generics enabled C# to become more functional (through LINQ, Lambdas, and generic
collections), and it enabled a new class of strongly typed, fully functional .NET languages
(such as F#) to thrive. Further, .NET Generics also enabled new key programming techniques,
such as Async programming in F# 2.0 and C# 5.0, and Rx programming for reactive systems.
Even though you may not realize it, you'll have learned a lot of functional programming by
the end of this book.
Next, .NET Generics categorically proved that strongly typed object-oriented programming
can integrate seamlessly with generic programming. It is hard to describe the extent to which
.NET Generics managed to defeat the "object fundamentalists" of the 1990s (who want
a world where there is nothing but classes). These people, many still occupying powerful
positions in the software industry, seemed satisfied with a world where programmers are
less productive, and programs less efficient, in the name of orthodoxy. Today, no practicing
programmer or language designer with experience of .NET Generics would design a strongly
typed programming language that does not include Generics. Further, almost every .NET
API now features the use of .NET Generics, and it has become an essential weapon in the
programmer's toolkit for solving many problems.
Finally, and for me most importantly, .NET Generics represents the victory of pragmatic
beauty over pragmatic ugliness. In the eyes of many, alternative solutions to the problem
of generic programming such as Java's "erasure" of Generics are simply unpleasant "hacks".
This leads to reduced productivity when using those languages. In contrast, .NET Generics
is perhaps the most smoothly integrated advanced programming language feature ever
constructed. It integrates with reflection, .NET NGEN pre-compilation, debugging, and run-
time code generation. I've had many people e-mail me to say that .NET Generics is their
favorite programming language feature. That is what language research is all about.
I trust you will learn a great deal from this book, and enjoy the productivity that comes from
C#, and .NET languages such as F#.
Dr. Don Syme
Principal Research,
Microsoft Research, Cambridge, U.K.
Generic types are more than just lists of T. Functional programmers have known this for a
long time. C++ programmers who use templates knew this too. But 10 years ago when Don
Syme and I first designed and prototyped the Generics feature of the .NET run-time, most
mainstream developers were constrained by the rudimentary type systems of languages
such as Visual Basic and Java, writing type-generic code only by resorting to casting tricks
or worse. In that space, it's hard to conceive of myriad uses of generic types beyond lists
and simple collections, and it's fair to say that there was some resistance to our design!
Fortunately, some forward thinkers in Microsoft's .NET run-time team regarded Generics
in managed languages as more than an academic indulgence, and committed substantial
resources to completing a first-class implementation of Generics that is deeply embedded in
the run-time languages and tools.
We've come a long way in 10 years! Managed code frameworks make liberal use of generic
types, ranging from obvious collection types such as List and Dictionary, through `action'
types such as Func and IEnumerable, to more specialized use of Generics such as Lazy
initialization. Blogs and online forums are full of discussions on sophisticated topics such as
variance and circular constraints. And if it weren't for Generics, it's hard to see how newer
language features such as LINQ, or even complete languages such as F#, could have got off
the ground.
Coming back, Generics really does start with List<T>, and this book sensibly begins from
there. It then takes a leisurely tour around the zoo of generic types in the .NET Framework
and beyond, to Power Collections and C5. The style is very much one of exploration: the
reader is invited to experiment with Generics, prodding and poking a generic type through
its methods and properties, and thereby understand the type and solve problems by using it.
As someone whose background is in functional programming, in which the initial experience
is very much like experimenting with a calculator, I find this very appealing. I hope you like it
as much as I do.
Andrew Kennedy
Microsoft Research, Cambridge, U.K.
About the Author
Sudipta Mukherjee was born in Kolkata and migrated to Bangalore, the IT capital of India,
to assume the position of a Senior Research Engineer in a renowned research lab. He is an
Electronics Engineer by education and a Computer Engineer/Scientist by profession and
passion. He graduated in 2004 with a degree in Electronics and Communication Engineering.
He has been working with .NET Generics since they first appeared in the .NET Framework 2.0.
He has a keen interest in data structure, algorithms, text processing, natural language
processing ,programming language, tools development, and game development.
His first book on data structure using the C programming language has been well received.
Parts of the book can be read on Google Books at http://goo.gl/pttSh. The book was
also translated into Simplified Chinese available on Amazon at http://goo.gl/lc536.
He is an active blogger and an open source enthusiast. He mainly blogs about programming
and related concepts at sudipta.posterous.com. Inspired by several string processing
methods in other languages, he created an open source string processing framework for
.NET, available for free at stringdefs.codeplex.com.
He lives in Bangalore with his wife. He can be reached via e-mail at sudipto80@yahoo.com
and via Twitter at @samthecoder.
Acknowledgement
Books like this cannot be brought to life by the author alone. I want to take this opportunity
to thank all the people who were involved in this book in any way.
First of all, I want to thank Microsoft Research for bringing Generics into the .NET
Framework. Great work guys. I have used STL in C++ and Collections in Java. But I can say
without being biased that Generics in .NET is the smartest implementation of generic
programming paradigm that I have ever come across. Without that, I wouldn't have anything
to write about.
I owe a big "Thank You" to the Senior Acquisition Editor and Publisher David Barnes at Packt
Publishing for offering me this opportunity to write for them. I want to thank Vishal Bodwani
and Meeta Rajani, also from Packt Publishing, for their great support. Everytime I missed a
deadline, they helped me get back on track. Thanks for bearing with me. Last but not the
least, I want to thank my Technical Editors Snehal and Veronica who painstakingly corrected
all the mistakes, did all the formatting, without which the book would not have been
possible. Thanks a lot.
I have no words to express my gratitude towards Don and Andrew for taking time off to read
the manuscript and their kind words. Thank you Don. Thank you Andrew.
I want to thank all the reviewers of the book. Thanks for all your great feedback. It really
made the book better.
My wife, Mou, motivated me to write this book. She stood by me when I needed her
throughout all these months. Thank you sweetheart. Last but not the least, I can't thank
my mom Dipali and dad Subrata enough for finding the love of my life and always being
supportive. Thank you mom. Thank you dad.
About the Reviewers
Atul Gupta, is currently a Principal Technology Architect at Infosys' Microsoft Technology
Center. He also has close to 15 years of experience working on Microsoft technologies.
His expertise spans user interface technologies, and he currently focuses on Windows
Presentation Foundation (WPF) and Silverlight technologies. Other technologies of interest
to him are Touch (Windows 7), Deepzoom, Pivot, Surface, and Windows Phone 7.
He recently co-authored the book "ASP.NET 4 Social Networking", Packt Publishing (http://
www.packtpub.com/asp-net-4-social-networking/book). His prior interest areas
were COM, DCOM, C, VC++, ADO.NET, ASP.NET, AJAX, and ASP.NET MVC.
He has also authored papers for industry publications and websites, some of which are
available on Infosys' Technology Showcase (http://www.infosys.com/microsoft/
resource-center/pages/technology-showcase.aspx). Along with colleagues from
Infosys, Atul is also an active blogger (http://www.infosysblogs.com/microsoft).
Being actively involved in professional Microsoft online communities and developer forums,
Atul has received Microsoft's Most Valuable Professional award for multiple years in a row.
WEI CHUNG, LOW, a Technical Lead in BizTalk and .NET, and a MCT, MCPD, MCITP, MCTS,
and MCSD.NET, works with ResMed (NYSE: RMD), at its Kuala Lumpur, Malaysia campus. He
is also a member of PMI, certified as a PMP. He started working on Microsoft .NET very early
on and has been involved in development, consultation, and corporate training in the areas
of business intelligence, system integration, and virtualization. He has been working for the
Bursa Malaysia (formerly Kuala Lumpur Stock Exchange) and Shell IT International previously,
which prepared him with rich integration experience across different platforms.
He strongly believes that great system implementation delivers precious value to the
business, and integration of various systems across different platforms shall always be a part
of it, just as people from different cultures and diversities are able to live in harmony in most
of the major cities.
Antonio Radesca has over 15 years of programming experience. He has a degree in
Computer Science and is interested in architectures, programming languages, and enterprise
development. He has worked at some of the most important Italian companies, especially
at Microsoft .NET Framework as a Developer and an Architect. His expertise spans .NET
programming to mobile development on iOS, Android, and Windows Phone.
www.PacktPub.com
Support files, eBooks, discount offers and more
You might want to visit www.PacktPub.com for support files and downloads related to
your book.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub
files available? You can upgrade to the eBook version at www.PacktPub.com and as a print
book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
service@packtpub.com for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up
for a range of free newsletters and receive exclusive discounts and offers on Packt books
and eBooks.
http://PacktLib.PacktPub.com
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book
library. Here, you can access, read and search across Packt's entire library of books.
Why Subscribe?
‹
‹ Fully searchable across every book published by Packt
‹
‹ Copy and paste, print and bookmark content
‹
‹ On demand and accessible via web browser
Free Access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access
PacktLib today and view nine entirely free books. Simply use your login credentials for
immediate access.
Table of Contents
Preface 1
Chapter 1: Why Generics? 7
An analogy 8
Reason 1: Generics can save you a lot of typing 8
Reason 2: Generics can save you type safety woes, big time 10
What's the problem with this approach? 12
Reason 3: Generics leads to faster code 14
Reason 4: Generics is now ubiquitous in the .NET ecosystem 15
Setting up the environment 15
Summary 17
Chapter 2: Lists 19
Why bother learning about generic lists? 20
Types of generic lists 20
Checking whether a sequence is a palindrome or not 22
Time for action – creating the generic stack as the buffer 24
Time for action – completing the rest of the method 26
Designing a generic anagram finder 28
Time for action – creating the method 29
Life is full of priorities, let's bring some order there 32
Time for action – creating the data structure for the prioritized shopping list 33
Time for action – let's add some gadgets to the list and see them 34
Time for action – let's strike off the gadgets with top-most priority
after we have bought them 37
Time for action – let's create an appointment list 40
Live sorting and statistics for online bidding 41
Time for action – let's create a custom class for live sorting 42
Why did we have three LinkedList<T> as part of the data structure? 47
An attempt to answer questions asked by your boss 47
Table of Contents
[ ii ]
Time for action – associating products with live sorted bid amounts 47
Time for action – finding common values across different bidding amount lists 50
You will win every scrabble game from now on 52
Time for action – creating the method to find the character histogram of a word 52
Time for action – checking whether a word can be formed 53
Time for action – let's see whether it works 54
Trying to fix an appointment with a doctor? 56
Time for action – creating a set of dates of the doctors' availability 57
Time for action – finding out when both doctors shall be present 58
Revisiting the anagram problem 60
Time for action – re-creating the anagram finder 60
Lists under the hood 64
Summary 65
Chapter 3: Dictionaries 67
Types of generic associative structures 68
Creating a tag cloud generator using dictionary 69
Time for action – creating the word histogram 69
Creating a bubble wrap popper game 73
Time for action – creating the game console 74
Look how easy it was! 77
How did we decide we need a dictionary and not a list? 78
Let's build a generic autocomplete service 79
Time for action – creating a custom dictionary for autocomplete 79
Time for action – creating a class for autocomplete 82
The most common pitfall. Don't fall there! 88
Let's play some piano 88
Time for action – creating the keys of the piano 89
How are we recording the key strokes? 94
Time for action – switching on recording and playing recorded keystrokes 95
How it works? 96
C# Dictionaries can help detect cancer. Let's see how! 97
Time for action – creating the KNN API 97
Time for action – getting the patient records 102
Time for action – creating the helper class to read a delimited file 103
Time for action – let's see how to use the predictor 104
Tuples are great for many occasions including games 105
Time for action – putting it all together 106
Why have we used Tuples? 113
How did we figure out whether the game is over or not? 115
Summary 116
Table of Contents
[ iii ]
Chapter 4: LINQ to Objects 117
What makes LINQ? 118
Extension methods 118
Time for action – creating an Extension method 119
Time for action – consuming our new Extension method 120
Check out these guidelines for when not to use Extension methods 122
Object initializers 122
Collection initializers 123
Implicitly typed local variables 124
Anonymous types 124
Lambda expressions 125
Functors 125
Predicates 127
Actions 127
Putting it all together, LINQ Standard Query Operators 128
Time for action – getting the LINQPad 129
Restriction operators 131
Where() 131
Time for action – finding all names with *am* 131
Time for action – finding all vowels 132
Time for action – finding all running processes matching a Regex 133
Time for action – playing with the indexed version of Where() 134
Time for action – learn how to go about creating a Where() clause 135
Projection operators 136
Select() 137
Time for action – let's say "Hello" to your buddies 137
Making use of the overloaded indexed version of Select() 138
Time for action – radio "Lucky Caller" announcement 138
SelectMany() 140
Time for action – flattening a dictionary 140
Partitioning operators 141
Take() 141
Time for action – leaving the first few elements 142
TakeWhile() 143
Time for action – picking conditionally 143
Skip() 145
Time for action – skipping save looping 145
SkipWhile() 146
Ordering operators 147
Reverse() 147
Time for action – reversing word-by-word 147
Time for action – checking whether a given string is a palindrome or not 148
OrderBy() 149
Table of Contents
[ iv ]
Time for action – sorting names alphabetically 149
Time for action – sorting 2D points by their co-ordinates 151
OrderByDescending() 152
ThenBy() 152
Time for action – sorting a list of fruits 152
What's the difference between a sequence of OrderBy().OrderBy() and OrderBy().ThenBy()? 154
ThenByDescending() 154
Grouping operator 154
GroupBy() 154
Time for action – indexing an array of strings 154
Time for action – grouping by length 156
Set operators 158
Intersect() 158
Time for action – finding common names from two names' lists 159
Union() 160
Time for action – finding all names from the list, removing duplicates 161
Concat() 162
Time for action – pulling it all together including duplicates 162
Except() 162
Time for action – finding all names that appear mutually exclusively 163
Distinct() 164
Time for action – removing duplicate song IDs from the list 165
Conversion operators 166
ToArray() 167
Time for action – making sure it works! 167
ToList() 168
Time for action – making a list out of IEnumerable<T> 168
ToDictionary() 169
Time for action – tagging names 169
ToLookup() 171
Time for action – one-to-many mapping 171
Element operators 172
First() 172
Time for action – finding the first element that 172
satisfies a condition 172
How First() is different from Single()? 173
FirstOrDefault() 173
Time for action – getting acquainted with FirstOrDefault() 173
Last() 174
LastOrDefault() 174
SequenceEquals() 174
Time for action – checking whether a sequence is palindromic 174
ElementAt() 175
Time for action – understanding ElementAt() 176
ElementAtOrDefault() 177
Table of Contents
[ v ]
DefaultIfEmpty() 177
Time for action – check out DefaultIfEmpty() 178
Generation operators 178
Range() 178
Time for action – generating arithmetic progression ranges 179
Time for action – running a filter on a range 179
Repeat() 180
Time for action – let's go round and round with Repeat() 180
Quantifier operators 181
Single() 181
Time for action – checking whether there is only one item matching this pattern 182
SingleOrDefault() 183
Time for action – set to default if there is more than one matching elements 183
Any() 184
Time for action – checking Any() 185
All() 186
Time for action – how to check whether all items match 186
a condition 186
Merging operators 187
Zip() 187
Summary 188
Chapter 5: Observable Collections 189
Active change/Statistical change 190
Passive change/Non-statistical change 191
Data sensitive change 191
Time for action – creating a simple math question monitor 193
Time for action – creating the collections to hold questions 194
Time for action – attaching the event to monitor the collections 195
Time for action – dealing with the change as it happens 197
Time for action – dealing with the change as it happens 199
Time for action – putting it all together 200
Time for action – creating a Twitter browser 201
Time for action – creating the interface 202
Time for action – creating the TweetViewer user control design 203
Time for action – gluing the TweetViewer control 205
Time for action – putting everything together 208
Time for action – dealing with the change in the list of names in the first tab 209
Time for action – a few things to beware of at the form load 210
Time for action – things to do when names get added or deleted 211
Time for action – sharing the load and creating a task for each BackgroundWorker 213
Time for action – a sample run of the application 216
Summary 219
Table of Contents
[ vi ]
Chapter 6: Concurrent Collections 221
Creating and running asynchronous tasks 222
Pattern 1: Creating and starting a new asynchronous task 222
Pattern 2: Creating a task and starting it off a little later 222
Pattern 3: Waiting for all running tasks to complete 222
Pattern 4: Waiting for any particular task 222
Pattern 5: Starting a task with an initial parameter 222
Simulating a survey (which is, of course, simultaneous by nature) 223
Time for action – creating the blocks 223
Devising a data structure for finding the most in-demand item 227
Time for action – creating the concurrent move-to-front list 228
Time for action – simulating a bank queue with multiple tellers 234
Time for action – making our bank queue simulator more useful 239
Be a smart consumer, don't wait till you have it all 241
Exploring data structure mapping 242
Summary 243
Chapter 7: Power Collections 245
Setting up the environment 246
BinarySearch() 248
Time for action – finding a name from a list of names 248
CartesianProduct() 249
Time for action – generating names of all the 52 playing cards 249
RandomShuffle() 250
Time for action – randomly shuffling the deck 250
NCopiesOf() 252
Time for action – creating random numbers of any given length 252
Time for action – creating a custom random number generator 253
ForEach() 256
Time for action – creating a few random numbers of given any length 256
Rotate() and RotateInPlace() 257
Time for action – rotating a word 258
Time for action – creating a word guessing game 258
RandomSubset() 262
Time for action – picking a set of random elements 262
Reverse() 263
Time for action – reversing any collection 263
EqualCollections() 264
Time for action – revisiting the palindrome problem 264
DisjointSets() 265
Time for action – checking for common stuff 265
Table of Contents
[ vii ]
Time for action – finding anagrams the easiest way 266
Creating an efficient arbitrary floating point representation 267
Time for action – creating a huge number API 267
Creating an API for customizable default values 273
Time for action – creating a default value API 273
Mapping data structure 277
Algorithm conversion strategy 277
Summary 278
Chapter 8: C5 Collections 279
Setting up the environment 281
Time for action – cloning Gender Genie! 281
Time for action – revisiting the anagram problem 287
Time for action – Google Sets idea prototype 288
Time for action – finding the most sought-after item 294
Sorting algorithms 299
Pattern 1: Sorting an array of integers 300
Pattern 2: Partially sorting an array—say, sort first five numbers of a long array 300
Pattern 3: Sorting a list of string objects 301
Summary 302
Chapter 9: Patterns, Practices, and Performance 303
Generic container patterns 304
How these are organized 304
Pattern 1: One-to-one mapping 304
Pattern 2: One-to-many unique value mapping 305
Pattern 3: One-to-many value mapping 306
Pattern 4: Many-to-many mapping 307
A special Tuple<> pattern 308
Time for action – refactoring deeply nested if-else blocks 310
Best practices when using Generics 312
Selecting a generic collection 314
Best practices when creating custom generic collections 315
Performance analysis 317
Lists 317
Dictionaries/associative containers 318
Sets 318
How would we do this investigation? 318
Benchmarking experiment 1 319
Benchmarking experiment 2 324
Benchmarking experiment 3 328
Benchmarking experiment 4 330
Benchmarking experiment 5 334
Table of Contents
[ viii ]
Benchmarking experiment 6 336
Benchmarking experiment 7 340
Benchmarking experiment 8 344
Benchmarking experiment 9 345
Summary 348
Appendix A: Performance Cheat Sheet 349
Parameters to consider 353
Appendix B: Migration Cheat Sheet 357
Appendix C: Pop Quiz Answers 361
Chapter 2 361
Lists 361
Chapter 3 361
Dictionaries 361
Chapter 4 362
LINQ to Objects 362
Index 363
Preface
Thanks for picking up this book. This is an example-driven book. You will learn about
several generic containers and generic algorithms available in the .NET Framework and a
couple of other majorly accepted APIs such as Power Collections and C5 by building several
applications and programs.
Towards the end, several benchmarkings have been carried out to identify the best container
for the job at hand.
What this book covers
Chapter 1, Why Generics?, introduces .NET Generics. We will examine the need for the
invention of Generics in the .NET Framework. If you start with a feel of "Why should I learn
Generics?", you will end with a feeling of "Why didn't I till now?"
Chapter 2, Lists, introduces you to several kinds of lists that .NET Generics has to offer. There
are simple lists and associative lists. You shall see how simple lists can deliver amazing results
avoiding any typecasting woes and boosting performance at the same time.
Chapter 3, Dictionaries, explains the need for associative containers and introduces you to
the associative containers that .NET has to offer. If you need to keep track of one or multiple
dependent variables while one independent variable changes, you need a dictionary.
For example, say you want to build a spell check or an autocomplete service, you need a
dictionary. This chapter will walk you through this. Along the way, you will pick up some very
important concepts.
Chapter 4, LINQ to Objects, explains LINQ to objects using extension methods. LINQ or
Language Integrated Query is a syntax that allows us to query collections unanimously. In this
chapter, we will learn about some standard LINQ Standard Query Operators (LSQO) and then
use them in unison to orchestrate an elegant query for any custom need.
Preface
[ 2 ]
Chapter 5, Observable Collections, introduces observable collections. Observing events on
collections has been inherently difficult. That's going to change forever, thanks to observable
collections. You can now monitor your collections for any change; whether some elements
are added to the collection, some of them are deleted, change locations, and so on. In this
chapter, you will learn about these collections.
Chapter 6, Concurrent Collections, covers concurrent collections that appeared in .NET
4.0. Multi-threaded applications are ubiquitous and that's the new expectation of our
generation. We are always busy and impatient, trying to get a lot of things done at once. So
concurrency is here and it is here to stay for a long time. Historically, there was no inbuilt
support for concurrency in generic collections. Programmers had to ensure concurrency
through primitive thread locking. You can still do so, but you now have an option to use the
concurrent version of generic collections that support concurrency natively. This greatly
simplifies the code. In this chapter, you will learn how to use them to build some useful
applications such as simulating a survey engine.
Chapter 7, Power Collections, introduces several generic algorithms in PowerCollections
and some handy generic containers. This collection API came from Wintellect (www.
wintellect.com) at the time when .NET Generics was not big and had some very useful
collections. However, now .NET Generics has grown to support all those types and even
more. So that makes most of the containers defined in PowerCollections outdated.
However, there are a lot of good general purpose generic algorithms that you will need but
which are missing from the .NET Generics API. That's the reason this chapter is included.
In this chapter, you will see how these generic algorithms can be used with any generic
container seamlessly.
Chapter 8, C5 Collections, introduces the C5 API. If you come from a Java background and are
wondering where your hash and tree-based data structures, are this is the chapter to turn
to. However, from the usage perspective, all the containers available in C5 can be augmented
with generic containers available in the .NET Framework. You are free to use them. This API
is also home to several great generic algorithms that make life a lot easier. In this chapter,
you will walk through the different collections and algorithms that C5 offers.
Chapter 9, Patterns, Practices, and Performance, covers some best practices when dealing
with Generics and introduces the benchmarking strategy. In this chapter, we will use
benchmarking code to see how different generic containers perform and then declare
a winner in that field. For example, benchmarking shows that if you need a set, then
HashSet<T> in the .NET Framework is the fastest you can get.
Appendix A, Performance Cheat Sheet, is a cheat sheet with all the performance measures
for all containers. Keeping this handy would be extremely useful when you want to decide
which container to use for the job at hand.
Preface
[ 3 ]
Appendix B, Migration Cheat Sheet, will show you how to migrate code from STL/JCF/
PowerCollections/.NET 1.0 to the latest .NET Framework-compliant code. Migration will
never be easier. Using this cheat sheet, it will be a no brainer. This is great for seasoned C++,
Java, or .NET developers who are looking for a quick reference to .NET Generics in the
latest framework.
What you need for this book
You will need the following software to use this book:
‹
‹ Visual Studio 2010 (any version will do, I have used the Ultimate Trial version)
‹
‹ LINQPad
Instructions to download this software are given in the respective chapters where they
are introduced.
Who this book is for
This book is for you, if you want to know what .NET Generics is all about and how it can help
solve real-world problems. It is assumed that readers are familiar with C# program constructs
such as variable declaration, looping, branching, and so on. No prior knowledge in .NET
Generics or generic programming is required.
This book also offers handy migration tips from other generic APIs available in other
languages, such as STL in C++ or JCF in Java. So if you are trying to migrate your code to the
.NET platform from any of these, then this book will be helpful.
Last but not the least, this book ends with generic patterns, best practices, and performance
analysis for several generic containers. So, if you are an architect or senior software engineer
and have to define coding standards, this will be very handy as a showcase of proofs to your
design decisions.
Conventions
In this book, you will find several headings appearing frequently.
To give clear instructions of how to complete a procedure or task, we use:
Preface
[ 4 ]
Time for action – heading
1. Action 1
2. Action 2
3. Action 3
Instructions often need some extra explanation so that they make sense, so they are
followed with:
What just happened?
This heading explains the working of tasks or instructions that you have just completed.
You will also find some other learning aids in the book, including:
Pop quiz – heading
These are short, multiple choice questions intended to help you test your own
understanding.
Have a go hero – heading
These set practical challenges and give you ideas for experimenting with what you
have learned.
You will also find a number of styles of text that distinguish between different kinds of
information. Here are some examples of these styles, and an explanation of their meaning.
Code words in text are shown as follows: "Suppose, I want to maintain a list of my students,
then we can do that by using ArrayList to store a list of such Student objects."
A block of code is set as follows:
private T[] Sort<T>(T[] inputArray)
{
//Sort input array in-place
//and return the sorted array
return inputArray;
}
Preface
[ 5 ]
When we wish to draw your attention to a particular part of a code block, the relevant lines
or items are set in bold:
Enumerable.Range(1, 100).Reverse().ToList()
.ForEach(n => nums.AddLast(n));
Any command-line input or output is written as follows:
Argument 1: cannot convert from 'int[]' to 'float[]'
New terms and important words are shown in bold. Words that you see on the screen, in
menus or dialog boxes for example, appear in the text like this: "Then go to the File menu to
create a console project."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book—
what you liked or may have disliked. Reader feedback is important for us to develop titles
that you really get the most out of.
To send us general feedback, simply send an e-mail to feedback@packtpub.com, and
mention the book title through the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or
contributing to a book, see our author guide on www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you
to get the most from your purchase.
Preface
[ 6 ]
Downloading the example code
You can download the example code files for all Packt books you have purchased from your
account at http://www.packtpub.com. If you purchased this book elsewhere, you can
visit http://www.packtpub.com/support and register to have the files e-mailed directly
to you.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do
happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—
we would be grateful if you would report this to us. By doing so, you can save other readers
from frustration and help us improve subsequent versions of this book. If you find any
errata, please report them by visiting http://www.packtpub.com/support, selecting
your book, clicking on the errata submission form link, and entering the details of your
errata. Once your errata are verified, your submission will be accepted and the errata will be
uploaded to our website, or added to any list of existing errata, under the Errata section of
that title.
Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt,
we take the protection of our copyright and licenses very seriously. If you come across any
illegal copies of our works, in any form, on the Internet, please provide us with the location
address or website name immediately so that we can pursue a remedy.
Please contact us at copyright@packtpub.com with a link to the suspected pirated
material.
We appreciate your help in protecting our authors, and our ability to bring you valuable
content.
Questions
You can contact us at questions@packtpub.com if you are having a problem with any
aspect of the book, and we will do our best to address it.
1
Why Generics?
Thanks for picking up the book! This means you care for Generics. This is similar
to dropping a plastic bag in favor of our lonely planet.
We are living in an interesting era, where more and more applications are data
driven. To store these different kinds of data, we need several data structures.
Although the actual piece of data is different, that doesn't always necessarily
mean that the type of data is different. For example, consider the following
situations:
Let's say, we have to write an application to pull in tweets and Facebook wall
updates for given user IDs. Although these two result sets will have different
features, they can be stored in a similar list of items. The list is a generic list that
can be programmed to store items of a given type, at compile time, to ensure
type safety. This is also known as parametric polymorphism.
A cat and a dog shouldn't
share a bed. Neither
should integers and floats.
Why Generics?
[ 8 ]
In this introductory chapter, I shall give you a few reasons why Generics is important.
An analogy
Here is an interesting analogy. Assume that there is a model hand pattern:
If we fill the pattern with clay, we get a clay-modeled hand. If we fill it with bronze, we get
a hand model replica made of bronze. Although the material in these two hand models are
very different, they share the same pattern (or they were created using the same algorithm,
if you would agree to that term, in a broader sense).
Reason 1: Generics can save you a lot of typing
Extrapolating the algorithm part, let's say we have to implement some sorting algorithm;
however, data types can vary for the input. To solve this, you can use overloading, as follows:
//Overloaded sort methods
private int[] Sort(int[] inputArray)
{
//Sort input array in-place
//and return the sorted array
return inputArray;
}
private float[] Sort(float[] inputArray)
{
//Sort input array in-place
//and return the sorted array
return inputArray;
}
Chapter 1
[ 9 ]
However, you have to write the same code for all numeric data types supported by .NET.
That's bad. Wouldn't it be cool if the compiler could somehow be instructed at compile time
to yield the right version for the given data type at runtime? That's what Generics is about.
Instead of writing the same method for all data types, you can create one single method with
a symbolic data type. This will instruct the compiler to yield a specific code for the specific
data type at runtime, as follows:
private T[] Sort<T>(T[] inputArray)
{
//Sort input array in-place
//and return the sorted array
return inputArray;
}
T is short for Type. If you replace T with anything, it will still compile; because it's the
symbolic name for the generic type that will get replaced with a real type in the .NET type
system at runtime.
So once we have this method, we can call it as follows:
int[] inputArray = { 1, 2, 0, 3 };
inputArray = Sort<int>(inputArray);
However, if you hover your mouse pointer right after the first brace ((), you can see in the
tooltip, the expected type is already int[], as shown in the following screenshot:
That's the beauty of Generics. As we had mentioned int inside < and >, the compiler now
knows for sure that it should expect only an int[] as the argument to the Sort<T> ()
method.
However, if you change int to float, you will see that the expectation of the compiler also
changes. It then expects a float[] as the argument, as shown:
Why Generics?
[ 10 ]
Now if you think you can fool the compiler by passing an integer array while it is asking for
a float, you are wrong. That's blocked by compiler-time type checking. If you try something
similar to the following:
You will get the following compiler error:
Argument 1: cannot convert from 'int[]' to 'float[]'
This means that Generics ensures strong type safety and is an integral part of the .NET
framework, which is type safe.
Reason 2: Generics can save you type safety woes, big time
The previous example was about a sorting algorithm that doesn't change with data type.
There are other things that become easier while dealing with Generics.
There are broadly two types of operations that can be performed on a list of elements:
1. Location centric operations
2. Data centric operations
Adding some elements at the front and deleting elements at an index are a couple of
examples of location-centric operations on a list of data. In such operations, the user doesn't
need to know about the data. It's just some memory manipulation at best.
However, if the request is to delete every odd number from a list of integers, then that's a
data-centric operation. To be able to successfully process this request, the method has to
know how to determine whether an integer is odd or not. This might sound trivial for an
integer; however, the point is the logic of determining whether an element is a candidate for
deletion or not, is not readily known to the compiler. It has to be delegated.
Before Generics appeared in .NET 2.0, people were using (and unfortunately these are still in
heavy use) non-generic collections that are capable of storing a list of objects.
As an object sits at the top of the hierarchy in the .NET object model, this opens floodgates.
If such a list exists and is exposed, people can put in just about anything in that list and the
compiler won't complain a bit, because to the compiler everything is fine as they are all
objects.
Chapter 1
[ 11 ]
So, if a loosely typed collection such as ArrayList is used to store objects of type T, then for
any data-centric operation, these must be down-casted to T again. Now, if somehow an entry
that is not T, is put into the list, then this down-casting will result in an exception at runtime.
Suppose, I want to maintain a list of my students, then we can do that by using ArrayList
to store a list of such Student objects:
class Student
{
public char Grade
{
get; set;
}
public int Roll
{
get; set;
}
public string Name
{
get; set;
}
}
//List of students
ArrayList studentList = new ArrayList();
Student newStudent = new Student();
newStudent.Name = "Dorothy";
newStudent.Roll = 1;
newStudent.Grade = 'A';
studentList.Add(newStudent);
newStudent = new Student();
newStudent.Name = "Sam";
newStudent.Roll = 2;
newStudent.Grade ='B';
studentList.Add(newStudent);
foreach (Object s in studentList)
{
//Type-casting. If s is anything other than a student
Why Generics?
[ 12 ]
//or a derived class, this line will throw an exception.
//This is a data centric operation.
Student currentStudent = (Student)s;
Console.WriteLine("Roll # " + currentStudent.Roll + " " +
currentStudent.Name + " Scored a " +
curr entStudent.Grade);
}
What's the problem with this approach?
All this might look kind of okay, because we have been taking great care not to put anything
else in the list other than Student objects. So, while we de-reference them after boxing, we
don't see any problem. However, as the ArrayList can take any object as the argument, we
could, by mistake, write something similar to the following:
studentList.Add("Generics"); //Fooling the compiler
As ArrayList is a loosely typed collection, it doesn't ensure compile-time type checking.
So, this code won't generate any compile-time warning, and eventually it will throw the
following exception at runtime when we try to de-reference this, to put in a Student object.
Then, it will throw an InvalidCastException:
What the exception in the preceding screenshot actually tells us is that Generics is a string
and it can't cast that to Student, for the obvious reason that the compiler has no clue how
to convert a string to a Student object.
Unfortunately, this only gets noticed by the compiler during runtime. With Generics, we can
catch this sort of error early on at compile time.
Chapter 1
[ 13 ]
Following is the generic code to maintain that list:
//Creating a generic list of type "Student".
//This is a strongly-typed-collection of type "Student".
//So nothing, except Student or derived class objects from Student
//can be put in this list myStudents
List<Student> myStudents = new List<Student>();
//Adding a couple of students to the list
Student newStudent = new Student();
newStudent.Name = "Dorothy";
newStudent.Roll = 1;
newStudent.Grade = 'A';
myStudents.Add(newStudent);
newStudent = new Student();
newStudent.Name = "Sam";
newStudent.Roll = 2;
newStudent.Grade = 'B';
myStudents.Add(newStudent);
//Looping through the list of students
foreach (Student currentStudent in myStudents)
{
//There is no need to type cast. Because compiler
//already knows that everything inside this list
//is a Student.
Console.WriteLine("Roll # " + currentStudent.Roll + " " +
currentStudent.Name + " Scored a " +
currentStudent.Grade);
}
The reasons mentioned earlier are the basic benefits of Generics. Also with Generics,
language features such as LINQ and completely new languages such as F# came into
existence. So, this is important. I hope you are convinced that Generics is a great
programming tool and you are ready to learn it.
Why Generics?
[ 14 ]
Reason 3: Generics leads to faster code
In the .NET Framework, everything is an object so it's okay to throw in anything to the non-
generic loosely typed collection such as ArrayList, as shown in the previous example. This
means we have to box (up-cast to object for storing things in the Arraylist; this process is
implicit) and unbox (down-cast the object to the desired object type). This leads to
slower code.
Here is the result of an experiment. I created two lists, one ArrayList and one List<int>
to store integers:
And following is the data that drove the preceding graph:
ArrayList List<T>
1323 185
1303 169
1327 172
1340 169
1302 172
The previous table mentions the total time taken in milliseconds to add 10,000,000 elements
to the list. Clearly, generic collection is about seven times faster.
Chapter 1
[ 15 ]
Reason 4: Generics is now ubiquitous in the .NET ecosystem
Look around. If you care to develop any non-trivial application, you are better off using some
of the APIs built for the specific job at hand. Most of the APIs available rely heavily on strong
typing and they achieve this through Generics. We shall discuss some of these APIs (LINQ,
PowerCollections, C5) that are being predominantly used by the .NET community in
this book.
So far, I have been giving you reasons to learn Generics. At this point, I am sure, you are
ready to experiment with .NET Generics. Please check out the instructions in the next section
to install the necessary software if you don't have it already.
Setting up the environment
If you are already running any 2010 version of Visual Studio that lets you create C# windows
and console projects, you don't have to do anything and you can skip this section.
You can download and install the Visual Studio Trial from http://www.microsoft.com/
download/en/details.aspx?displaylang=en&id=12752.
Once you are done, you should see the following in your program menu:
After this, start the program highlighted in the preceding screenshot Microsoft Visual
Studio 2010.
Why Generics?
[ 16 ]
Then go to the File menu to create a console project:
Now, once that is created, make sure the following namespaces are available:
If these are available, you have done the right setup. Congratulations!
Chapter 1
[ 17 ]
Summary
My objective for this chapter was to make sure you get why Generics is important. Following
are the points again in bullets:
‹
‹ It ensures compile-time type checking, so type safety is ensured.
‹
‹ It can yield the right code for the data type thrown at it at runtime, thus saving us a
lot of typing.
‹
‹ It is very fast (about seven times) compared to its non-generic cousins for value
types.
‹
‹ It is everywhere in the .NET ecosystem. API/framework developers trust the element
of least surprise and they know people are familiar with Generics and their syntax.
So they try to make sure their APIs also seem familiar to the users.
In the end, we did an initial setup of the environment; so we are ready to build and run
applications using .NET Generics. From the next chapter, we shall learn about .NET Generic
containers and classes. In the next chapter, we shall discuss the Generic container List<T>
that will let you store any type of data in a type safe way. Now that you know that's
important, let's go there.
Net 40 Generics Beginners Guide Sudipta Mukherjee
2
Lists
Lists are everywhere, starting from the laundry list and grocery list to the
checklist on your smartphone's task manager. There are two types of lists.
Simple lists, which just store some items disregarding the order allowing
duplicates; and other types which don't allow duplicates. These second types
of lists which don't allow duplicates are called sets in mathematics. The other
broad category of list is associative list, where each element in some list gets
mapped to another element in another list.
In this chapter, we shall learn about these generic containers and related methods. We shall
learn when to use which list-based container depending on the situation.
Reading this chapter and following the exercises you will learn the following:
‹
‹ Why bother learning about generic lists?
‹
‹ Types of generic lists and how to use them
Don't forget the milk, honey!
Lists
[ 20 ]
‹
‹ Give proper rationale for choosing a generic list such as one container over the other
‹
‹ How to create custom generic list-based containers
So let's get on with it...
Why bother learning about generic lists?
Let us see why generic lists are important:
‹
‹ It ensures compile-time type checking. So type-unsafe code becomes a thing of the
past.
‹
‹ It saves us a lot of typing, because compiler can generate type-safe code for generic
types at runtime. So the same code works for different data types.
‹
‹ It is faster in many cases than its non-generic cousins, because it removes the need
to box and unbox (also known as type-casting) from the code.
‹
‹ It makes source code much cleaner than its older, non-generic, unsafe cousins.
In this chapter, you shall find examples of how generic list-based containers make these
possible. Happy listing!
Types of generic lists
There are mainly three types of lists you can imagine or would ever need:
1. Simple list: It allows duplicates by default.
2. Sets: It doesn't allow duplicates by default.
3. Associative list: It helps to represent a relationship between two types of entities.
A simple list is just a collection of items. Say a laundry list, a grocery list, a task list, a list of
courses. The elements in a simple container don't associate them with any other element. There
are several generic container classes to represent simple lists. They are Stack<T>, Queue<T>,
List<T>, LinkedList<T>, and SortedSet<T>. These are generic implementations of
classic data structures. So Stack<T> is a Last In First Out (LIFO) list, Queue<T> is a First In First
Out (FIFO) list, List<T> is a simple unordered list, and so is LinkedList<T>. But List<T>
supports random integer indexing natively, while the others don't.
Sets are simple lists that don't allow duplicates. All sets implement the interface ISet<T>.
There are two set implementations HashSet<T> and SortedSet<T>. HashSet<T> doesn't
maintain the order of elements, while SortedSet<T> keeps the elements sorted, if it knows
how to sort the type. For custom types, you can pass a custom IComparer<T> instance to
delegate the task of comparing. For HashSet<T>, you can pass IEqualityComparer<T>
for custom equality comparison.
Chapter 2
[ 21 ]
An associative list, as the name suggests, brings in an association between two different
entities and represents them in a single list for example, marks obtained by a student in
a different semester of a course, share values for a company over the years, and so on.
To represent these type of lists, there is an interface IDictionary<TKey,TValue> and
SortedList<TKey,TValue> is a derived class that implements this interface. So we
can use SortedList<TKey,TValue> to represent any associative list in .NET Generics.
SortedList<TKey,TValue> is also a list. This is implemented using an array. So unlike
other IDictionary<TKey,TValue> implementations, SortedList<TKey,TValue>
supports indexing over keys and values. So the order of insertion in a SortedList
determines the order of elements; unlike other IDictionary<TKey,TValue>
implementations, as we shall see in the next chapter.
If you were wondering what the heck are TKey and TValue, they are short and quite
traditional ways of representing the type of key and type of value respectively. As generic
lists can support any type, they are represented in this way. So at runtime the compiler
generates appropriate code for the specified data type. This greatly helps to reduce code
duplication and type mismatch issues.
In a nutshell:
Stack<T> This is a generic Stack implementation. This is first in last out.
Queue<T> This is a generic Queue implementation. This is a first in first out list.
List<T> This is a generic implementation of a simple list. This offers native random
zero based integer indexing like an array.
LinkedList<T> This is a generic implementation of a classic double-linked list. No native
random indexing is offered.
HashSet<T> This is a generic Set implementation. The elements are not
sorted. For custom equality comparison, you can pass the
IEqualityComparer<T> instance.
SortedSet<T> This is a generic Set implementation. The value type elements remain
sorted, by default. For reference types, we have to pass custom-comparer
objects for custom element sorting; you can use the IComparer<T>
instance.
SortedList<T> Sometimes you want an associative container, but you still want to be
able to access each key-value pair, like you do in a plain old array using the
index. Then all you need is a SortedList<T>.
Lists
[ 22 ]
Now that we have some basic idea about these generic list based containers, we shall see
how these can be used to solve some real-world problems. Let's get started with a fun app!
A generic collection can contain objects of value and reference types. This means you can
create nested types.
For example, if you want a list of stacks, you can get that by declaring List<Stack<T>>.
If you want a SortedList of integer keys and associate a list of string values with each such
integer key, you can write SortedList<int,List<string>>.
Checking whether a sequence is a palindrome or not
All the following sequences share a common attribute. They all read the same both ways,
save for the punctuations
"Madam I'm Adam"
"A Man, A Plan, A Canal, Panama!!"
12321
Detroit-Chicago-Detroit (This reads same word by word backwards, unlike others that read
the same character by character.)
A Toyota
These types of sequences are called palindromes. A sequence is palindromic too, if the
contents read the same both ways, for example, A-B-A. In this example, we shall see how a
generic stack (that is, a Stack<T> instance) can be used to implement this, so that we can
detect whether a given sequence is a palindrome or not for any given type that knows how
to compare itself (that is, implements the IComparable interface).
So the task at hand is to build a generic palindrome checker that can check whether any
sequence is a palindrome or not. All we have to do is let it know the type of the sequence at
runtime.
The algorithm to find whether a sequence is a palindrome or not is really simple. If we
arrange the tasks to be done in order to check whether the given sequence is a palindrome
or not, it will be like:
Chapter 2
[ 23 ]
Pick items from Input
Put them in reverse order
Retrieve elements from Input and Reversed Sequence
Compare these two
Equals
Sequence Ends ?
The sequence is not palindrome
The sequence is palindrome
No
No
Yes
Yes
The sequence can be of any type; char, string, integer, float, and so on to name a few. Also,
note that the algorithm is not different for all these different types. However, we shall have
to write several methods for supporting several data types.
However, if we use Generics we can avoid this code duplication for each type. We can write
a single method (also known as Generic Method) that can write the data type-specific code
at runtime depending on what type of data type we want. The tradition is to use the letter
T (which is short for Type) to create the generic method. When we consume this method,
we pass concrete Types that conform to the standard expectations from the Type; like in this
case, we expect the Type to implement IComparable.
The heart of the solution is to reverse the elements of the input sequence. This can be done
by a stack. Since we want to make the method generic, we need a generic stack.
Lists
[ 24 ]
Time for action – creating the generic stack as the buffer
Follow the given steps:
1. Create a console application project. Call it Palindrome Checker.
2. Create a method called IsPalindromic() with the following signature:
public static bool IsPalindromic<T>(IEnumerable<T> inputSequence)
where T:IComparable
{
Stack<T> buffer = new Stack<T>();
return true;
}
3. Add the following code in the Main() method:
static void Main(string[] args)
{
bool status = IsPalindromic<char>(new int[] { 1, 2, 2, 1 });
}
4. Try to compile the program.
What just happened?
You will see a compiler error as shown in the following screenshot:
Let's see why that compile-time error occurred. Before that, let's learn a little more about
generic stacks.
Creating a generic stack is very easy. Here is how:
Stack<T> myGenericStack = new Stack<T>();
So if you want a generic stack to be used to store a stack of string, then you change T with
string as follows:
Stack<string> myCDs = new Stack<string>();
Chapter 2
[ 25 ]
If you want a stack of integers, you just say:
Stack<int> opCodes = new Stack<int>();
If you are dealing with reference types, then you can declare a stack of base types and put
derived types in that. Say if D is a class that implements an ID interface, then if you create a
stack of ID objects, you can put ID objects in the Stack as follows:
Stack<ID> somethings = new Stack<ID>();
Somethings.Push(new ID());
However, the method needs to know how to compare the elements in the buffer. So now
the obvious question you might have is, if we write the code using a generic place holder (T
in this case) which gets replaced by the original data type at runtime, how will the method
know at compile time how to compare variables of such data type?
Well, that's a very good question and the answer lies in the very first line of the method.
Let's take a close look at it:
public static bool IsPalindromic<T>(IEnumerable<T> inputSequence)
where T:IComparable
The keyword where is used to constrain the types that can be used as a valid argument
in the generic method IsPalindromic<T>(), we just created. where T:IComparable
means T has to be a type that implements the IComparable interface. This syntax is known
as Constraints in Generics.
Now, let's get back to the compilation error part. Generics ensure compile-time type
checking as follows:
bool status = IsPalindromic<char>(new int[] { 1, 2, 2, 1 });
In this code, IsPalindromic<char> promises that everything that follows in the argument
to this method will be of type character. However, we have an integer array as the input
sequence. This is causing a type mismatch and thus is caught at compile time.
We are passing an array as the parameter, where the method expects something of type
IEnumerable<T>. This is possible because IEnumerable<T> inherits from IEnumerable
and good old arrays implement IEnumerable too. Thus, IEnumerable serves as a bridge
between pre-generic collections and generic collections.
Lists
[ 26 ]
Time for action – completing the rest of the method
Follow the given steps:
1. Add the following code after the initialization of the buffer in the source, as carried
out previously in step 2:
foreach (T element in inputSequence)
{
buffer.Push(element);
}
Count() and ElementAt() are extension methods and are available at System.
Linq namespace in .NET Framework 3.5 and above. You can get it with Visual Studio
2008 and above. So please include that namespace:
for (int i = 0; i < inputSequence.Count(); i++)
{
if(buffer.Pop().CompareTo(inputSequence.ElementAt(i))==0)
continue;
else
return false;
}
Make sure you retain the last return true; statement.
2. Replace the content of the Main() method with the following:
static void Main(string[] args)
{
//Checking if a string (Which is basically a sequence of
//characters)
bool status1 = IsPalindromic<char>("LIRIL");
//Checking if an array of string is palindromic
bool status2 = IsPalindromic<string>(new string[]
{"mango","apple","mango"});
//Checking if an array of int is palindromic
bool status3 = IsPalindromic<int>(new int[]
{ 1,2,3,4,5,6,0,6,5,4,3,2,1 });
//Checking if an array of float is palindromic
bool status4 = IsPalindromic<float>(new float[]
{ 1.34F,2.34F,43.1F});
Console.WriteLine(status1 + " " + status2 + " " +
status3 + " " + status4);
}
3. Run the program.
Chapter 2
[ 27 ]
What just happened?
The program shall print the following to the console:
The following looping construct:
foreach (T element in inputSequence)
{
buffer.Push(element);
}
pushes all the elements in the input sequence to a stack. The stack is a last in first out list.
It keeps the elements in reverse order. So if you want to add an element to the top of the
stack, you should use the push method.
So when the method is called by bool status1 = IsPalindromic<char>("GENERI
CS"); it stores the characters of the input sequence in the internal generic stack buffer
as follows:
G
E
N
E
R
I
C
S
Input Sequence
G
E
N
E
R
I
C
Stack buffer
push()
buffer.Pop() returns the top-most element from the stack and removes that from the
stack. The ElementAt() method returns the ith element from the input sequence. As long
as these two are equal, the sequence might be a palindrome. So, we must continue going
through the input sequence. However, if they mismatch at any point, it becomes evident
immediately that the input sequence is not a palindrome. Thus, we can return False.
However, if we can get to the end of the input sequence without encountering a mismatch,
the input sequence is a palindrome and thus we have to return True.
Lists
[ 28 ]
Let's now try to decode the output. Among four input sequences in the Main() method,
the first three are palindromes. However, the last one doesn't read the same both ways
and surely isn't a palindrome. Output matches that. We get True for the first three input
sequences and False for the last one.
Any type that implements IComparable would work. Other types will fail.
Designing a generic anagram finder
Generics are not limited to lists and you can even mix parameterized types with specialized
types as well. For instance, what if you want to store the frequency of occurrence of a string,
number, or a symbol. While the type of what you keep the frequency of is unknown or
undecided, however you see that the frequency itself is always a number. Let's take a look at
how we can implement that using anagrams as an example.
Anagrams are as fascinating as palindromes. Two sequences are said to be anagrams of each
another, when they share the same number of elements in the same frequency.
For example, two strings "The eyes" and "They see" both have the same number of
characters, and the frequency of each character in these two strings is the same. Both of
them have a single "T", a couple of "e"s, and so on. Thus, they are anagrams of each other.
http://www.anagrammy.com/ organizes a competition for the best anagrams each
month. Assume your friend wants to participate and is now seeking your help to develop a
program that can find anagrams of a given word. Let's get into action and help your buddy.
A strategy to check whether two sequences are anagrams of each other or not is really
simple. We need a container that would let us store each unique element of the sequence
and their frequency of appearance in the sequence.
For example, the string "The eyes" will be stored in such a container as follows:
Element Frequency
T
H
E
Y
S
1
1
3
1
1
Chapter 2
[ 29 ]
If another string stored in the same way shares the same frequency of characters, then that
will be an anagram of "The eyes". So, if we deduct 1 from the frequency as soon as we get
the same character in the second string; we shall have all zeros in the frequency column of
the preceding table at the end of scanning the second string; in this case, we are dealing with
two anagrams.
This algorithm is applicable to any type of anagram sequence, not only for strings. So, we can
write a generic method to check whether two sequences are anagrams of each other or not,
for any type.
Time for action – creating the method
Follow the given steps:
1. Create a console application called Ganagram (short form for generic anagram). This
is a showcase of SortedList<TKey,TValue>, solving a real problem.
2. Add the following method in the Program.cs file:
public static bool IsAnagram<T>(IEnumerable<T> first,
IEnumerable<T> second)
{
SortedList<T, int> val = new SortedList<<T, int>();
foreach (T element in first)
{
if (!val.ContainsKey(element))
val.Add(element, 1);
else
val[element]++;
}
foreach (T element in second)
{
if (val.ContainsKey(element))
val[element]--;
else
return false;
}
foreach (T element in val.Keys)
{
if (val[element] != 0)
return false;
Other documents randomly have
different content
captain. Nothing in his narrative enables us to identify
this Cocke with the Abraham Cocke of Limehouse, who
was “never heard of more” after he parted from Battell
on the coast of Brazil in 1590, nor with the Abram
Cocke who, according to Knivet, put in at the Ilha
Grande in 1598, in the hope of making prizes of some of the richly-
laden Spanish vessels returning from the Rio de la Plata. Battell,
surely, may be supposed to have been acquainted with the fate of
his old shipmate, whilst Knivet gives no hint that the Abram Cocke of
the Ilha Grande was the captain of the Roebuck, to whom he was
indebted for his life when Cavendish was about to throw him
overboard in Magellan’s Strait. It is, however, just possible that there
was but one Abraham Cock, who had not been heard of for some
time when Battell returned to England about 1610.263
When Cavendish returned from Magellan’s Strait, he put Knivet and
nineteen other sick men ashore near St. Sebastian, to shift for
themselves. Knivet was ultimately taken by the Portuguese; but they
spared his life, and he became the “bond-slave” of Salvador Corrêa
de Sá, the Governor of Rio de Janeiro; and apart from the time he
spent among the cannibal Indians, and on a voyage to Angola, he
remained with his master to the end, and returned with him to
Portugal in 1599.
My friend, Colonel G. Earl Church, to whom I applied for an opinion
on the trustworthiness of Knivet’s statements with regard to Brazil,
writes as follows:—
“Yesterday morning I spent at the R. Geo. Soc., refreshing my
memory of Knivet’s extraordinary adventures. One must read them
always bearing in mind the romantic spirit of the age in which they
were written, and the novel surroundings in which every adventurer
found himself in the New World. Giving due weight to all this, I find
Knivet’s relation of his voyages singularly truthful, so far as my
knowledge of Brazil goes. What he states, excepting in two or three
minor particulars, clashes with no geographical, descriptive, or
historical point with which I am familiar, and he often throws in a
sentence which relates to facts which no man could invent, and
which makes his narrative impressive with truthfulness. I utterly
discard Cavendish’s opinion of his men and companions for
Cavendish appears to have been one of the most cold-blooded
freebooters who ever cut a throat or raided a settlement or scuttled
a prize.”
I regret not being able to write in terms equally favourable of what
Knivet claims to have experienced during his visit to Angola and
Kongo. Knivet says that he ran away from bondage on June 27th,
1597, and that he reached the “port of Angola” after a perilous
voyage of five months, that is in November. He then sailed up the
Kwanza, and reached Masanganu, where he remained three months,
when he was arrested in consequence of a requisition of his master
and sent back to Brazil, which he must have reached before June,
1598. We should be quite prepared to accept this part of his story if
his description of Masanganu did not show that he can never have
been there. Knivet, however, is not content with such modest
honours, but claims to have resided for some time at the court of
the King of Kongo, and to have fallen in the hands of the Portuguese
when on his road to Prester John’s country. By them he was carried
to Masanganu, where he lived three months. These two accounts
are absolutely irreconcilable. As to the author’s astounding
geographical misstatements, I refer the reader to the notes
appended to his narrative.
First Account (Purchas, pp. 1220-2).
Continually I desired my master to give me leave to get my living,
intending to come into my country, but the Governor would not let
me go from him. When I saw no means to get leave of my master, I
determined to run away to Angola, for to serve the King as a soldier
in Massangano till such time that I might pass myself to the King of
Anyeca,264
which warreth against the Portugals, and so have come
through Prester Johns country into Turkey.
On the seven and twentieth day of June, 1597, I embarked myself
unknown to my master, in a small ship of one Emanuell Andrea, for
to come for Angola. In this voyage we were driven so near the Cape
of Good Hope that we thought all of us should have been cast away,
the seas are there so great; and by reason of the current they brake
in such sort that no ship is able to endure. There we brake both our
main mast and our mizzen. It pleased God to send us the wind
Eastward, which brought us to our desired harbour [of] Angola.265
We had been five months in our voyage, and by that means other
ships that departed two months after us were there before us.
When I heard that there were ships of the River of Ienero [Rio de
Janeiro], I durst not go ashore for fear of being known of some of
the Portugals. The next day after that we came into the harbour,
there came a great boat aboard us, to ask if we would sell any
Cassava meal. We told them we would, and asked them whither
they went with their boat. They answered, that they tarried for the
tide to go up to the River of Guansa [Kwanza] to Masangano. Then I
thought it a fit time for my purpose, and so embarked myself in the
bark. The Portugals marvelled to see me go willingly to Masangano;
for there men die like chickens, and no man will go thither if he can
chose.
Nine days we were going up the River of Guansa [Kwanza], in which
time two Portugal soldiers died; the country is so hot that it pierceth
their hearts. Three days after I had been in Masangano, Don
Francisco de Mendosa Fortado,266
the Governor of the city of Kongo,
having received a letter from Salvador Coria de Sasa [Salvador
Corrêa de Sá], who was his great friend, sent a Pursuivant for me,
who brought me by land through the King of Kongo’s country, and in
six days we came to a town called Saint Francis267
(where the
Governor was), hard by the kingdom of Manicongo.
When I came before the Governor he used me very kindly in words,
and asked me what I meant, to cast myself away wilfully in
Masangano. Then I told him how long I had served Salvador Coria
de Sasa; and in how many dangers I had been for him and his Son,
without ever having any recompence of any of them, and therefore I
thought it better to venture my life in the King’s service, than to live
his Bond-slave. The Governor commanded me to be carried to
Angola, and charged a pair of bolts to be put upon my legs, because
I should not run away.
About a fortnight after I was sent back again in a Carvell [caravel] of
Francis Lewes, and in two months we arrived in the River of Jenero
[Rio de Janeiro], and I was carried with my bolts on my legs before
the Governor; when he saw me he began to laugh and to jest with
me, saying that I was welcome out of England. So, after many jests
he spake, he bade pull off my bolts from my legs, and gave me
clothes and used me very well.
Second Account (Purchas, pp. 1233-7).
Angola is a kingdom of itself in Ethiopia, where first the Portugals did
begin to inhabit: The country of Angola cometh along the coast; as
Portugal doth upon Spain, so doth Angola run upon the Kingdom of
Longa [Luangu] and Manicongo.
In Angola the Portugals have a City called the Holy Ghost,268
where
they have great store of Merchandise, and the Moors do come
thither with all kind of such things as the country yieldeth; some
bring elephant’s teeth, some bring negro slaves to sell, that they
take from other kingdoms which join hard by them; thus do they use
once a week, as we keep markets, so do all the Blackamoors bring
hens and hogs, which they call gula,269
and hens they call Sange,270
and a kind of beast that they take in the wilderness, like a dog,
which they call ambroa:271
then they have that beast which before I
have told you of, called gumbe, which is bigger than a horse.272
The Blackamoors do keep good laws, and fear their King very much;
the King is always attended with the nobles of his realm, and
whensoever he goeth abroad, he has always at the least two
hundred archers in his guard, and ten or twelve more going before
him, singing and playing with pipes made of great canes, and four or
five young Moors coming after him as his pages. After them follow
all his noblemen.
When there falleth out any controversy among them, they crave
battle of the King, and then they fight it out before him. They come
before the King and fall flat on their breasts; then they rise up and
kneel upon their knees, stretching out their arms crying, Mahobeque
benge, benge;273
then the King striketh them on the shoulders with
a horse-tail; then they go to the camp, and with their bows they
fight it out till they kill one another. After the battle is done, if any
liveth, he that liveth falleth down before the King in the same
manner as he did when he went to the field; and after a long oration
made, he taketh the horse-tail from the King’s shoulder, and waveth
it about the King’s head, and then layeth it on his shoulder again,
and goeth away with great honour, being accompanied with all the
nobles of the Court. The Moors of Angola do know that there is a
God, and do call God Caripongoa,274
but they worship the sun and
the moon.
The country is champaign plain, and dry black earth, and yieldeth
very little corn; the most of anything that it yieldeth is plantons
[plantains], which the Portugals call baynonas [bananas], and the
Moors call them mahonge275
and their wheat they call tumba,276
and
the bread anou; and if you will buy any bread of them, you must
say, Tala cuna auen tumbola gimbo; that is, Give me some bread,
here is money.277
Their money is called gullginbo,278
a shell of a fish
that they find by the shore-side; and from Brazil the Portugals do
carry great store of them to Angola.
These Moors do esteem very much of red, blue and yellow cloths.
They will give a slave for a span of cloth in breadth, I mean, and the
length of it, of the breadth of the piece; those pieces of cloth they
wear about their middles, and under it they hang the skin of a great
weasel before them, and another behind them, and this is all the
garments that they wear. A weasel in their language is called
puccu.279
You can do a Blackamoor no greater disgrace than to take
away his skin from before him, for he will die with grief if he cannot
be revenged.
The Portugals do mark them as we do sheep, with a hot iron, which
the Moors call crimbo.280
The poor slaves stand all in a row one by
another, and sing Mundele que sumbela he Carey ha belelelle,281
and thus the poor rogues are beguiled, for the Portugals make them
believe that they that have not the mark is not accounted a man of
any account in Brazil or in Portugal, and thus they bring the poor
Moors to be in a most damnable bondage under the cover of love.
The country of Angola yieldeth no stone, and very little wood: the
Moors do make their houses all covered with earth. These houses
are no bigger than a reasonable chamber, and within are many
partitions, like the cabins of a ship, in such sort that a man cannot
stand upright in them. Their beds are made of great bulrushes
sewed together with the rinds of a tree. They do make cloth like
spark of velvet (but it is thinner) of the bark of a tree, and that cloth
they do call mollelleo.282
The elephants do feed in the evening and in the morning in low
marshes, as there be many. The Moors do watch which way they
come, and as soon as the elephants are at meat, they dig great
holes in the ground, and cover them with sticks, and then they cover
the pits with earth; and when they have made all ready they go to
the elephants and shoot at them with their arrows; and as soon as
the elephants feel themselves hurt, they run at whatsoever they see
before them, following after the Blackamores that chase them. Then
they fall into the deep pits where, after they are once in, they
cannot get out.
The Moors of Angola are as black as jet; they are men of good
stature; they never take but one wife, whom they call mocasha.283
These Moors do cut long streaks in their faces, that reach from the
top of their ears to their chins. The women do wear shells of
fishes284
on their arms, and on the small of their legs. The law
amongst them is, that if any Moor do lie with another’s wife, he shall
lose his ears for his offence. These Moors do circumcise their
children, and give them their names, as we do when we baptize.
Angola may very easily be taken, for the Portugals have no forts to
defend it of any strength.
The King285
of Congo is the greatest King in all Ethiopia; and doth
keep in the field continually sixty thousand soldiers, that do war
against the King of Vangala,286
and the King of Angola; this King is a
Christian, and his brother-in-law of arms with the King of Spain. His
servants of his house are most of them all Portugals, and he doth
favour them very much.
The King is of a very liberal condition, and very favourable to all
travellers, and doth delight very much to hear of foreign countries.
He was in a manner amazed to hear how it was possible Her Majesty
[Queen Elizabeth] had lived a maiden Queen so long, and always
reigned in peace with her subjects. When I was brought before the
King, and told him of my country, what plenty of things we had, if
the Portugals had not liked of it, they would interrupt my speech,
and the King would show himself very angry, and tell them that
every man was best able to speak of his country, and that I had no
reason but to tell him that which was true.
The King of Congo, when he goeth to the camp to see his army,
rideth upon an elephant in great pomp and majesty; on either side
of the elephant he hath six slaves. Two of them were kings, that he
himself had taken in the field; all the rest were of noble birth; some
of them were brothers to the King of Ancica, and some of them were
of the chiefest blood of the great King of Bengala. These noble
slaves, at every command of the King of Congo, do fall flat on the
ground on their breasts. When the King doth ride, as you have
heard, they carry a canopy, as it were a cloth of state, over his head.
His two secretaries, the one a nobleman of Spain, the other a Moor,
do ride next after him. Before him goeth at the least five hundred
archers which are his guard; then there followeth a Moor, which doth
nothing but talk aloud in praise of the King, telling what a great
warrior he hath been, and praising his wisdom for all things that he
hath accomplished very honourably to his great fame of such as
knew him.
When this King of Congo cometh to his host, all the soldiers, as he
passeth, fall flat on their faces to the ground. He never cometh into
his host after any battle, but he dubbeth at the least twenty Knights
Portugals, and as many Moors, giving them very great living
according to their callings, and the service that they have done. The
brother of this King was in Spain at my coming from thence for
ambassador from his brother.287
Here the Portugal Captain would have taken me perforce, to have
been a common soldier, but the King commanded that they should
let me go whither I would, and my determination at that time was to
have gone for the country of Prester John [Abyssinia], for I had a
great desire to see the River of Nilo and Jerusalem (for I accounted
myself as a lost man, not caring into what country or kingdom I
came) But it was not the will of God that I should at that time obtain
my desire, for travelling through the kingdom of Congo, to have
gone to the kingdom of Angila,288
it was my fortune to meet a
company of Portugal soldiers that went to a conquest that the King
of Spain had newly taken, called Masangana; which place is on the
borders of Anguca. Here they made me serve like a drudge, for both
day and night I carried some stone and lime to make a fort.
It lyeth right under the Line, and standeth in a bottom in the middle
of four hills, and about are many fogges [bogs] but not one river.289
It is the unfirmest country under the sun. Here the Portugals die like
chickens. You shall see men in the morning very lusty, and within
two hours dead. Others, that if they but wet their legs, presently
they swell bigger than their middles;290
others break in the sides
with a draught of water. O, if you did know the intolerable heat of
the country, you would think yourself better a thousand times dead,
than to live there a week. There you shall see poor soldiers lie in
troops, gaping like camelians [camels?] for a puff of wind.
Here lived I three months, not as the Portugals did, taking of
physick, and every week letting of blood and keeping close in their
houses when they had any rain, observing hours, and times to go
abroad morning and evening, and never to eat but at such and such
times. I was glad when I had got anything at morning, noon, or
night; I thank God I did work all day from morning till night; had it
been rain or never so great heat, I had always my health as well as I
have in England.
This country is very rich. The king had great store of gold291
sent
him from this place: the time that I was there, the King of Angica
had a great city at Masangana; which city Paulas Dias, Governor of
Angola, took and situated there; and finding hard by it great store of
gold, fortified it with four forts, and walled a great circuit of ground
round about it, and within that wall; now the Portugals do build a
city, and from this city every day they do war against the King of
Angica, and have burnt a great part of his kingdom.
The Angicas292
are men of goodly stature; they file their teeth
before on their upper jaw, and on their under jaw, making a distance
between them like the teeth of a dog; they do eat man’s flesh; they
are the stubbornest nation that lives under the sun, and the
resolutest in the field that ever man saw; for they will rather kill
themselves than yield to the Portugals. They inhabit right under the
line, and of all kinds of Moors these are the blackest. They do live in
the law of the Turks, and honour Mahomet. They keep many
concubines, as the Turks do; they wash themselves every morning
upwards, falling flat on their faces towards the east. They wear their
hair all made in plaits on their heads, as well men as women; they
have good store of wheat, and a kind of grain like vetches, of which
they make bread: they have great store of hens like partridges, and
turkeys, and all their feathers curl on their backs. Their houses are
like the other houses of the kingdoms aforenamed.
And thus I end, showing you as brief as I can, all the nations and
kingdoms, that, with great danger of my life, I travelled through in
twelve years of my best age, getting no more than my travel for my
pain. From this kingdom, Angica, was I brought in irons again to my
master, Salvador Corea de Sasa, to the City of San Sebastian in
Brazil, as you have heard.
APPENDIX II.
A SKETCH OF THE HISTORY OF KONGO
TO THE
end of the seventeenth century.
The Early History of Kongo.
F traditions may be accepted where written history fails us, the
foundation of the Empire of Kongo lies back no further than the
middle of the fifteenth century.
The founder of the dynasty and first King of Kongo—
Ntotela ntinu nekongo—was Nimi a Lukeni, the son of
Nimi a nzima and of Lukeni lua nsanzi, the daughter of
Nsa ku ki-lau. His father appears to have been a mere
village chief in Kurimba (Corimba),293
a district of the
kingdom of Kwangu. He had established himself at a ferry on a great
river (nzari), now known to us as the Kwangu, and levied a toll upon
all travellers who crossed the stream. One day the young man’s aunt
came that way, and claimed exemption on the ground of being the
old chief’s sister. Her brother was absent, and not only was the claim
denied, but young Nimi a Lukeni, notwithstanding that she was with
child, caused her to be disembowelled. The younger members of his
clan looked upon this act of brutality as one of bravery, and shielded
him against his father’s just wrath. He then placed himself at their
head, assumed the title of ntinu (king), and started westward upon
a career of conquest.
The country he was about to invade was inhabited by a people
kindred to those of Angola and of the country to the north of the
Zaire, split up into numerous small clans294
ruled by independent
kinglets. This, no doubt, would account for the rapidity and the
extent of his conquests, which have been matched however, in our
own days, by the Makololo.
Having defeated Mbumbulu mwana Mpangala of Mpemba-kasi, he
founded his capital—Mbazi a nkanu—295
upon a rock within that
chief’s territory. By degrees he extended his conquests southward to
the Kwanza and even beyond, installed his uncle Nsa ku ki-lau as
ruler of the important province of Mbata, bestowed large territories
upon others of his adherents, and even restored some of their
father’s territories to the children of the Mwana Mpangala. His
“sons,” attended by the great Nganga Ngoyo, he sent across the
Zaire, and they became the founders of the “kingdoms” of Kakongo
and Luangu; whilst a third son, by a slave woman, is supposed to be
the ancestor of the “counts” of Sonyo or Soyo.296
Anciently the King
of Kakongo, before he assumed his kingship, was bound to marry a
princess of the blood royal of Kongo, whilst he of Luangu married a
princess of Kakongo; yet the ruler of Luangu was highest in rank, for
he enjoyed the title of nunu (“aged person”), whilst his brother of
Kakongo had to be contented with the inferior title of nkaji
(“spouse”). The Kings were elected by the feudal princes, but their
choice was limited to the sons of princesses, as in a great part of
negro Africa.297
Of the early institutions of Kongo we know next to nothing, though
we may presume that the law of succession was originally the same
there as in the sister-states to the north, for the first Ntotela was
succeeded by two nephews (Nanga kia ntinu and another, whose
name has not reached us). But even thus early, and anterior to the
introduction of Christianity, the old law of succession was broken
through, for Nkuwu a ntinu, the fourth Ntotela, was a son of Ntinu
Nimi a Lukeni, and was succeeded by a son of his own, Nzinga a
Nkuwa, the first Christian Ntotela, better known in history as John I.
If Dapper may be believed, it was the custom to bury twelve virgins
with the earlier kings—a distinction much sought after, as in other
parts of Africa; but the people of Kongo have never been charged
with cannibalism, nor its rulers with the bloody rites practised by the
Jaga.
Cão’s Discovery of the Kongo, 1482.298
It was towards the end of 1482, that the natives at the mouth of the
River Kongo for the first time saw rising above the horizon the white
wings of a European vessel, ascending, as it were, from the Land of
Spirits; and we can imagine their surprise when they for the first
time beheld the bleached faces of its inmates. Yet they came on
board, offering ivory in exchange for cloth. The interpreters from the
Guinea coast who were with Cão naturally failed to make themselves
understood, but they learnt from signs that far inland there dwelt a
powerful king. Cão at once despatched some Christian negroes in
search of this potentate. They were the bearers of suitable presents,
and were instructed to assure the King of the friendly intentions of
his visitors, whose only desire it was to trade with him.
Before continuing his voyage, Cão set up the first of the stone
pillars, or padroes, which he had on board. He then sailed south
along the coast, noting its prominent features, but curiously missed
the Kwanza or River of Angola, although its clayey waters discolour
the sea for ten or fifteen miles. On a low foreland, Cabo do Lobo,299
ten miles beyond the cliffs named by him Castello d’Alter Pedroso, he
set up a second pillar, to mark the furthest point reached by him.
On again returning to the Kongo, he was annoyed to find that his
messengers had not returned; and as he was naturally anxious to
make known in Portugal his discovery of a magnificent river and a
powerful kingdom, he left them behind him, and seized instead four
unsuspecting visitors to his ship as “hostages;” giving their friends to
understand that they should be restored to them after the lapse of
fifteen months, when they would be exchanged for his own men.
These latter appear to have been treated with distinction at first, but
when the King heard of Cão’s high-handed proceedings he refused
to admit them any longer to his presence, and even threatened
them with death, should his own people not be restored.
Among the hostages carried off by Cão there was a man of some
distinction in his own country, Nsaku (Caçuto) by name, who picked
up Portuguese quickly, and much pleased King John by the
information he was able to give. He, as well as his companions, were
much petted in Portugal, and, in defiance of all sumptuary laws,
were dressed in fine cloths and silks.
Cão himself, soon after his arrival, in April, 1484, was appointed a
cavalier in the Royal household, granted an annuity of 18,000 reals,
and on the 14th of that month he was “separated from the common
herd,” and granted a coat-of-arms charged with the two pillars
erected by him during this memorable voyage.
Cão’s Second Voyage, 1485-6.
Cão’s departure on a second voyage was much delayed, either
because the King’s Council were opposed to these adventures, which
strained the resources of a small kingdom like Portugal, or—and this
is more likely—because it was desired that a change in the Royal
Arms, which was only made in June, 1485, should be recorded on
the stone pillars which Cão was to take with him.
Great was the rejoicing when Cão’s “fleet” appeared in the Kongo,
and the hostages, loud in praise of the good treatment they had
received, were once more among their friends. Cão at once
forwarded rich presents to the King, with an invitation to throw aside
all fetishes, and to embrace the only true and saving faith; promising
that, on his return from a voyage to the south, he would personally
visit the capital of his kingdom. This promise Cão was not permitted
to fulfil, for having set up a pillar on Monte Negro (15° 40´ S.) and
another on Cape Cross (21° 50´),300
he died a short distance
beyond. Of the details of his death we know nothing.301
It seems,
however, that the loss of their commander induced a speedy return
home: for Cão’s vessels must have arrived in Portugal before August,
1487, as in that month Dias sailed on his famous voyage, taking with
him the negroes whom Cão had kidnapped to the south of the
Kongo, with a view to their learning Portuguese, and being employed
as interpreters in future voyages.
Cão, therefore, never saw the King of Kongo; and there are good
grounds for believing that Nsaku who was sent by the King to
Portugal to ask for priests, masons, carpenters, agricultural
labourers, and women to make bread, only reached Europe in one of
Dias’s vessels, in December, 1488. Nsaku, most certainly, was first
introduced to King John at Beja, in January, 1489, when he and his
companions were baptised, the King himself, the Queen, and
gentlemen of title acting as sponsors.(312) He was sent back to the
Kongo with Don Gonçalo de Sousa, in December, 1490, about two
years after he had been baptised.302
The Embassy of 1490-1.303
Don João de Sousa, the ambassador, left Portugal on December
19th, 1490, with a fleet commanded by Gonçalo de Sousa, as
captain-major. Among the pilots were Pero d’Alemquer and Pero
Escovar, men famous in the maritime history of Portugal. Ten
Franciscan Friars304
went out with this fleet, and so did Nsaku, the
ambassador of the King of Kongo. The plague was raging at Lisbon
at the time, and before the vessels reached the Cape Verde Islands,
this dreaded disease had carried off João de Sousa (the
ambassador), the captain-major, and many others. Ruy de Sousa, a
nephew of the captain-major, was then chosen to take the place of
D. João de Sousa.
After a voyage of a hundred days the vessels reached the Kongo,
and the Mwana of Sonyo and his son, who had already been
instructed in the Christian doctrine by a priest from S. Thomé, were
baptised on Easter Sunday, April 3rd, 1491, and were thenceforth
known as Don Manuel and Don Antonio da Silva; for it was the
practice of the Portuguese, from the very beginning, to bestow
Portuguese names and titles upon the negroes who submitted to the
sacrament of baptism.
This ceremony performed, Ruy de Sousa started for the King’s
capital,305
which he reached on April 29th. The King received him
seated on a platform, in a chair inlaid with ivory. He wore a loin-
cloth, presented to him by Cão, copper bracelets, and a cap of palm-
cloth. A zebra tail depended from his left shoulder—a badge of
royalty.306
The King was about to join his son Mbemba a Nzinga, Duke of
Nsundi, who had taken the field against the Bateke;307
but before
doing so he was anxious to be baptised. The foundations of a church
having been laid on Rood Day, May 3rd,308
the King and his Queen
were baptised at once by Frei João de Santa Maria, and were named
Don João and Donna Leonor, after the King and Queen of Portugal.
The King, marching for the first time under the banner of the Cross,
and supported by the firearms of his Portuguese allies, came back a
victor to his capital. His eldest son and many nobles were then
baptised.
When Ruy de Sousa departed, he left behind him Frei Antonio309
with other priests, and gave instructions for an exploration of the
Kongo river above the cataracts, which do not appear to have been
acted upon. He also founded a factory near the mouth of the Kongo,
where the enterprising people of S. Thomé had already established
commercial relations, although formal permission to do so was only
granted them by King Manuel on March 26th, 1500. Dom Pedro, a
cousin of the King of Kongo, accompanied him, with nine attendants,
who, having been taught to read and write, returned to their native
country with D. João Soares, early in 1494.310
The missionaries lost no time in preaching the doctrines of their
Church; but whilst Don Affonso proved an ardent Christian, who
recklessly destroyed all fetishes discovered in his province of Nsundi,
the King himself soon grew lukewarm, owing to the priests’
interference with polygamy and other valued social institutions. In
the country at large, the heathen still held their ground.
D. Affonso I, 1509-1540.311
And thus it happened that when João I died in 1509, the chiefs
favoured his second son, Mpanzu a nzinga,312
a heathen, whilst the
dowager queen and the Count of Sonyo took the part of the elder
brother. Don Affonso, immediately on hearing of his father’s illness,
hurried up to the capital, accompanied by only thirty-six Christians.
He found that his father had died. His brother approached with a
mighty army, but five flaming swords seen in the heavens on the eve
of battle gave courage to his small following, whilst a white cross
and the appearance of St. James at the head of the celestial host
struck terror into the hearts of the assailants. They fled in a panic.313
Mpanzu himself was taken, wounded, and decapitated.
Order having been restored throughout the country, King Affonso
availed himself of the presence of Gonçalo Rodriguez Ribeiro, who
had come from Portugal with a number of priests, and was about to
return to that country, to send an embassy to Pope Julius II and
King Manuel.314
The head of this mission was Don Pedro (de
Castro?), a cousin of the King (who was accompanied by his wife),
and with him went D. Manuel, a brother of the King, and D.
Henrique, a son. The presents conveyed to Portugal included seven
hundred copper bracelets, elephant tusks, slaves, parrots, civet cats
and other animals, and native cloth. D. Henrique remained behind at
Rome, where he was ordained and created Bishop of Utica in
1518.315
The mission sent by King Manuel in return was far-reaching in its
effects upon the political development of Kongo.316
Of its magnitude
we may judge when we learn that it embarked in five vessels. Its
leader, Simão da Silva, dying on the road to S. Salvador, his place
was taken by Alvaro Lopes, the Royal factor. In his company were
priests, experienced soldiers, masons and carpenters to build
churches and a royal palace, and a lawyer (leterado) to explain the
law books which figured among the royal gifts, besides horses,
mules, cloth, banners, church furniture and images. The ambassador
was instructed to explain the management of the royal household in
Portugal, and King Affonso quickly learnt the lessons he received,
and at once introduced the Portuguese titles of Duke, Marquis, and
Count. The ambassador likewise had with him an elaborate coat-of-
arms for the King,317
and twenty less ambitious heraldic designs for
his principal noblemen; and the monarch himself adopted a title
closely imitated from that of his “brother” of Portugal.318
The
ambassador was likewise instructed to make inquiries about the
origin of the Kongo in a lake, and to bring home cargoes of slaves,
copper and ivory.
The King was delighted with all these gifts, not being aware that by
accepting them he virtually acknowledged himself to be a vassal of
the King of Portugal; and he published a long manifesto to his
people, in which he dwelt upon his past career, the blessings of the
Christian faith, and the honours now done him. He actually read the
six bulky folios, but he told Ruy d’Aguiar (in 1516) that if
complicated laws like these were to be introduced in his dominions,
not a day would pass without a legal offence of some kind being
committed.319
The intercourse between Kongo and Lisbon must have been very
active in those days. We learn, for instance, that in 1526 the King
asked for physicians and apothecaries, and in 1530 he forwarded to
his “brother” Manuel two silver bracelets, which he had received
from Matamba. Many young Kongoese were sent to Portugal to be
educated; but, to judge from a letter written by the King in 1517, the
results were not always very gratifying.320
Nay, he accuses Antonio
Viera, to whom he entrusted twenty young relations to be taken to
Portugal, of having parted with several among them to Mpanzu-
alumbu, his enemy, and of having left others behind him at S.
Thomé.321
A second embassy left Kongo in 1540, to do homage to
Pope Paul III. It was headed by D. Manuel, a brother of the King,
who had been a member of D. Pedro’s mission. King Affonso
expected the King of Portugal to pay 3,000 cruzados towards the
expenses of this mission, in consideration of the large profits which
he derived from the trade with Kongo.322
As a member of the Church militant, King Affonso deserved well of
the priesthood. He ruthlessly ordered all fetishes to be destroyed
throughout his dominions, but supplied their place with images of
saints, crosses, agni dei, and other ecclesiastical paraphernalia,
which he held to be more effectual. The clergy were numerous in his
day, and in addition to secular priests included Franciscans,
Dominicans and Austin Friars. They were wealthy, too, for lands and
slaves had been given them, and Christian churches arose even in
remote parts of the country. A Franciscan friar, Antonio de Dénis
(known in the world as D. Diogo de Vilhegas) had been appointed
Bishop of S. Thomé and Kongo,323
and took possession of his see in
1534, on which occasion exceptional honours were shown him. He
was a man of energy and much sincerity, but, unhappily for his
Church, survived only a few years. On his death-bed he desired that
D. Henrique, the King’s son, whom he himself had ordained a priest,
when in Rome, and whom the Pope (as already mentioned) had
created Bishop of Utica in 1518, should succeed him in the episcopal
chair. The Pope, however, before he would consent to the
appointment of a native, desired personally to inquire into the
matter. D. Henrique went to Rome, but died on the voyage home, in
1539 or earlier.
King Affonso deserved his reputation as a zealous Christian, and had
certainly proved himself a good friend to the regular and secular
clergy who undertook to convert his people. Yet, as early as 1515,
he had occasion to call upon the King of Portugal to aid him in
suppressing the irregularities of these “unworthy preachers of the
Holy Catholic Faith,” whose inordinate desire of power and
covetousness brought scandal upon the Church, and promised little
for the future.324
Towards the close of his reign, in 1540, one of
these priests, Frei Alvaro, actually attempted to assassinate the King,
in church, and after Mass!325
The Portuguese living at the time in Kongo were placed under a
royal factor and a Corregedor (magistrate), and enjoyed ex-territorial
jurisdiction. They had a factory at Mpinda, at the mouth of the
Kongo, where the King of Portugal levied heavy duties. The
commercial relations do not appear to have been at all times of the
most friendly nature. In 1514 the King complained that Fernão de
Mello, the Governor of S. Thomé, traded with the Mpangu-lungu326
who were his enemies; and in 1526 he remonstrated against the
conduct of the Portuguese slave-merchants. Indeed, so preposterous
were the claims put forward by the Portuguese officials, that King
Affonso, in 1517, humbly begged to be allowed to employ a ship of
his own when trading; or, at least to be exempted from paying the
heavy duties exacted by a foreign, albeit suzerain, power upon the
outlanders trading in his kingdom. These ill-advised exactions
explain, too, why trade gradually deserted the Kongo, and sought
more favourable openings to the south, at Luandu, as is shown by
an inquiry held in 1548.327
The Portuguese made an effort to exploit the mineral wealth of the
country. Ruy Mendes, the “factor of the copper mines,” is stated to
have discovered lead; and Gimdarlach (Durlacher?), a German
“fundidor,” in 1593 discovered copper, lead, and silver. The King,
however, would not allow the mines to be worked, for he feared that
such a concession might cost him his kingdom.
Proposals for the exploration of the interior were made, but bore no
fruit. Gregòrio de Quadra, who had spent several years as a prisoner
among the Arabs, was sent to Kongo in 1520, with instructions to
make his way thence to the country of Prester John. The King
refused his consent; Quadra returned to Portugal, and died a
monk.328
Balthasar de Castro, the companion of Manuel Pacheco in
Angola, desired to explore the upper Kongo in 1526; but neither his
scheme nor that of Manuel Pacheco himself, who was to have built
two brigantines, seems to have been carried out.
Of the domestic wars corned on by the King, we know next to
nothing. Angola and Matamba seem to have been virtually
independent in his day, though the island of Luandu, with its
valuable cowry-fishery, was held by him and his successors until
1649. He conquered, however, Mpanzu-alumbu (Mpangu-lunga?)329
on the lower Kongo, a district inhabited by a predatory tribe.330
That
his successes in these “wars” were due to his Portuguese
mercenaries and their fire-locks is a matter of course.
Don Affonso died in 1540, or soon afterwards, leaving behind him a
son, D. Pedro, who succeeded him, and three daughters.331
D. Pedro and his Successors, 1540-1561.
Pedro I had been educated in Portugal, and is described by Cavazzi
as a wise prince who had inherited all the virtues of his father, and
was a great friend of the missionaries. His reign was apparently a
short one,332
and he was succeeded by a cousin, D. Francisco, who
only reigned two or three years, and left the kingdom to a son,333
D.
Diogo.334
Duarte Lopez describes this prince as a man of noble mind,
witty, intelligent, prudent in council, an upholder of the missionaries,
and at the same time a great warrior who, in the course of a few
years, conquered many of the neighbouring countries. His “wars”
certainly did not enlarge the borders of his kingdom, and the only
war we know of ended in disaster. The Portuguese at S. Salvador,
jealous of the growing commercial importance of Luandu, had
persuaded the King to send an army against Ngola Mbandi, they
themselves furnishing an auxiliary corps. The Kongoese, in spite of
this, were defeated on the river Dande (about 1556); and Ngola not
only appealed to Portugal for protection, but also allied himself with
the Jagas, with whose aid he invaded Kongo (in 1558).
Nor were the relations of D. Diogo with the missionaries quite as
friendly as Lopez would lead us to believe. As early as 1549, D.
Diogo complained of the overbearing conduct of the Jesuits who had
arrived in that year in the company of D. João Baptista, the Bishop
of S. Thomé;335
the priests, on their side, accused the King of having
shown little respect to the bishop, and of having ordered them to be
pulled out of their pulpits, when they denounced his vices and those
of his people.336
The Jesuits may have been over-zealous in the
performance of what they conceived to be their duty, and too prone
to meddle in politics; but they seem to have led clean lives, which
cannot be said of all of their clerical brethren. When D. Gaspar
Cão,337
the Bishop of S. Thomé and Kongo, a man who took the
duties of his office seriously, visited S. Salvador, these priests openly
defied his authority. But after several of the recalcitrant priests had
been deported to Portugal, whilst others had left voluntarily with
such wealth as they had been able to amass, discipline was re-
established.338
A Reign of Anarchy, 1561-1568.
When Diogo died, about 1561, the Portuguese residents
endeavoured to secure the throne for one of their own creatures,
and caused the duly elected favourite of the people to be
assassinated. As a result, the people of S. Salvador rose upon the
Portuguese, many of whom were killed, not even priests being
spared. The accounts339
of this period of disorder are too confused
to enable us to be certain even of the names of the reigning kings.
D. Affonso II, a son (probably illegitimate) of D. Diogo, ascended the
throne of his father, but was murdered by his brother, D. Bernardo,
who appears to have been the candidate favoured by the
Portuguese. He at once sent Father Estevão de Laguos on an
embassy to Queen Catherine of Portugal, who, in a letter dated June
26th, 1562,340
congratulated him upon his accession, whilst gently
chiding him for the murder of his brother. This King was evidently
friendly disposed towards the Portuguese; and Antonio Vieira, a
negro, who had visited Portugal as member of an embassy, when
writing to Queen Catherine in April 1566,341
suggested that he might
be induced to allow the mines of copper and tin to be worked. D.
Bernardo is stated by the Duke of Mbamba to have fallen in a war
with the Anzicas, “in defence of Christianity and the Fatherland.” He
was succeeded by D. Henrique, a brother of D. Diogo, who, after a
short and troubled reign, died of a wound received in a battle, either
against some revolted vassals,342
or fighting the Anzicanas.343
He
was the last king of the original dynasty, for Alvaro I, his successor,
was only a step-son.
D. Alvaro I and the Ayaka, 1568-1574.344
D. Alvaro, immediately on his accession, sent an embassy to
Portugal, to apologise for the massacre of many Portuguese during
the reigns of his predecessors, which he excused on the ground of
the vices and abuses of the clergy. These excuses were apparently
accepted in Portugal, fortunately for D. Alvaro, for the very next year
the dreaded Ayaka345
invaded his kingdom by way of Mbata; and,
being worsted, the King fled with his adherents to the Hippopotamus
Island,346
on the lower Kongo, where they suffered many hardships,
and whence he appealed piteously to the Portuguese for help. This
help was not denied him. Francisco de Gouvea, corregedor of S.
Thomé, in 1570, hastened to his aid with six hundred Portuguese,
expelled the Ayaka, reinstated the King in his capital, and built a wall
round S. Salvador for greater security. The King fully recognised the
value of the service that had been rendered him, for Paulo Dias de
Novaes told Garcia Mendes347
that he acknowledged himself a vassal
of Portugal;348
and as neither gold or silver had been discovered in
his country, he agreed to pay a tribute in njimbos, which he actually
did for a few years.
No sooner was Alvaro once more seated securely upon his throne
than he sent the Count of Sonyo against Ngola (1572). Several
encounters took place in Musulu and Mbuila (Ambuila); but in the
end Ngola was allowed to retain his father’s conquests, the river
Dande being fixed upon as the boundary between the two
kingdoms. Kongo, however, retained possession of the valuable
island of Luandu.
Among other events of this reign we should mention a second visit
of D. Gaspar Cão, the bishop, shortly before his death (in 1574); and
the scandal caused by the burial of a notorious infídel, D. Francisco
Mbula matadi, in the church of S. Cruz, the roof of which was taken
off by night, and the body, carried away by the Devil!349
D. Alvaro only enjoyed his prosperity for a short time, for when
Paulo Dias landed at Luandu, in 1575, he was already dead.350
D. Alvaro II, 1574-1614.
Alvaro II, a son of Alvaro I, is described by Bishop D. Manuel
Baptista as a “zealous Christian, father and friend of all;”351
but it is
evident that he looked not with overmuch favour upon the
Portuguese residents in his country, and he is charged, in a memoir
addressed by Domingos d’Abreu Brito to King Philip I, in 1592 with
having plotted with the kings of Ndongo and Matamba against the
Portuguese. An army which he sent ostensibly to the aid of the
Portuguese in 1583 retired, apparently without striking a blow, whilst
he furnished a contingent to the forces of Matamba which invaded
Angola in 1590. He hindered, by specious excuses, the completion of
a stone fort at Mpinda, which had been commenced in 1609 by
Antonio Gonçalves Pitta, until all the workmen had died. He favoured
Dutch traders to the great detriment of the Portuguese; and we
know from Samuel Braun,352
that an effort was made in 1612 to
expel the Dutch from the Kongo, and that it would have been
successful, had not the natives sided with these heretical enemies,
whose dealings appeared to them to be more generous. Moreover,
the King, although he had promised Sebastian da Costa (1580) that
he would allow the supposed silver mines to be sought for,
eventually refused his consent.353
Turning to Church affairs, we hear of the usual applications for
missionaries, and of several episcopal visitations by D. F. Antonio de
Goiva (1578), D. Manuel de Ulhoa, D. Miguel Baptista Rangel, and D.
Manuel Baptista. D. Manuel de Ulhoa presided over a synod at S.
Salvador, in 1585, and laid down statutes for the government of his
see. D. Miguel Baptista Rangel was the first Bishop of Kongo, which
had been separated from the diocese of S. Thomé by a Bull of May
20th, 1596. His successor, D. Manuel Baptista, resided for several
years in Kongo, where he died in 1621; and a letter addressed to
King Philip II, in 1612,354
speaks of the results of over a century of
missionary effort as insignificant, and describes the people as
incurable barbarians, full of vice.
D. Pedro II Affonso, 1622-1624.
Bernardo II, a son of Alvaro II, only reigned for a few months, for he
was killed by his brother, Alvaro III, and a complaint addressed to
him by the Governor of Angola about the admission of heretical
Dutchmen to trade in Sonyo was answered by his successor. This
Alvaro III, the fratricide, is nevertheless described by Cavazzi as
having been “wise, modest, courageous, and above all a zealous
Christian.” It was during his reign, in 1619, that the Jesuits founded
a college at S. Salvador. A proposed mission of Italian Capuchins
came to nothing, for King Philip of Spain, by royal letters of
September 22nd, 1620, forbade foreign missionaries to enter
Portuguese colonies without first obtaining a royal license.355
Alvaro
III died on May 26th, 1622, and was succeeded by D. Pedro II
Affonso, whom Cavazzi describes as a son of Alvaro III; whilst a
Jesuit canon of S. Salvador,356
who wrote an interesting life of this
prince in 1624, makes him out to have been a son of Mbiki a
ntumba, Duke of Nsundi, and a descendant, in the female line, of
the first King of Kongo. If this biographer can be trusted, he was a
man of much promise, and of a mild, forgiving temper; for although
the Duke of Mbamba had sought his life, he conferred upon him the
marquisate of Wembo. His reign was a short and troubled one. In
August, 1622, the Duke of Mbata had been killed by rebels, and his
vassal, the King of Kwangu (Ocango), had suffered a defeat. João
Corrêa de Souza, the Governor of Angola, summoned him to
surrender Luandu Island and all the copper mines; and this being
refused, the Portuguese under Luiz Gomez, aided by the Jagas,
crossed the Dande at Ikau and invaded Nambu a ngongo, and (in
December) also Mbumbi, where the Duke of Mpemba and many
others were killed and eaten by the Jagas, in spite of their being
Christians. The people of the invaded districts revenged themselves
by killing the Portuguese living in their midst, the King vainly
endeavouring to protect them. These invaders had scarcely been
driven off, when Captain Silvestre Soares, with a body of Jagas,
entered Ngombe and Kabanda. But that which gave most pain to the
King was the destruction of the kingdom of Bangu, and the murder
of its King by the Jagas, with the aid of the King of “Loango,” which
was the “trunk and origin of the kingdom of Kongo.”357
In the midst
of these afflictions, the King was rejoiced to learn the arrival of D.
Simão Mascarenhas at Luanda; but he met with an accident, and
died on April 13th, 1624, after a short reign of less than two years,
and mourned by six sons and two daughters.358
D. Pedro’s successors, 1624-1641.
Garcia, the eldest son of D. Pedro, when elected was only twenty
years of age, He was succeeded by D. Ambrosio, in October, 1626,
whose reign, up till March, 1631, was one continuous warfare with
his powerful vassals. The country became unsafe, and the
Portuguese retired for a time from S. Salvador. Alvaro IV, a son of
Alvaro III, made himself master of the kingdom, and retained
possession until his death, February 25th, 1636. He was succeded by
his son, Alvaro V, who, doubting the loyalty of his half-brothers, the
Duke of Mbamba and the Marquis of Kiowa, made war upon them,
was defeated and taken prisoner, but liberated. Unmindful of the
generosity of his opponents, he once more tried the fortune of
battle, was taken again, and executed (in August, 1636). The Duke
of Mbamba was unanimously elected in his place, and reigned, as
Alvaro VI, until his death on February 22nd, 1641. He waged two
unsuccessful wars against the Count of Sonyo, in 1636 and again in
1637; and was obliged to surrender the district of Makuta (Mocata)
to his adversary.
Garcia II Affonso, o Kimbaku, 1641-1663,359
the half-brother and old companion in arms of Alvaro VI, took
possession of the throne at a critical time; for in August of the year
of his accession, the Dutch captured Luandu, and the fortunes of the
Portuguese were at the lowest ebb. The Dutch lost no time in
sending an embassy to Kongo (1642),360
and these new allies lent
him their assistance in a small war against Mwana Nsala, who had
defied the royal authority.361
But they declined to give effective help
against a more powerful vassal, the Count of Sonyo, as it might have
interfered with their trade interests on the Lower Kongo.362
The
King’s army was defeated twice on April 29th, 1645, when Affonso,
the King’s son, was taken prisoner, and again in July 1648, in the
forest of Mfinda angulu. Meanwhile the Dutch had broken the
padrão set up by Cão at the mouth of the Kongo; they had re-
named S. Antonio’s Bay after their river Pampus at Amsterdam; had
gone to S. Salvador; and at least one of them, Johan Herder,363
had
travelled far inland, and visited the Mwana Nkundi on the Kwangu.
The heretical tracts and books which they liberally distributed were
in due course burnt by the Capuchin friars.
Portugal was, moreover, irritated by the admission of Italian and
Castilian Capuchins, a batch of whom, headed by P. Bonaventura of
Alessano,364
arrived at S. Salvador, on September 2nd, 1645, without
having previously called at Lisbon. This first mission was followed by
three others in 1648, 1651 and 1654,365
and mission stations were
established in Mbata, in Nkusu, Nsundi, Mpemba, Mbwela, and
Wembo (Ovando).366
Among the more noteworthy missionary travels
of the time was that of P. Girolamo of Montesarchio, who visited
Konko a bele (Concobello), in 1652.367
Even greater offence was given to Portugal by a mission which the
King despatched to Rome in 1646, and which arrived there, by way
of Holland, in May, 1648. P. Angelo de Valenza, the head of this
mission, had been instructed to beg the Pope to appoint three
bishops for Kongo, Matamba and the Makoko’s country, without
reference to the claims of Portugal. This the Pope declined to do; but
to show his pleasure at receiving this mission, he had a medal struck
in memory of its visit, with the inscription “Et Congo agnovit
Pastorem,” and sent the King a Royal crown blessed by himself. The
King, however, when his mission returned (1651), and when he
heard that the Pope had refused to change Kongo from an elective
into a hereditary monarchy, grew wroth. He openly renounced
Christianity, forbade the Capuchins to preach the word of God, and
recalled his native ngangas. But when some bags containing relics
and ornaments, which the King had taken out of the churches, were
miraculously spared by a fire which broke out in his palace, he
reconsidered his position. A reconciliation with the Capuchins was
effected, and soon afterwards the King, in penitential robes, actually
marched at the head of a procession which had been organised to
turn away a threatened plague of locusts; he allowed himself to be
crowned by P. Giannuario of Nola, in the name of his Holiness, and
took an active part in the celebration of the Pope’s jubilee.368
Meanwhile the Portuguese had recovered Luandu, and the King was
called upon to pay the penalty for having made friendship with the
Dutch heretics, and admitted foreigners as missionaries.
Bartholomeu de Vasconcellos invaded Kongo. The King at once sent
P. Domingos Cardoso, a Jesuit, and the Capuchin Friar Bonaventura
Sardo, to Luandu, where they had an interview with the Governor
(on February 19th, 1649), and preliminary terms of peace were
arranged.369
The treaty was reported upon by the Conselho
Ultramarino, and confirmed in 1651 at Lisbon, whither Friar
Bonaventura370
of Sorrento had gone to do homage to the King of
Portugal, on behalf of the Prefect of the Capuchins, as also to plead
the cause of his Order in reference to the proposed treaty. The terms
of this treaty, as modified, were as follows:—Castilians or Dutchmen
not to be permitted to reside or travel in Kongo nor their ships to be
admitted, unless provided with a Portuguese passport; the Capuchin
friars to communicate with Rome only by way of Luandu or Lisbon,
and no Castilians to be admitted among them; the Kings of Kongo
and Portugal to mutually assist each other if attacked by an enemy;
an ambassador of the King of Kongo to take up his residence at
Luandu, as also a royal prince, as hostage, or in his absence two or
three men of rank; compensation to be granted for all the losses
suffered by the Portuguese since the arrival of the Dutch, and
fugitive slaves to be surrendered; Portuguese merchants to be
exempted from the payment of tolls; a site to be granted at the
mouth of the Kongo for a fortress; all gold and silver mines to be
ceded to the crown of Portugal, and the country to the south of the
river Dande to be ceded absolutely; and finally the King of Kongo to
acknowledge himself a “tributario” of Portugal.
The King seems to have long hesitated before he ratified this treaty,
for in 1656, Diogo Gomes de Morales was ordered to invade Kongo
to enforce it, and was on the point of crossing the river Loje into
Mbamba, when he was recalled, as envoys from the King had arrived
at Luandu, definitely to arrange the terms of peace.
During the later years of his life, D. Garcia once more fell away from
his Christian teachers, whom he accused of being influenced by
political motives. Suspecting the Duke of Mpemba of a desire to
deprive his son of the succession, he had him executed; and when
the native diviners accused his eldest son, Affonso, of aiming at his
life, he had his second son elected as his successor. He died in 1663.
D. Antonio I, 1663-66.
D. Antonio had been enjoined by his dying father to avenge the
humiliation forced upon him by the Portuguese. He inaugurated his
reign by killing his own brother and other relatives, whom he
suspected of disloyalty. The warnings of heaven—fiery balls, an
earthquake, which destroyed part of his capital, a plague, which
decimated the population—were disregarded by him.
He very soon found himself involved in a war with the Portuguese,
who claimed possession of the mines which had been promised by
treaty, and complained of raids made upon friendly chiefs. On July
13th, 1665, the King called upon his people to rise in defence of
their country and liberty.371
His diviners had promised him an easy
victory. The Portuguese had recently been reinforced from Brazil, yet
the army which they were able to put into the field only numbered
four hundred Europeans, with two field guns and six thousand
negroes. It was commanded by Luiz Lopez de Sequeira, the captain-
major, with whom were Manuel Rebello de Brito, Diogo Rodriguez de
Sá, Simão de Matos and Antonio Araujo Cabreira, the serjeant-major.
The hostile forces met on January 1st, 1666, at Ulanga, near the
Pedras de Ambuilla.372
Antonio, seeing the small force opposed to
him, hoped to gain an easy victory; but the Portuguese, formed in
square, resisted the onslaught of his hosts for six hours. At last the
King left the ranks, desirous of a personal encounter with Lopez de
Sequeira; but he was shot down, his head was cut off, and stuck
upon a pike. His followers fled in dismay. The missionaries assert
that the Virgin Mary, with her Child, was seen to stand by the side of
the Portuguese leader, directing the battle, and that a fiery rain fell
upon the idolaters.373
The Governor of Angola, in commemoration of this victory, built the
chapel of N.S. da Nazareth at Luandu, whilst the King of Portugal
amply rewarded the victors.
A Time of Anarchy, after 1666.
We are indebted to Pedro Mendes for an account of the history of
Kongo from the death of D. Antonio in 1666 to the beginning of the
eighteenth century.374
During that time, according to this authority,
there were fourteen Kings of Kongo, of whom four were beheaded
(or killed) by the Musurongo, five by the Ezikongo, three died a
natural death, and two were survivors when he wrote, namely, D.
Pedro IV, at Salvador, and D. João at Mbula.375
At one time there
were actually three kings in the field.
Alvaro VII, a royal prince who had passed his early life in retirement,
but who, on being raised to the throne, turned out a monster of
iniquity, was killed by his own subjects, abetted by the Count of
Sonyo (1666), under whose auspices took place the election of his
successor, D. Alvaro VIII (1666-70), who was in turn removed by the
Marquis of Mpemba. Alvaro VIII376
had allowed the Portuguese to
search for gold, but this search turned out as fruitless as the search
for silver at Kambambe. Meanwhile D. Affonso III Affonso had been
proclaimed at Kibangu, the new capital (1667), whilst D. Pedro III
nsukia ntamba was put up as an opposition King in Mbula. The latter
defeated his rival, who fled beyond the Mbiriji (Ambriz), and died
there (of poison?). His widow, D. Anna, a daughter of a former King,
Garcia, retired to Nkondo (Mucondo), and survived her husband until
1680. The people proclaimed D. Garcia III nenganga mbemba377
his
successor, whilst the opposition, at the old capital (S. Salvador),
declared D. Daniel de Guzman, descendant of Mpanzu (Alvaro I), to be
the rightful King. D. Daniel took the field against D. Garcia III, but,
before he reached the residence of that King, he was overtaken by
D. Pedro of Mbula; his army was dispersed, and himself beheaded.
His children sought refuge with the Count of Sonyo, and by
treachery they succeeded in getting D. Pedro into their power, and
killed him. The people of Mbula thereupon raised his brother, D.
João, to the throne, who survived until after 1710. S. Salvador, after
D. Daniel had deserted it, became the haunt of wild beasts.
Meanwhile D. Rafael, Marquis of Mpemba, who had been proclaimed
King some time anterior to this, had been obliged to seek refuge
among the Portuguese, and his reinstatement was one of the objects
of the disastrous expedition of 1670,378
by which it was sought to
punish Count Estevão da Silva of Sonyo for his desecration of
Christian churches and the ill-treatment of Portuguese traders: or,
rather, his dealings with heretic competitors.
João Soares de Almeida, the commander of this expedition, had with
him five hundred Portuguese, supported by a strong force of native
allies, among whom was a Jaga Kalandula. He won a battle, in which
Estevão was killed; but Pedro, the brother of the unfortunate Count,
rallied the forces of Sonyo, unexpectedly fell upon the Portuguese
near the Mbiriji (Ambriz),and scarcely a man among them escaped.
Count Pedro then expelled the Italian Capuchins, who were
supposed to be friendly to Portugal, and invited in their stead
Belgian members of the same Order, who arrived in September,
1673, under the lead of P. Wouters. But, having been accused of
stopping the rain, and having in reply excommunicated the Count,
they were speedily expelled.379
Peace between Sonyo and Portugal
was only restored in 1690, when the former promised to abolish
idolatry and to sell no slaves to heretics.
It was about this period (between 1669 and 1675) that Francisco do
Murça, the captain-major of Dande, visited S. Salvador, and
proceeded thence to Mbata and the Kwangu, where he was told that
this river flowed through the kingdom of the Makoko, and entered
the sea at Mpinda, a fact long before known to the missionaries.
These latter had not quite abandoned the Kongo, notwithstanding
these troubles, and in 1668 the Capuchins still occupied their
monasteries at the capital of Mbamba and at Mpembu;380
whilst
Girolamo Merolla (1682-88) and Antonio Zucchelli steadily laboured
(1700-02) in Sonyo and Luangu.381
D. Andre succeeded D. Garcia, but died after a short reign. D. Manuel
nzinga elenge, a descendant of Mpanzu, was duly elected, but
expelled by the sons of the late D. Garcia, who raised Alvaro IX to
the throne in his stead. This prince was never recognised by the
Count of Sonyo, who looked upon D. Manuel, who had sought refuge
with him, as the legitimate King. He was reinstated by him for a
time, but ultimately fell into the power of his enemies, and was
beheaded.
Alvaro IX was succeeded in 1694 by his brother Pedro IV nsanu a
mbemba, also known as agoa rosada,382
who once more returned to
the ancient capital. He and D. João of Mbula were the only Kings
alive in 1701, when the Capuchin Friar Francisco de Pavia, and his
colleague Friar João Maria went throughout the kingdom of Kongo,
preaching peace, and calling upon the leading men to recognise D.
Pedro as their King; and thus put an end to quarrels which had
distracted the country for an entire generation.
A Retrospect.
And if we ask to what extent, and in what manner, have the natives
of Kongo been benefited by two centuries of contact with the
civilisation of Europe, and of missionary effort, we feel bound to
admit that they have not been benefited at all—either materially or
morally. On the contrary. There were, no doubt, a few earnest men
among the missionaries, and the Church of Rome deserves some
credit for the zeal with which she addressed herself to the object of
converting the natives. At the same time it cannot be denied that the
instruments she employed, the methods she pursued, and the
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

More Related Content

PPTX
Session i
PDF
NET Programming A Practical Guide Using C 1st Edition Pradeep Tapadiya
PPT
Everything You Never Wanted To Know About Net Generics
PDF
Unit I- Introduction to .NET Framework.pdf
PDF
tybsc it asp.net full unit 1,2,3,4,5,6 notes
PDF
NET Programming A Practical Guide Using C 1st Edition Pradeep Tapadiya
PDF
Reasons Why .NET framework is Most Demanding in 2023?
PDF
Net In Action Second Edition Meap V06 2nd Chapters 1 To 12 Of 13 Dustin Metzgar
Session i
NET Programming A Practical Guide Using C 1st Edition Pradeep Tapadiya
Everything You Never Wanted To Know About Net Generics
Unit I- Introduction to .NET Framework.pdf
tybsc it asp.net full unit 1,2,3,4,5,6 notes
NET Programming A Practical Guide Using C 1st Edition Pradeep Tapadiya
Reasons Why .NET framework is Most Demanding in 2023?
Net In Action Second Edition Meap V06 2nd Chapters 1 To 12 Of 13 Dustin Metzgar

Similar to Net 40 Generics Beginners Guide Sudipta Mukherjee (20)

PDF
NET Programming A Practical Guide Using C 1st Edition Pradeep Tapadiya
PPTX
.Net framework
PDF
Microsfot’s .NET 5 Is All Set To Prove It’s Worth.pdf
PPTX
Why is .Net Technology Recognised for Software Development?
PDF
Why is .Net Technology Recognised for Software Development?
PDF
.NET TECHNOLOGIES
PDF
Dot net interview_questions
PPT
Synapse india fundamentals of dotnet development
DOCX
Vb.net class notes
PDF
Top 7 Benefits & Features of .NET Framework For Developers
PPTX
.NET Comprehensive guide to C# Covering advance topics and best practices.
PDF
Practical guide for building web applications with ASP .NET core.
PDF
Chapter1
PDF
Harness the Potential of .NET for Software Development
PPTX
.NET Vs. Java: Which Framework/Language Should Developers Choose?
PPT
Inside .net framework
PDF
Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)
PDF
Dot net interview_questions
PDF
Dot net interview_questions
PDF
Dotnet interview qa
NET Programming A Practical Guide Using C 1st Edition Pradeep Tapadiya
.Net framework
Microsfot’s .NET 5 Is All Set To Prove It’s Worth.pdf
Why is .Net Technology Recognised for Software Development?
Why is .Net Technology Recognised for Software Development?
.NET TECHNOLOGIES
Dot net interview_questions
Synapse india fundamentals of dotnet development
Vb.net class notes
Top 7 Benefits & Features of .NET Framework For Developers
.NET Comprehensive guide to C# Covering advance topics and best practices.
Practical guide for building web applications with ASP .NET core.
Chapter1
Harness the Potential of .NET for Software Development
.NET Vs. Java: Which Framework/Language Should Developers Choose?
Inside .net framework
Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)
Dot net interview_questions
Dot net interview_questions
Dotnet interview qa
Ad

Recently uploaded (20)

PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
Cell Types and Its function , kingdom of life
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Classroom Observation Tools for Teachers
PPTX
GDM (1) (1).pptx small presentation for students
PPTX
Cell Structure & Organelles in detailed.
PDF
Complications of Minimal Access Surgery at WLH
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
01-Introduction-to-Information-Management.pdf
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
PPH.pptx obstetrics and gynecology in nursing
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
VCE English Exam - Section C Student Revision Booklet
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Cell Types and Its function , kingdom of life
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
O7-L3 Supply Chain Operations - ICLT Program
O5-L3 Freight Transport Ops (International) V1.pdf
Classroom Observation Tools for Teachers
GDM (1) (1).pptx small presentation for students
Cell Structure & Organelles in detailed.
Complications of Minimal Access Surgery at WLH
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
STATICS OF THE RIGID BODIES Hibbelers.pdf
01-Introduction-to-Information-Management.pdf
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
TR - Agricultural Crops Production NC III.pdf
Supply Chain Operations Speaking Notes -ICLT Program
PPH.pptx obstetrics and gynecology in nursing
Ad

Net 40 Generics Beginners Guide Sudipta Mukherjee

  • 1. Net 40 Generics Beginners Guide Sudipta Mukherjee download https://ebookbell.com/product/net-40-generics-beginners-guide- sudipta-mukherjee-2518856 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. Aspnet 40 In Practice Pappsc Daniele Bochicchio Stefano Mostarda https://ebookbell.com/product/aspnet-40-in-practice-pappsc-daniele- bochicchio-stefano-mostarda-2327468 Introducing Net 40 With Visual Studio 2010 Experts Voice In Net 1st Edition Alex Mackey https://ebookbell.com/product/introducing-net-40-with-visual- studio-2010-experts-voice-in-net-1st-edition-alex-mackey-2527400 Aspnet 40 Projects Covers Net 35 And Net 40 Codes Black Book Kogent Learning Solutions Inc https://ebookbell.com/product/aspnet-40-projects-covers-net-35-and- net-40-codes-black-book-kogent-learning-solutions-inc-231815770 Aspnet 40 Programming Joydip Kanjilal https://ebookbell.com/product/aspnet-40-programming-joydip- kanjilal-170487994
  • 3. Sams Teach Yourself Aspnet 40 In 24 Hours Complete Starter Kit Mitchell https://ebookbell.com/product/sams-teach-yourself- aspnet-40-in-24-hours-complete-starter-kit-mitchell-21995470 Pro Dynamic Net 40 Applications Datadriven Programming For The Net Framework 1st Edition Carl Ganz Jr https://ebookbell.com/product/pro-dynamic-net-40-applications- datadriven-programming-for-the-net-framework-1st-edition-carl-ganz- jr-2309974 Pro Dynamic Net 40 Applications 1st Edition Carl Ganz Jr https://ebookbell.com/product/pro-dynamic-net-40-applications-1st- edition-carl-ganz-jr-50640784 Comdex Net Programming Course Kit Covering Net Framework 40 Vb 2010 C 2010 And Aspnet 40 Vikas Gupta https://ebookbell.com/product/comdex-net-programming-course-kit- covering-net-framework-40-vb-2010-c-2010-and-aspnet-40-vikas- gupta-231677358 Pro Vb 2010 And The Net 40 Platform 1st Edition Andrew Troelsen https://ebookbell.com/product/pro-vb-2010-and-the-net-40-platform-1st- edition-andrew-troelsen-2098406
  • 6. .NET 4.0 Generics Beginner's Guide Enhance the type safety of your code and create applications easily using Generics in the .NET 4.0 Framework Sudipta Mukherjee BIRMINGHAM - MUMBAI
  • 7. .NET 4.0 Generics Beginner's Guide Copyright © 2012 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: January 2012 Production Reference: 1190112 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-84969-078-2 www.packtpub.com Cover Image by Asher Wishkerman (a.wishkerman@mpic.de)
  • 8. Credits Author Sudipta Mukherjee Reviewers Atul Gupta WEI CHUNG, LOW Antonio Radesca Acquisition Editor David Barnes Lead Technical Editor Meeta Rajani Technical Editors Veronica Fernandes Copy Editor Laxmi Subramanian Project Coordinator Vishal Bodwani Proofreader Joanna McMahon Indexer Monica Ajmera Mehta Rekha Nair Graphics Manu Joseph Production Coordinator Alwin Roy Cover Work Alwin Roy
  • 10. Foreword It is my pleasure to write the foreword to a book which will introduce you to the world of generic programming with C# and other .NET languages. You will be able to learn a lot from this book, as it introduces you to the elegant power of generic programming in C#. Through it, you will become a better C# programmer, and a better programmer in all future languages you might choose to use. It is now almost 10 years since .NET Generics was first described in publications from Microsoft Research, Cambridge, a project I was able to lead and contribute to, and six years since it was released in product form in C# 2.0. In this foreword, I would like to take a moment to review the importance of .NET Generics in the history of programming languages, and the way it continues to inspire a new generation of programmers. When we began the design of C# and .NET Generics, generic programming was not new. However, it was considered to be outside the mainstream, and attempts to change that with C++ templates and proposals for Java Generics were proving highly problematic for practitioners. At Microsoft Research, we pride ourselves on solving problems at their core. The three defining core features of .NET Generics as we designed them were efficient generics over value types with code generation and sharing managed by the virtual machine, reified run-time types, and language neutrality. These technical features are now widely acknowledged to represent the "right" fundamental design choices for programming language infrastructure. They are not easy to design or build, and they are not easy to deliver, and when Microsoft Research embarked on this project, we believe we put the .NET platform many years ahead of its rivals. The entire credit goes to Microsoft and people such as Bill Gates, Eric Rudder, and Anders Hejlsberg for taking the plunge to push this into our range of programming languages. However, without the prototyping, research, engineering, and incessant advocacy by Microsoft Research, C# and .NET Generics would never be in their current form.
  • 11. Let's take some time to examine why this was important. First, .NET Generics represents the moment where strongly typed and functional programming entered the mainstream. .NET Generics enabled C# to become more functional (through LINQ, Lambdas, and generic collections), and it enabled a new class of strongly typed, fully functional .NET languages (such as F#) to thrive. Further, .NET Generics also enabled new key programming techniques, such as Async programming in F# 2.0 and C# 5.0, and Rx programming for reactive systems. Even though you may not realize it, you'll have learned a lot of functional programming by the end of this book. Next, .NET Generics categorically proved that strongly typed object-oriented programming can integrate seamlessly with generic programming. It is hard to describe the extent to which .NET Generics managed to defeat the "object fundamentalists" of the 1990s (who want a world where there is nothing but classes). These people, many still occupying powerful positions in the software industry, seemed satisfied with a world where programmers are less productive, and programs less efficient, in the name of orthodoxy. Today, no practicing programmer or language designer with experience of .NET Generics would design a strongly typed programming language that does not include Generics. Further, almost every .NET API now features the use of .NET Generics, and it has become an essential weapon in the programmer's toolkit for solving many problems. Finally, and for me most importantly, .NET Generics represents the victory of pragmatic beauty over pragmatic ugliness. In the eyes of many, alternative solutions to the problem of generic programming such as Java's "erasure" of Generics are simply unpleasant "hacks". This leads to reduced productivity when using those languages. In contrast, .NET Generics is perhaps the most smoothly integrated advanced programming language feature ever constructed. It integrates with reflection, .NET NGEN pre-compilation, debugging, and run- time code generation. I've had many people e-mail me to say that .NET Generics is their favorite programming language feature. That is what language research is all about. I trust you will learn a great deal from this book, and enjoy the productivity that comes from C#, and .NET languages such as F#. Dr. Don Syme Principal Research, Microsoft Research, Cambridge, U.K.
  • 12. Generic types are more than just lists of T. Functional programmers have known this for a long time. C++ programmers who use templates knew this too. But 10 years ago when Don Syme and I first designed and prototyped the Generics feature of the .NET run-time, most mainstream developers were constrained by the rudimentary type systems of languages such as Visual Basic and Java, writing type-generic code only by resorting to casting tricks or worse. In that space, it's hard to conceive of myriad uses of generic types beyond lists and simple collections, and it's fair to say that there was some resistance to our design! Fortunately, some forward thinkers in Microsoft's .NET run-time team regarded Generics in managed languages as more than an academic indulgence, and committed substantial resources to completing a first-class implementation of Generics that is deeply embedded in the run-time languages and tools. We've come a long way in 10 years! Managed code frameworks make liberal use of generic types, ranging from obvious collection types such as List and Dictionary, through `action' types such as Func and IEnumerable, to more specialized use of Generics such as Lazy initialization. Blogs and online forums are full of discussions on sophisticated topics such as variance and circular constraints. And if it weren't for Generics, it's hard to see how newer language features such as LINQ, or even complete languages such as F#, could have got off the ground. Coming back, Generics really does start with List<T>, and this book sensibly begins from there. It then takes a leisurely tour around the zoo of generic types in the .NET Framework and beyond, to Power Collections and C5. The style is very much one of exploration: the reader is invited to experiment with Generics, prodding and poking a generic type through its methods and properties, and thereby understand the type and solve problems by using it. As someone whose background is in functional programming, in which the initial experience is very much like experimenting with a calculator, I find this very appealing. I hope you like it as much as I do. Andrew Kennedy Microsoft Research, Cambridge, U.K.
  • 13. About the Author Sudipta Mukherjee was born in Kolkata and migrated to Bangalore, the IT capital of India, to assume the position of a Senior Research Engineer in a renowned research lab. He is an Electronics Engineer by education and a Computer Engineer/Scientist by profession and passion. He graduated in 2004 with a degree in Electronics and Communication Engineering. He has been working with .NET Generics since they first appeared in the .NET Framework 2.0. He has a keen interest in data structure, algorithms, text processing, natural language processing ,programming language, tools development, and game development. His first book on data structure using the C programming language has been well received. Parts of the book can be read on Google Books at http://goo.gl/pttSh. The book was also translated into Simplified Chinese available on Amazon at http://goo.gl/lc536. He is an active blogger and an open source enthusiast. He mainly blogs about programming and related concepts at sudipta.posterous.com. Inspired by several string processing methods in other languages, he created an open source string processing framework for .NET, available for free at stringdefs.codeplex.com. He lives in Bangalore with his wife. He can be reached via e-mail at sudipto80@yahoo.com and via Twitter at @samthecoder.
  • 14. Acknowledgement Books like this cannot be brought to life by the author alone. I want to take this opportunity to thank all the people who were involved in this book in any way. First of all, I want to thank Microsoft Research for bringing Generics into the .NET Framework. Great work guys. I have used STL in C++ and Collections in Java. But I can say without being biased that Generics in .NET is the smartest implementation of generic programming paradigm that I have ever come across. Without that, I wouldn't have anything to write about. I owe a big "Thank You" to the Senior Acquisition Editor and Publisher David Barnes at Packt Publishing for offering me this opportunity to write for them. I want to thank Vishal Bodwani and Meeta Rajani, also from Packt Publishing, for their great support. Everytime I missed a deadline, they helped me get back on track. Thanks for bearing with me. Last but not the least, I want to thank my Technical Editors Snehal and Veronica who painstakingly corrected all the mistakes, did all the formatting, without which the book would not have been possible. Thanks a lot. I have no words to express my gratitude towards Don and Andrew for taking time off to read the manuscript and their kind words. Thank you Don. Thank you Andrew. I want to thank all the reviewers of the book. Thanks for all your great feedback. It really made the book better. My wife, Mou, motivated me to write this book. She stood by me when I needed her throughout all these months. Thank you sweetheart. Last but not the least, I can't thank my mom Dipali and dad Subrata enough for finding the love of my life and always being supportive. Thank you mom. Thank you dad.
  • 15. About the Reviewers Atul Gupta, is currently a Principal Technology Architect at Infosys' Microsoft Technology Center. He also has close to 15 years of experience working on Microsoft technologies. His expertise spans user interface technologies, and he currently focuses on Windows Presentation Foundation (WPF) and Silverlight technologies. Other technologies of interest to him are Touch (Windows 7), Deepzoom, Pivot, Surface, and Windows Phone 7. He recently co-authored the book "ASP.NET 4 Social Networking", Packt Publishing (http:// www.packtpub.com/asp-net-4-social-networking/book). His prior interest areas were COM, DCOM, C, VC++, ADO.NET, ASP.NET, AJAX, and ASP.NET MVC. He has also authored papers for industry publications and websites, some of which are available on Infosys' Technology Showcase (http://www.infosys.com/microsoft/ resource-center/pages/technology-showcase.aspx). Along with colleagues from Infosys, Atul is also an active blogger (http://www.infosysblogs.com/microsoft). Being actively involved in professional Microsoft online communities and developer forums, Atul has received Microsoft's Most Valuable Professional award for multiple years in a row. WEI CHUNG, LOW, a Technical Lead in BizTalk and .NET, and a MCT, MCPD, MCITP, MCTS, and MCSD.NET, works with ResMed (NYSE: RMD), at its Kuala Lumpur, Malaysia campus. He is also a member of PMI, certified as a PMP. He started working on Microsoft .NET very early on and has been involved in development, consultation, and corporate training in the areas of business intelligence, system integration, and virtualization. He has been working for the Bursa Malaysia (formerly Kuala Lumpur Stock Exchange) and Shell IT International previously, which prepared him with rich integration experience across different platforms. He strongly believes that great system implementation delivers precious value to the business, and integration of various systems across different platforms shall always be a part of it, just as people from different cultures and diversities are able to live in harmony in most of the major cities.
  • 16. Antonio Radesca has over 15 years of programming experience. He has a degree in Computer Science and is interested in architectures, programming languages, and enterprise development. He has worked at some of the most important Italian companies, especially at Microsoft .NET Framework as a Developer and an Architect. His expertise spans .NET programming to mobile development on iOS, Android, and Windows Phone.
  • 17. www.PacktPub.com Support files, eBooks, discount offers and more You might want to visit www.PacktPub.com for support files and downloads related to your book. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service@packtpub.com for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks. http://PacktLib.PacktPub.com Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books. Why Subscribe? ‹ ‹ Fully searchable across every book published by Packt ‹ ‹ Copy and paste, print and bookmark content ‹ ‹ On demand and accessible via web browser Free Access for Packt account holders If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.
  • 18. Table of Contents Preface 1 Chapter 1: Why Generics? 7 An analogy 8 Reason 1: Generics can save you a lot of typing 8 Reason 2: Generics can save you type safety woes, big time 10 What's the problem with this approach? 12 Reason 3: Generics leads to faster code 14 Reason 4: Generics is now ubiquitous in the .NET ecosystem 15 Setting up the environment 15 Summary 17 Chapter 2: Lists 19 Why bother learning about generic lists? 20 Types of generic lists 20 Checking whether a sequence is a palindrome or not 22 Time for action – creating the generic stack as the buffer 24 Time for action – completing the rest of the method 26 Designing a generic anagram finder 28 Time for action – creating the method 29 Life is full of priorities, let's bring some order there 32 Time for action – creating the data structure for the prioritized shopping list 33 Time for action – let's add some gadgets to the list and see them 34 Time for action – let's strike off the gadgets with top-most priority after we have bought them 37 Time for action – let's create an appointment list 40 Live sorting and statistics for online bidding 41 Time for action – let's create a custom class for live sorting 42 Why did we have three LinkedList<T> as part of the data structure? 47 An attempt to answer questions asked by your boss 47
  • 19. Table of Contents [ ii ] Time for action – associating products with live sorted bid amounts 47 Time for action – finding common values across different bidding amount lists 50 You will win every scrabble game from now on 52 Time for action – creating the method to find the character histogram of a word 52 Time for action – checking whether a word can be formed 53 Time for action – let's see whether it works 54 Trying to fix an appointment with a doctor? 56 Time for action – creating a set of dates of the doctors' availability 57 Time for action – finding out when both doctors shall be present 58 Revisiting the anagram problem 60 Time for action – re-creating the anagram finder 60 Lists under the hood 64 Summary 65 Chapter 3: Dictionaries 67 Types of generic associative structures 68 Creating a tag cloud generator using dictionary 69 Time for action – creating the word histogram 69 Creating a bubble wrap popper game 73 Time for action – creating the game console 74 Look how easy it was! 77 How did we decide we need a dictionary and not a list? 78 Let's build a generic autocomplete service 79 Time for action – creating a custom dictionary for autocomplete 79 Time for action – creating a class for autocomplete 82 The most common pitfall. Don't fall there! 88 Let's play some piano 88 Time for action – creating the keys of the piano 89 How are we recording the key strokes? 94 Time for action – switching on recording and playing recorded keystrokes 95 How it works? 96 C# Dictionaries can help detect cancer. Let's see how! 97 Time for action – creating the KNN API 97 Time for action – getting the patient records 102 Time for action – creating the helper class to read a delimited file 103 Time for action – let's see how to use the predictor 104 Tuples are great for many occasions including games 105 Time for action – putting it all together 106 Why have we used Tuples? 113 How did we figure out whether the game is over or not? 115 Summary 116
  • 20. Table of Contents [ iii ] Chapter 4: LINQ to Objects 117 What makes LINQ? 118 Extension methods 118 Time for action – creating an Extension method 119 Time for action – consuming our new Extension method 120 Check out these guidelines for when not to use Extension methods 122 Object initializers 122 Collection initializers 123 Implicitly typed local variables 124 Anonymous types 124 Lambda expressions 125 Functors 125 Predicates 127 Actions 127 Putting it all together, LINQ Standard Query Operators 128 Time for action – getting the LINQPad 129 Restriction operators 131 Where() 131 Time for action – finding all names with *am* 131 Time for action – finding all vowels 132 Time for action – finding all running processes matching a Regex 133 Time for action – playing with the indexed version of Where() 134 Time for action – learn how to go about creating a Where() clause 135 Projection operators 136 Select() 137 Time for action – let's say "Hello" to your buddies 137 Making use of the overloaded indexed version of Select() 138 Time for action – radio "Lucky Caller" announcement 138 SelectMany() 140 Time for action – flattening a dictionary 140 Partitioning operators 141 Take() 141 Time for action – leaving the first few elements 142 TakeWhile() 143 Time for action – picking conditionally 143 Skip() 145 Time for action – skipping save looping 145 SkipWhile() 146 Ordering operators 147 Reverse() 147 Time for action – reversing word-by-word 147 Time for action – checking whether a given string is a palindrome or not 148 OrderBy() 149
  • 21. Table of Contents [ iv ] Time for action – sorting names alphabetically 149 Time for action – sorting 2D points by their co-ordinates 151 OrderByDescending() 152 ThenBy() 152 Time for action – sorting a list of fruits 152 What's the difference between a sequence of OrderBy().OrderBy() and OrderBy().ThenBy()? 154 ThenByDescending() 154 Grouping operator 154 GroupBy() 154 Time for action – indexing an array of strings 154 Time for action – grouping by length 156 Set operators 158 Intersect() 158 Time for action – finding common names from two names' lists 159 Union() 160 Time for action – finding all names from the list, removing duplicates 161 Concat() 162 Time for action – pulling it all together including duplicates 162 Except() 162 Time for action – finding all names that appear mutually exclusively 163 Distinct() 164 Time for action – removing duplicate song IDs from the list 165 Conversion operators 166 ToArray() 167 Time for action – making sure it works! 167 ToList() 168 Time for action – making a list out of IEnumerable<T> 168 ToDictionary() 169 Time for action – tagging names 169 ToLookup() 171 Time for action – one-to-many mapping 171 Element operators 172 First() 172 Time for action – finding the first element that 172 satisfies a condition 172 How First() is different from Single()? 173 FirstOrDefault() 173 Time for action – getting acquainted with FirstOrDefault() 173 Last() 174 LastOrDefault() 174 SequenceEquals() 174 Time for action – checking whether a sequence is palindromic 174 ElementAt() 175 Time for action – understanding ElementAt() 176 ElementAtOrDefault() 177
  • 22. Table of Contents [ v ] DefaultIfEmpty() 177 Time for action – check out DefaultIfEmpty() 178 Generation operators 178 Range() 178 Time for action – generating arithmetic progression ranges 179 Time for action – running a filter on a range 179 Repeat() 180 Time for action – let's go round and round with Repeat() 180 Quantifier operators 181 Single() 181 Time for action – checking whether there is only one item matching this pattern 182 SingleOrDefault() 183 Time for action – set to default if there is more than one matching elements 183 Any() 184 Time for action – checking Any() 185 All() 186 Time for action – how to check whether all items match 186 a condition 186 Merging operators 187 Zip() 187 Summary 188 Chapter 5: Observable Collections 189 Active change/Statistical change 190 Passive change/Non-statistical change 191 Data sensitive change 191 Time for action – creating a simple math question monitor 193 Time for action – creating the collections to hold questions 194 Time for action – attaching the event to monitor the collections 195 Time for action – dealing with the change as it happens 197 Time for action – dealing with the change as it happens 199 Time for action – putting it all together 200 Time for action – creating a Twitter browser 201 Time for action – creating the interface 202 Time for action – creating the TweetViewer user control design 203 Time for action – gluing the TweetViewer control 205 Time for action – putting everything together 208 Time for action – dealing with the change in the list of names in the first tab 209 Time for action – a few things to beware of at the form load 210 Time for action – things to do when names get added or deleted 211 Time for action – sharing the load and creating a task for each BackgroundWorker 213 Time for action – a sample run of the application 216 Summary 219
  • 23. Table of Contents [ vi ] Chapter 6: Concurrent Collections 221 Creating and running asynchronous tasks 222 Pattern 1: Creating and starting a new asynchronous task 222 Pattern 2: Creating a task and starting it off a little later 222 Pattern 3: Waiting for all running tasks to complete 222 Pattern 4: Waiting for any particular task 222 Pattern 5: Starting a task with an initial parameter 222 Simulating a survey (which is, of course, simultaneous by nature) 223 Time for action – creating the blocks 223 Devising a data structure for finding the most in-demand item 227 Time for action – creating the concurrent move-to-front list 228 Time for action – simulating a bank queue with multiple tellers 234 Time for action – making our bank queue simulator more useful 239 Be a smart consumer, don't wait till you have it all 241 Exploring data structure mapping 242 Summary 243 Chapter 7: Power Collections 245 Setting up the environment 246 BinarySearch() 248 Time for action – finding a name from a list of names 248 CartesianProduct() 249 Time for action – generating names of all the 52 playing cards 249 RandomShuffle() 250 Time for action – randomly shuffling the deck 250 NCopiesOf() 252 Time for action – creating random numbers of any given length 252 Time for action – creating a custom random number generator 253 ForEach() 256 Time for action – creating a few random numbers of given any length 256 Rotate() and RotateInPlace() 257 Time for action – rotating a word 258 Time for action – creating a word guessing game 258 RandomSubset() 262 Time for action – picking a set of random elements 262 Reverse() 263 Time for action – reversing any collection 263 EqualCollections() 264 Time for action – revisiting the palindrome problem 264 DisjointSets() 265 Time for action – checking for common stuff 265
  • 24. Table of Contents [ vii ] Time for action – finding anagrams the easiest way 266 Creating an efficient arbitrary floating point representation 267 Time for action – creating a huge number API 267 Creating an API for customizable default values 273 Time for action – creating a default value API 273 Mapping data structure 277 Algorithm conversion strategy 277 Summary 278 Chapter 8: C5 Collections 279 Setting up the environment 281 Time for action – cloning Gender Genie! 281 Time for action – revisiting the anagram problem 287 Time for action – Google Sets idea prototype 288 Time for action – finding the most sought-after item 294 Sorting algorithms 299 Pattern 1: Sorting an array of integers 300 Pattern 2: Partially sorting an array—say, sort first five numbers of a long array 300 Pattern 3: Sorting a list of string objects 301 Summary 302 Chapter 9: Patterns, Practices, and Performance 303 Generic container patterns 304 How these are organized 304 Pattern 1: One-to-one mapping 304 Pattern 2: One-to-many unique value mapping 305 Pattern 3: One-to-many value mapping 306 Pattern 4: Many-to-many mapping 307 A special Tuple<> pattern 308 Time for action – refactoring deeply nested if-else blocks 310 Best practices when using Generics 312 Selecting a generic collection 314 Best practices when creating custom generic collections 315 Performance analysis 317 Lists 317 Dictionaries/associative containers 318 Sets 318 How would we do this investigation? 318 Benchmarking experiment 1 319 Benchmarking experiment 2 324 Benchmarking experiment 3 328 Benchmarking experiment 4 330 Benchmarking experiment 5 334
  • 25. Table of Contents [ viii ] Benchmarking experiment 6 336 Benchmarking experiment 7 340 Benchmarking experiment 8 344 Benchmarking experiment 9 345 Summary 348 Appendix A: Performance Cheat Sheet 349 Parameters to consider 353 Appendix B: Migration Cheat Sheet 357 Appendix C: Pop Quiz Answers 361 Chapter 2 361 Lists 361 Chapter 3 361 Dictionaries 361 Chapter 4 362 LINQ to Objects 362 Index 363
  • 26. Preface Thanks for picking up this book. This is an example-driven book. You will learn about several generic containers and generic algorithms available in the .NET Framework and a couple of other majorly accepted APIs such as Power Collections and C5 by building several applications and programs. Towards the end, several benchmarkings have been carried out to identify the best container for the job at hand. What this book covers Chapter 1, Why Generics?, introduces .NET Generics. We will examine the need for the invention of Generics in the .NET Framework. If you start with a feel of "Why should I learn Generics?", you will end with a feeling of "Why didn't I till now?" Chapter 2, Lists, introduces you to several kinds of lists that .NET Generics has to offer. There are simple lists and associative lists. You shall see how simple lists can deliver amazing results avoiding any typecasting woes and boosting performance at the same time. Chapter 3, Dictionaries, explains the need for associative containers and introduces you to the associative containers that .NET has to offer. If you need to keep track of one or multiple dependent variables while one independent variable changes, you need a dictionary. For example, say you want to build a spell check or an autocomplete service, you need a dictionary. This chapter will walk you through this. Along the way, you will pick up some very important concepts. Chapter 4, LINQ to Objects, explains LINQ to objects using extension methods. LINQ or Language Integrated Query is a syntax that allows us to query collections unanimously. In this chapter, we will learn about some standard LINQ Standard Query Operators (LSQO) and then use them in unison to orchestrate an elegant query for any custom need.
  • 27. Preface [ 2 ] Chapter 5, Observable Collections, introduces observable collections. Observing events on collections has been inherently difficult. That's going to change forever, thanks to observable collections. You can now monitor your collections for any change; whether some elements are added to the collection, some of them are deleted, change locations, and so on. In this chapter, you will learn about these collections. Chapter 6, Concurrent Collections, covers concurrent collections that appeared in .NET 4.0. Multi-threaded applications are ubiquitous and that's the new expectation of our generation. We are always busy and impatient, trying to get a lot of things done at once. So concurrency is here and it is here to stay for a long time. Historically, there was no inbuilt support for concurrency in generic collections. Programmers had to ensure concurrency through primitive thread locking. You can still do so, but you now have an option to use the concurrent version of generic collections that support concurrency natively. This greatly simplifies the code. In this chapter, you will learn how to use them to build some useful applications such as simulating a survey engine. Chapter 7, Power Collections, introduces several generic algorithms in PowerCollections and some handy generic containers. This collection API came from Wintellect (www. wintellect.com) at the time when .NET Generics was not big and had some very useful collections. However, now .NET Generics has grown to support all those types and even more. So that makes most of the containers defined in PowerCollections outdated. However, there are a lot of good general purpose generic algorithms that you will need but which are missing from the .NET Generics API. That's the reason this chapter is included. In this chapter, you will see how these generic algorithms can be used with any generic container seamlessly. Chapter 8, C5 Collections, introduces the C5 API. If you come from a Java background and are wondering where your hash and tree-based data structures, are this is the chapter to turn to. However, from the usage perspective, all the containers available in C5 can be augmented with generic containers available in the .NET Framework. You are free to use them. This API is also home to several great generic algorithms that make life a lot easier. In this chapter, you will walk through the different collections and algorithms that C5 offers. Chapter 9, Patterns, Practices, and Performance, covers some best practices when dealing with Generics and introduces the benchmarking strategy. In this chapter, we will use benchmarking code to see how different generic containers perform and then declare a winner in that field. For example, benchmarking shows that if you need a set, then HashSet<T> in the .NET Framework is the fastest you can get. Appendix A, Performance Cheat Sheet, is a cheat sheet with all the performance measures for all containers. Keeping this handy would be extremely useful when you want to decide which container to use for the job at hand.
  • 28. Preface [ 3 ] Appendix B, Migration Cheat Sheet, will show you how to migrate code from STL/JCF/ PowerCollections/.NET 1.0 to the latest .NET Framework-compliant code. Migration will never be easier. Using this cheat sheet, it will be a no brainer. This is great for seasoned C++, Java, or .NET developers who are looking for a quick reference to .NET Generics in the latest framework. What you need for this book You will need the following software to use this book: ‹ ‹ Visual Studio 2010 (any version will do, I have used the Ultimate Trial version) ‹ ‹ LINQPad Instructions to download this software are given in the respective chapters where they are introduced. Who this book is for This book is for you, if you want to know what .NET Generics is all about and how it can help solve real-world problems. It is assumed that readers are familiar with C# program constructs such as variable declaration, looping, branching, and so on. No prior knowledge in .NET Generics or generic programming is required. This book also offers handy migration tips from other generic APIs available in other languages, such as STL in C++ or JCF in Java. So if you are trying to migrate your code to the .NET platform from any of these, then this book will be helpful. Last but not the least, this book ends with generic patterns, best practices, and performance analysis for several generic containers. So, if you are an architect or senior software engineer and have to define coding standards, this will be very handy as a showcase of proofs to your design decisions. Conventions In this book, you will find several headings appearing frequently. To give clear instructions of how to complete a procedure or task, we use:
  • 29. Preface [ 4 ] Time for action – heading 1. Action 1 2. Action 2 3. Action 3 Instructions often need some extra explanation so that they make sense, so they are followed with: What just happened? This heading explains the working of tasks or instructions that you have just completed. You will also find some other learning aids in the book, including: Pop quiz – heading These are short, multiple choice questions intended to help you test your own understanding. Have a go hero – heading These set practical challenges and give you ideas for experimenting with what you have learned. You will also find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning. Code words in text are shown as follows: "Suppose, I want to maintain a list of my students, then we can do that by using ArrayList to store a list of such Student objects." A block of code is set as follows: private T[] Sort<T>(T[] inputArray) { //Sort input array in-place //and return the sorted array return inputArray; }
  • 30. Preface [ 5 ] When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold: Enumerable.Range(1, 100).Reverse().ToList() .ForEach(n => nums.AddLast(n)); Any command-line input or output is written as follows: Argument 1: cannot convert from 'int[]' to 'float[]' New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "Then go to the File menu to create a console project." Warnings or important notes appear in a box like this. Tips and tricks appear like this. Reader feedback Feedback from our readers is always welcome. Let us know what you think about this book— what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of. To send us general feedback, simply send an e-mail to feedback@packtpub.com, and mention the book title through the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors. Customer support Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
  • 31. Preface [ 6 ] Downloading the example code You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you. Errata Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code— we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website, or added to any list of existing errata, under the Errata section of that title. Piracy Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at copyright@packtpub.com with a link to the suspected pirated material. We appreciate your help in protecting our authors, and our ability to bring you valuable content. Questions You can contact us at questions@packtpub.com if you are having a problem with any aspect of the book, and we will do our best to address it.
  • 32. 1 Why Generics? Thanks for picking up the book! This means you care for Generics. This is similar to dropping a plastic bag in favor of our lonely planet. We are living in an interesting era, where more and more applications are data driven. To store these different kinds of data, we need several data structures. Although the actual piece of data is different, that doesn't always necessarily mean that the type of data is different. For example, consider the following situations: Let's say, we have to write an application to pull in tweets and Facebook wall updates for given user IDs. Although these two result sets will have different features, they can be stored in a similar list of items. The list is a generic list that can be programmed to store items of a given type, at compile time, to ensure type safety. This is also known as parametric polymorphism. A cat and a dog shouldn't share a bed. Neither should integers and floats.
  • 33. Why Generics? [ 8 ] In this introductory chapter, I shall give you a few reasons why Generics is important. An analogy Here is an interesting analogy. Assume that there is a model hand pattern: If we fill the pattern with clay, we get a clay-modeled hand. If we fill it with bronze, we get a hand model replica made of bronze. Although the material in these two hand models are very different, they share the same pattern (or they were created using the same algorithm, if you would agree to that term, in a broader sense). Reason 1: Generics can save you a lot of typing Extrapolating the algorithm part, let's say we have to implement some sorting algorithm; however, data types can vary for the input. To solve this, you can use overloading, as follows: //Overloaded sort methods private int[] Sort(int[] inputArray) { //Sort input array in-place //and return the sorted array return inputArray; } private float[] Sort(float[] inputArray) { //Sort input array in-place //and return the sorted array return inputArray; }
  • 34. Chapter 1 [ 9 ] However, you have to write the same code for all numeric data types supported by .NET. That's bad. Wouldn't it be cool if the compiler could somehow be instructed at compile time to yield the right version for the given data type at runtime? That's what Generics is about. Instead of writing the same method for all data types, you can create one single method with a symbolic data type. This will instruct the compiler to yield a specific code for the specific data type at runtime, as follows: private T[] Sort<T>(T[] inputArray) { //Sort input array in-place //and return the sorted array return inputArray; } T is short for Type. If you replace T with anything, it will still compile; because it's the symbolic name for the generic type that will get replaced with a real type in the .NET type system at runtime. So once we have this method, we can call it as follows: int[] inputArray = { 1, 2, 0, 3 }; inputArray = Sort<int>(inputArray); However, if you hover your mouse pointer right after the first brace ((), you can see in the tooltip, the expected type is already int[], as shown in the following screenshot: That's the beauty of Generics. As we had mentioned int inside < and >, the compiler now knows for sure that it should expect only an int[] as the argument to the Sort<T> () method. However, if you change int to float, you will see that the expectation of the compiler also changes. It then expects a float[] as the argument, as shown:
  • 35. Why Generics? [ 10 ] Now if you think you can fool the compiler by passing an integer array while it is asking for a float, you are wrong. That's blocked by compiler-time type checking. If you try something similar to the following: You will get the following compiler error: Argument 1: cannot convert from 'int[]' to 'float[]' This means that Generics ensures strong type safety and is an integral part of the .NET framework, which is type safe. Reason 2: Generics can save you type safety woes, big time The previous example was about a sorting algorithm that doesn't change with data type. There are other things that become easier while dealing with Generics. There are broadly two types of operations that can be performed on a list of elements: 1. Location centric operations 2. Data centric operations Adding some elements at the front and deleting elements at an index are a couple of examples of location-centric operations on a list of data. In such operations, the user doesn't need to know about the data. It's just some memory manipulation at best. However, if the request is to delete every odd number from a list of integers, then that's a data-centric operation. To be able to successfully process this request, the method has to know how to determine whether an integer is odd or not. This might sound trivial for an integer; however, the point is the logic of determining whether an element is a candidate for deletion or not, is not readily known to the compiler. It has to be delegated. Before Generics appeared in .NET 2.0, people were using (and unfortunately these are still in heavy use) non-generic collections that are capable of storing a list of objects. As an object sits at the top of the hierarchy in the .NET object model, this opens floodgates. If such a list exists and is exposed, people can put in just about anything in that list and the compiler won't complain a bit, because to the compiler everything is fine as they are all objects.
  • 36. Chapter 1 [ 11 ] So, if a loosely typed collection such as ArrayList is used to store objects of type T, then for any data-centric operation, these must be down-casted to T again. Now, if somehow an entry that is not T, is put into the list, then this down-casting will result in an exception at runtime. Suppose, I want to maintain a list of my students, then we can do that by using ArrayList to store a list of such Student objects: class Student { public char Grade { get; set; } public int Roll { get; set; } public string Name { get; set; } } //List of students ArrayList studentList = new ArrayList(); Student newStudent = new Student(); newStudent.Name = "Dorothy"; newStudent.Roll = 1; newStudent.Grade = 'A'; studentList.Add(newStudent); newStudent = new Student(); newStudent.Name = "Sam"; newStudent.Roll = 2; newStudent.Grade ='B'; studentList.Add(newStudent); foreach (Object s in studentList) { //Type-casting. If s is anything other than a student
  • 37. Why Generics? [ 12 ] //or a derived class, this line will throw an exception. //This is a data centric operation. Student currentStudent = (Student)s; Console.WriteLine("Roll # " + currentStudent.Roll + " " + currentStudent.Name + " Scored a " + curr entStudent.Grade); } What's the problem with this approach? All this might look kind of okay, because we have been taking great care not to put anything else in the list other than Student objects. So, while we de-reference them after boxing, we don't see any problem. However, as the ArrayList can take any object as the argument, we could, by mistake, write something similar to the following: studentList.Add("Generics"); //Fooling the compiler As ArrayList is a loosely typed collection, it doesn't ensure compile-time type checking. So, this code won't generate any compile-time warning, and eventually it will throw the following exception at runtime when we try to de-reference this, to put in a Student object. Then, it will throw an InvalidCastException: What the exception in the preceding screenshot actually tells us is that Generics is a string and it can't cast that to Student, for the obvious reason that the compiler has no clue how to convert a string to a Student object. Unfortunately, this only gets noticed by the compiler during runtime. With Generics, we can catch this sort of error early on at compile time.
  • 38. Chapter 1 [ 13 ] Following is the generic code to maintain that list: //Creating a generic list of type "Student". //This is a strongly-typed-collection of type "Student". //So nothing, except Student or derived class objects from Student //can be put in this list myStudents List<Student> myStudents = new List<Student>(); //Adding a couple of students to the list Student newStudent = new Student(); newStudent.Name = "Dorothy"; newStudent.Roll = 1; newStudent.Grade = 'A'; myStudents.Add(newStudent); newStudent = new Student(); newStudent.Name = "Sam"; newStudent.Roll = 2; newStudent.Grade = 'B'; myStudents.Add(newStudent); //Looping through the list of students foreach (Student currentStudent in myStudents) { //There is no need to type cast. Because compiler //already knows that everything inside this list //is a Student. Console.WriteLine("Roll # " + currentStudent.Roll + " " + currentStudent.Name + " Scored a " + currentStudent.Grade); } The reasons mentioned earlier are the basic benefits of Generics. Also with Generics, language features such as LINQ and completely new languages such as F# came into existence. So, this is important. I hope you are convinced that Generics is a great programming tool and you are ready to learn it.
  • 39. Why Generics? [ 14 ] Reason 3: Generics leads to faster code In the .NET Framework, everything is an object so it's okay to throw in anything to the non- generic loosely typed collection such as ArrayList, as shown in the previous example. This means we have to box (up-cast to object for storing things in the Arraylist; this process is implicit) and unbox (down-cast the object to the desired object type). This leads to slower code. Here is the result of an experiment. I created two lists, one ArrayList and one List<int> to store integers: And following is the data that drove the preceding graph: ArrayList List<T> 1323 185 1303 169 1327 172 1340 169 1302 172 The previous table mentions the total time taken in milliseconds to add 10,000,000 elements to the list. Clearly, generic collection is about seven times faster.
  • 40. Chapter 1 [ 15 ] Reason 4: Generics is now ubiquitous in the .NET ecosystem Look around. If you care to develop any non-trivial application, you are better off using some of the APIs built for the specific job at hand. Most of the APIs available rely heavily on strong typing and they achieve this through Generics. We shall discuss some of these APIs (LINQ, PowerCollections, C5) that are being predominantly used by the .NET community in this book. So far, I have been giving you reasons to learn Generics. At this point, I am sure, you are ready to experiment with .NET Generics. Please check out the instructions in the next section to install the necessary software if you don't have it already. Setting up the environment If you are already running any 2010 version of Visual Studio that lets you create C# windows and console projects, you don't have to do anything and you can skip this section. You can download and install the Visual Studio Trial from http://www.microsoft.com/ download/en/details.aspx?displaylang=en&id=12752. Once you are done, you should see the following in your program menu: After this, start the program highlighted in the preceding screenshot Microsoft Visual Studio 2010.
  • 41. Why Generics? [ 16 ] Then go to the File menu to create a console project: Now, once that is created, make sure the following namespaces are available: If these are available, you have done the right setup. Congratulations!
  • 42. Chapter 1 [ 17 ] Summary My objective for this chapter was to make sure you get why Generics is important. Following are the points again in bullets: ‹ ‹ It ensures compile-time type checking, so type safety is ensured. ‹ ‹ It can yield the right code for the data type thrown at it at runtime, thus saving us a lot of typing. ‹ ‹ It is very fast (about seven times) compared to its non-generic cousins for value types. ‹ ‹ It is everywhere in the .NET ecosystem. API/framework developers trust the element of least surprise and they know people are familiar with Generics and their syntax. So they try to make sure their APIs also seem familiar to the users. In the end, we did an initial setup of the environment; so we are ready to build and run applications using .NET Generics. From the next chapter, we shall learn about .NET Generic containers and classes. In the next chapter, we shall discuss the Generic container List<T> that will let you store any type of data in a type safe way. Now that you know that's important, let's go there.
  • 44. 2 Lists Lists are everywhere, starting from the laundry list and grocery list to the checklist on your smartphone's task manager. There are two types of lists. Simple lists, which just store some items disregarding the order allowing duplicates; and other types which don't allow duplicates. These second types of lists which don't allow duplicates are called sets in mathematics. The other broad category of list is associative list, where each element in some list gets mapped to another element in another list. In this chapter, we shall learn about these generic containers and related methods. We shall learn when to use which list-based container depending on the situation. Reading this chapter and following the exercises you will learn the following: ‹ ‹ Why bother learning about generic lists? ‹ ‹ Types of generic lists and how to use them Don't forget the milk, honey!
  • 45. Lists [ 20 ] ‹ ‹ Give proper rationale for choosing a generic list such as one container over the other ‹ ‹ How to create custom generic list-based containers So let's get on with it... Why bother learning about generic lists? Let us see why generic lists are important: ‹ ‹ It ensures compile-time type checking. So type-unsafe code becomes a thing of the past. ‹ ‹ It saves us a lot of typing, because compiler can generate type-safe code for generic types at runtime. So the same code works for different data types. ‹ ‹ It is faster in many cases than its non-generic cousins, because it removes the need to box and unbox (also known as type-casting) from the code. ‹ ‹ It makes source code much cleaner than its older, non-generic, unsafe cousins. In this chapter, you shall find examples of how generic list-based containers make these possible. Happy listing! Types of generic lists There are mainly three types of lists you can imagine or would ever need: 1. Simple list: It allows duplicates by default. 2. Sets: It doesn't allow duplicates by default. 3. Associative list: It helps to represent a relationship between two types of entities. A simple list is just a collection of items. Say a laundry list, a grocery list, a task list, a list of courses. The elements in a simple container don't associate them with any other element. There are several generic container classes to represent simple lists. They are Stack<T>, Queue<T>, List<T>, LinkedList<T>, and SortedSet<T>. These are generic implementations of classic data structures. So Stack<T> is a Last In First Out (LIFO) list, Queue<T> is a First In First Out (FIFO) list, List<T> is a simple unordered list, and so is LinkedList<T>. But List<T> supports random integer indexing natively, while the others don't. Sets are simple lists that don't allow duplicates. All sets implement the interface ISet<T>. There are two set implementations HashSet<T> and SortedSet<T>. HashSet<T> doesn't maintain the order of elements, while SortedSet<T> keeps the elements sorted, if it knows how to sort the type. For custom types, you can pass a custom IComparer<T> instance to delegate the task of comparing. For HashSet<T>, you can pass IEqualityComparer<T> for custom equality comparison.
  • 46. Chapter 2 [ 21 ] An associative list, as the name suggests, brings in an association between two different entities and represents them in a single list for example, marks obtained by a student in a different semester of a course, share values for a company over the years, and so on. To represent these type of lists, there is an interface IDictionary<TKey,TValue> and SortedList<TKey,TValue> is a derived class that implements this interface. So we can use SortedList<TKey,TValue> to represent any associative list in .NET Generics. SortedList<TKey,TValue> is also a list. This is implemented using an array. So unlike other IDictionary<TKey,TValue> implementations, SortedList<TKey,TValue> supports indexing over keys and values. So the order of insertion in a SortedList determines the order of elements; unlike other IDictionary<TKey,TValue> implementations, as we shall see in the next chapter. If you were wondering what the heck are TKey and TValue, they are short and quite traditional ways of representing the type of key and type of value respectively. As generic lists can support any type, they are represented in this way. So at runtime the compiler generates appropriate code for the specified data type. This greatly helps to reduce code duplication and type mismatch issues. In a nutshell: Stack<T> This is a generic Stack implementation. This is first in last out. Queue<T> This is a generic Queue implementation. This is a first in first out list. List<T> This is a generic implementation of a simple list. This offers native random zero based integer indexing like an array. LinkedList<T> This is a generic implementation of a classic double-linked list. No native random indexing is offered. HashSet<T> This is a generic Set implementation. The elements are not sorted. For custom equality comparison, you can pass the IEqualityComparer<T> instance. SortedSet<T> This is a generic Set implementation. The value type elements remain sorted, by default. For reference types, we have to pass custom-comparer objects for custom element sorting; you can use the IComparer<T> instance. SortedList<T> Sometimes you want an associative container, but you still want to be able to access each key-value pair, like you do in a plain old array using the index. Then all you need is a SortedList<T>.
  • 47. Lists [ 22 ] Now that we have some basic idea about these generic list based containers, we shall see how these can be used to solve some real-world problems. Let's get started with a fun app! A generic collection can contain objects of value and reference types. This means you can create nested types. For example, if you want a list of stacks, you can get that by declaring List<Stack<T>>. If you want a SortedList of integer keys and associate a list of string values with each such integer key, you can write SortedList<int,List<string>>. Checking whether a sequence is a palindrome or not All the following sequences share a common attribute. They all read the same both ways, save for the punctuations "Madam I'm Adam" "A Man, A Plan, A Canal, Panama!!" 12321 Detroit-Chicago-Detroit (This reads same word by word backwards, unlike others that read the same character by character.) A Toyota These types of sequences are called palindromes. A sequence is palindromic too, if the contents read the same both ways, for example, A-B-A. In this example, we shall see how a generic stack (that is, a Stack<T> instance) can be used to implement this, so that we can detect whether a given sequence is a palindrome or not for any given type that knows how to compare itself (that is, implements the IComparable interface). So the task at hand is to build a generic palindrome checker that can check whether any sequence is a palindrome or not. All we have to do is let it know the type of the sequence at runtime. The algorithm to find whether a sequence is a palindrome or not is really simple. If we arrange the tasks to be done in order to check whether the given sequence is a palindrome or not, it will be like:
  • 48. Chapter 2 [ 23 ] Pick items from Input Put them in reverse order Retrieve elements from Input and Reversed Sequence Compare these two Equals Sequence Ends ? The sequence is not palindrome The sequence is palindrome No No Yes Yes The sequence can be of any type; char, string, integer, float, and so on to name a few. Also, note that the algorithm is not different for all these different types. However, we shall have to write several methods for supporting several data types. However, if we use Generics we can avoid this code duplication for each type. We can write a single method (also known as Generic Method) that can write the data type-specific code at runtime depending on what type of data type we want. The tradition is to use the letter T (which is short for Type) to create the generic method. When we consume this method, we pass concrete Types that conform to the standard expectations from the Type; like in this case, we expect the Type to implement IComparable. The heart of the solution is to reverse the elements of the input sequence. This can be done by a stack. Since we want to make the method generic, we need a generic stack.
  • 49. Lists [ 24 ] Time for action – creating the generic stack as the buffer Follow the given steps: 1. Create a console application project. Call it Palindrome Checker. 2. Create a method called IsPalindromic() with the following signature: public static bool IsPalindromic<T>(IEnumerable<T> inputSequence) where T:IComparable { Stack<T> buffer = new Stack<T>(); return true; } 3. Add the following code in the Main() method: static void Main(string[] args) { bool status = IsPalindromic<char>(new int[] { 1, 2, 2, 1 }); } 4. Try to compile the program. What just happened? You will see a compiler error as shown in the following screenshot: Let's see why that compile-time error occurred. Before that, let's learn a little more about generic stacks. Creating a generic stack is very easy. Here is how: Stack<T> myGenericStack = new Stack<T>(); So if you want a generic stack to be used to store a stack of string, then you change T with string as follows: Stack<string> myCDs = new Stack<string>();
  • 50. Chapter 2 [ 25 ] If you want a stack of integers, you just say: Stack<int> opCodes = new Stack<int>(); If you are dealing with reference types, then you can declare a stack of base types and put derived types in that. Say if D is a class that implements an ID interface, then if you create a stack of ID objects, you can put ID objects in the Stack as follows: Stack<ID> somethings = new Stack<ID>(); Somethings.Push(new ID()); However, the method needs to know how to compare the elements in the buffer. So now the obvious question you might have is, if we write the code using a generic place holder (T in this case) which gets replaced by the original data type at runtime, how will the method know at compile time how to compare variables of such data type? Well, that's a very good question and the answer lies in the very first line of the method. Let's take a close look at it: public static bool IsPalindromic<T>(IEnumerable<T> inputSequence) where T:IComparable The keyword where is used to constrain the types that can be used as a valid argument in the generic method IsPalindromic<T>(), we just created. where T:IComparable means T has to be a type that implements the IComparable interface. This syntax is known as Constraints in Generics. Now, let's get back to the compilation error part. Generics ensure compile-time type checking as follows: bool status = IsPalindromic<char>(new int[] { 1, 2, 2, 1 }); In this code, IsPalindromic<char> promises that everything that follows in the argument to this method will be of type character. However, we have an integer array as the input sequence. This is causing a type mismatch and thus is caught at compile time. We are passing an array as the parameter, where the method expects something of type IEnumerable<T>. This is possible because IEnumerable<T> inherits from IEnumerable and good old arrays implement IEnumerable too. Thus, IEnumerable serves as a bridge between pre-generic collections and generic collections.
  • 51. Lists [ 26 ] Time for action – completing the rest of the method Follow the given steps: 1. Add the following code after the initialization of the buffer in the source, as carried out previously in step 2: foreach (T element in inputSequence) { buffer.Push(element); } Count() and ElementAt() are extension methods and are available at System. Linq namespace in .NET Framework 3.5 and above. You can get it with Visual Studio 2008 and above. So please include that namespace: for (int i = 0; i < inputSequence.Count(); i++) { if(buffer.Pop().CompareTo(inputSequence.ElementAt(i))==0) continue; else return false; } Make sure you retain the last return true; statement. 2. Replace the content of the Main() method with the following: static void Main(string[] args) { //Checking if a string (Which is basically a sequence of //characters) bool status1 = IsPalindromic<char>("LIRIL"); //Checking if an array of string is palindromic bool status2 = IsPalindromic<string>(new string[] {"mango","apple","mango"}); //Checking if an array of int is palindromic bool status3 = IsPalindromic<int>(new int[] { 1,2,3,4,5,6,0,6,5,4,3,2,1 }); //Checking if an array of float is palindromic bool status4 = IsPalindromic<float>(new float[] { 1.34F,2.34F,43.1F}); Console.WriteLine(status1 + " " + status2 + " " + status3 + " " + status4); } 3. Run the program.
  • 52. Chapter 2 [ 27 ] What just happened? The program shall print the following to the console: The following looping construct: foreach (T element in inputSequence) { buffer.Push(element); } pushes all the elements in the input sequence to a stack. The stack is a last in first out list. It keeps the elements in reverse order. So if you want to add an element to the top of the stack, you should use the push method. So when the method is called by bool status1 = IsPalindromic<char>("GENERI CS"); it stores the characters of the input sequence in the internal generic stack buffer as follows: G E N E R I C S Input Sequence G E N E R I C Stack buffer push() buffer.Pop() returns the top-most element from the stack and removes that from the stack. The ElementAt() method returns the ith element from the input sequence. As long as these two are equal, the sequence might be a palindrome. So, we must continue going through the input sequence. However, if they mismatch at any point, it becomes evident immediately that the input sequence is not a palindrome. Thus, we can return False. However, if we can get to the end of the input sequence without encountering a mismatch, the input sequence is a palindrome and thus we have to return True.
  • 53. Lists [ 28 ] Let's now try to decode the output. Among four input sequences in the Main() method, the first three are palindromes. However, the last one doesn't read the same both ways and surely isn't a palindrome. Output matches that. We get True for the first three input sequences and False for the last one. Any type that implements IComparable would work. Other types will fail. Designing a generic anagram finder Generics are not limited to lists and you can even mix parameterized types with specialized types as well. For instance, what if you want to store the frequency of occurrence of a string, number, or a symbol. While the type of what you keep the frequency of is unknown or undecided, however you see that the frequency itself is always a number. Let's take a look at how we can implement that using anagrams as an example. Anagrams are as fascinating as palindromes. Two sequences are said to be anagrams of each another, when they share the same number of elements in the same frequency. For example, two strings "The eyes" and "They see" both have the same number of characters, and the frequency of each character in these two strings is the same. Both of them have a single "T", a couple of "e"s, and so on. Thus, they are anagrams of each other. http://www.anagrammy.com/ organizes a competition for the best anagrams each month. Assume your friend wants to participate and is now seeking your help to develop a program that can find anagrams of a given word. Let's get into action and help your buddy. A strategy to check whether two sequences are anagrams of each other or not is really simple. We need a container that would let us store each unique element of the sequence and their frequency of appearance in the sequence. For example, the string "The eyes" will be stored in such a container as follows: Element Frequency T H E Y S 1 1 3 1 1
  • 54. Chapter 2 [ 29 ] If another string stored in the same way shares the same frequency of characters, then that will be an anagram of "The eyes". So, if we deduct 1 from the frequency as soon as we get the same character in the second string; we shall have all zeros in the frequency column of the preceding table at the end of scanning the second string; in this case, we are dealing with two anagrams. This algorithm is applicable to any type of anagram sequence, not only for strings. So, we can write a generic method to check whether two sequences are anagrams of each other or not, for any type. Time for action – creating the method Follow the given steps: 1. Create a console application called Ganagram (short form for generic anagram). This is a showcase of SortedList<TKey,TValue>, solving a real problem. 2. Add the following method in the Program.cs file: public static bool IsAnagram<T>(IEnumerable<T> first, IEnumerable<T> second) { SortedList<T, int> val = new SortedList<<T, int>(); foreach (T element in first) { if (!val.ContainsKey(element)) val.Add(element, 1); else val[element]++; } foreach (T element in second) { if (val.ContainsKey(element)) val[element]--; else return false; } foreach (T element in val.Keys) { if (val[element] != 0) return false;
  • 55. Other documents randomly have different content
  • 56. captain. Nothing in his narrative enables us to identify this Cocke with the Abraham Cocke of Limehouse, who was “never heard of more” after he parted from Battell on the coast of Brazil in 1590, nor with the Abram Cocke who, according to Knivet, put in at the Ilha Grande in 1598, in the hope of making prizes of some of the richly- laden Spanish vessels returning from the Rio de la Plata. Battell, surely, may be supposed to have been acquainted with the fate of his old shipmate, whilst Knivet gives no hint that the Abram Cocke of the Ilha Grande was the captain of the Roebuck, to whom he was indebted for his life when Cavendish was about to throw him overboard in Magellan’s Strait. It is, however, just possible that there was but one Abraham Cock, who had not been heard of for some time when Battell returned to England about 1610.263 When Cavendish returned from Magellan’s Strait, he put Knivet and nineteen other sick men ashore near St. Sebastian, to shift for themselves. Knivet was ultimately taken by the Portuguese; but they spared his life, and he became the “bond-slave” of Salvador Corrêa de Sá, the Governor of Rio de Janeiro; and apart from the time he spent among the cannibal Indians, and on a voyage to Angola, he remained with his master to the end, and returned with him to Portugal in 1599. My friend, Colonel G. Earl Church, to whom I applied for an opinion on the trustworthiness of Knivet’s statements with regard to Brazil, writes as follows:— “Yesterday morning I spent at the R. Geo. Soc., refreshing my memory of Knivet’s extraordinary adventures. One must read them always bearing in mind the romantic spirit of the age in which they were written, and the novel surroundings in which every adventurer found himself in the New World. Giving due weight to all this, I find Knivet’s relation of his voyages singularly truthful, so far as my knowledge of Brazil goes. What he states, excepting in two or three minor particulars, clashes with no geographical, descriptive, or historical point with which I am familiar, and he often throws in a
  • 57. sentence which relates to facts which no man could invent, and which makes his narrative impressive with truthfulness. I utterly discard Cavendish’s opinion of his men and companions for Cavendish appears to have been one of the most cold-blooded freebooters who ever cut a throat or raided a settlement or scuttled a prize.” I regret not being able to write in terms equally favourable of what Knivet claims to have experienced during his visit to Angola and Kongo. Knivet says that he ran away from bondage on June 27th, 1597, and that he reached the “port of Angola” after a perilous voyage of five months, that is in November. He then sailed up the Kwanza, and reached Masanganu, where he remained three months, when he was arrested in consequence of a requisition of his master and sent back to Brazil, which he must have reached before June, 1598. We should be quite prepared to accept this part of his story if his description of Masanganu did not show that he can never have been there. Knivet, however, is not content with such modest honours, but claims to have resided for some time at the court of the King of Kongo, and to have fallen in the hands of the Portuguese when on his road to Prester John’s country. By them he was carried to Masanganu, where he lived three months. These two accounts are absolutely irreconcilable. As to the author’s astounding geographical misstatements, I refer the reader to the notes appended to his narrative. First Account (Purchas, pp. 1220-2). Continually I desired my master to give me leave to get my living, intending to come into my country, but the Governor would not let me go from him. When I saw no means to get leave of my master, I determined to run away to Angola, for to serve the King as a soldier in Massangano till such time that I might pass myself to the King of Anyeca,264 which warreth against the Portugals, and so have come through Prester Johns country into Turkey.
  • 58. On the seven and twentieth day of June, 1597, I embarked myself unknown to my master, in a small ship of one Emanuell Andrea, for to come for Angola. In this voyage we were driven so near the Cape of Good Hope that we thought all of us should have been cast away, the seas are there so great; and by reason of the current they brake in such sort that no ship is able to endure. There we brake both our main mast and our mizzen. It pleased God to send us the wind Eastward, which brought us to our desired harbour [of] Angola.265 We had been five months in our voyage, and by that means other ships that departed two months after us were there before us. When I heard that there were ships of the River of Ienero [Rio de Janeiro], I durst not go ashore for fear of being known of some of the Portugals. The next day after that we came into the harbour, there came a great boat aboard us, to ask if we would sell any Cassava meal. We told them we would, and asked them whither they went with their boat. They answered, that they tarried for the tide to go up to the River of Guansa [Kwanza] to Masangano. Then I thought it a fit time for my purpose, and so embarked myself in the bark. The Portugals marvelled to see me go willingly to Masangano; for there men die like chickens, and no man will go thither if he can chose. Nine days we were going up the River of Guansa [Kwanza], in which time two Portugal soldiers died; the country is so hot that it pierceth their hearts. Three days after I had been in Masangano, Don Francisco de Mendosa Fortado,266 the Governor of the city of Kongo, having received a letter from Salvador Coria de Sasa [Salvador Corrêa de Sá], who was his great friend, sent a Pursuivant for me, who brought me by land through the King of Kongo’s country, and in six days we came to a town called Saint Francis267 (where the Governor was), hard by the kingdom of Manicongo. When I came before the Governor he used me very kindly in words, and asked me what I meant, to cast myself away wilfully in Masangano. Then I told him how long I had served Salvador Coria
  • 59. de Sasa; and in how many dangers I had been for him and his Son, without ever having any recompence of any of them, and therefore I thought it better to venture my life in the King’s service, than to live his Bond-slave. The Governor commanded me to be carried to Angola, and charged a pair of bolts to be put upon my legs, because I should not run away. About a fortnight after I was sent back again in a Carvell [caravel] of Francis Lewes, and in two months we arrived in the River of Jenero [Rio de Janeiro], and I was carried with my bolts on my legs before the Governor; when he saw me he began to laugh and to jest with me, saying that I was welcome out of England. So, after many jests he spake, he bade pull off my bolts from my legs, and gave me clothes and used me very well. Second Account (Purchas, pp. 1233-7). Angola is a kingdom of itself in Ethiopia, where first the Portugals did begin to inhabit: The country of Angola cometh along the coast; as Portugal doth upon Spain, so doth Angola run upon the Kingdom of Longa [Luangu] and Manicongo. In Angola the Portugals have a City called the Holy Ghost,268 where they have great store of Merchandise, and the Moors do come thither with all kind of such things as the country yieldeth; some bring elephant’s teeth, some bring negro slaves to sell, that they take from other kingdoms which join hard by them; thus do they use once a week, as we keep markets, so do all the Blackamoors bring hens and hogs, which they call gula,269 and hens they call Sange,270 and a kind of beast that they take in the wilderness, like a dog, which they call ambroa:271 then they have that beast which before I have told you of, called gumbe, which is bigger than a horse.272 The Blackamoors do keep good laws, and fear their King very much; the King is always attended with the nobles of his realm, and whensoever he goeth abroad, he has always at the least two
  • 60. hundred archers in his guard, and ten or twelve more going before him, singing and playing with pipes made of great canes, and four or five young Moors coming after him as his pages. After them follow all his noblemen. When there falleth out any controversy among them, they crave battle of the King, and then they fight it out before him. They come before the King and fall flat on their breasts; then they rise up and kneel upon their knees, stretching out their arms crying, Mahobeque benge, benge;273 then the King striketh them on the shoulders with a horse-tail; then they go to the camp, and with their bows they fight it out till they kill one another. After the battle is done, if any liveth, he that liveth falleth down before the King in the same manner as he did when he went to the field; and after a long oration made, he taketh the horse-tail from the King’s shoulder, and waveth it about the King’s head, and then layeth it on his shoulder again, and goeth away with great honour, being accompanied with all the nobles of the Court. The Moors of Angola do know that there is a God, and do call God Caripongoa,274 but they worship the sun and the moon. The country is champaign plain, and dry black earth, and yieldeth very little corn; the most of anything that it yieldeth is plantons [plantains], which the Portugals call baynonas [bananas], and the Moors call them mahonge275 and their wheat they call tumba,276 and the bread anou; and if you will buy any bread of them, you must say, Tala cuna auen tumbola gimbo; that is, Give me some bread, here is money.277 Their money is called gullginbo,278 a shell of a fish that they find by the shore-side; and from Brazil the Portugals do carry great store of them to Angola. These Moors do esteem very much of red, blue and yellow cloths. They will give a slave for a span of cloth in breadth, I mean, and the length of it, of the breadth of the piece; those pieces of cloth they wear about their middles, and under it they hang the skin of a great weasel before them, and another behind them, and this is all the
  • 61. garments that they wear. A weasel in their language is called puccu.279 You can do a Blackamoor no greater disgrace than to take away his skin from before him, for he will die with grief if he cannot be revenged. The Portugals do mark them as we do sheep, with a hot iron, which the Moors call crimbo.280 The poor slaves stand all in a row one by another, and sing Mundele que sumbela he Carey ha belelelle,281 and thus the poor rogues are beguiled, for the Portugals make them believe that they that have not the mark is not accounted a man of any account in Brazil or in Portugal, and thus they bring the poor Moors to be in a most damnable bondage under the cover of love. The country of Angola yieldeth no stone, and very little wood: the Moors do make their houses all covered with earth. These houses are no bigger than a reasonable chamber, and within are many partitions, like the cabins of a ship, in such sort that a man cannot stand upright in them. Their beds are made of great bulrushes sewed together with the rinds of a tree. They do make cloth like spark of velvet (but it is thinner) of the bark of a tree, and that cloth they do call mollelleo.282 The elephants do feed in the evening and in the morning in low marshes, as there be many. The Moors do watch which way they come, and as soon as the elephants are at meat, they dig great holes in the ground, and cover them with sticks, and then they cover the pits with earth; and when they have made all ready they go to the elephants and shoot at them with their arrows; and as soon as the elephants feel themselves hurt, they run at whatsoever they see before them, following after the Blackamores that chase them. Then they fall into the deep pits where, after they are once in, they cannot get out. The Moors of Angola are as black as jet; they are men of good stature; they never take but one wife, whom they call mocasha.283 These Moors do cut long streaks in their faces, that reach from the
  • 62. top of their ears to their chins. The women do wear shells of fishes284 on their arms, and on the small of their legs. The law amongst them is, that if any Moor do lie with another’s wife, he shall lose his ears for his offence. These Moors do circumcise their children, and give them their names, as we do when we baptize. Angola may very easily be taken, for the Portugals have no forts to defend it of any strength. The King285 of Congo is the greatest King in all Ethiopia; and doth keep in the field continually sixty thousand soldiers, that do war against the King of Vangala,286 and the King of Angola; this King is a Christian, and his brother-in-law of arms with the King of Spain. His servants of his house are most of them all Portugals, and he doth favour them very much. The King is of a very liberal condition, and very favourable to all travellers, and doth delight very much to hear of foreign countries. He was in a manner amazed to hear how it was possible Her Majesty [Queen Elizabeth] had lived a maiden Queen so long, and always reigned in peace with her subjects. When I was brought before the King, and told him of my country, what plenty of things we had, if the Portugals had not liked of it, they would interrupt my speech, and the King would show himself very angry, and tell them that every man was best able to speak of his country, and that I had no reason but to tell him that which was true. The King of Congo, when he goeth to the camp to see his army, rideth upon an elephant in great pomp and majesty; on either side of the elephant he hath six slaves. Two of them were kings, that he himself had taken in the field; all the rest were of noble birth; some of them were brothers to the King of Ancica, and some of them were of the chiefest blood of the great King of Bengala. These noble slaves, at every command of the King of Congo, do fall flat on the ground on their breasts. When the King doth ride, as you have heard, they carry a canopy, as it were a cloth of state, over his head. His two secretaries, the one a nobleman of Spain, the other a Moor,
  • 63. do ride next after him. Before him goeth at the least five hundred archers which are his guard; then there followeth a Moor, which doth nothing but talk aloud in praise of the King, telling what a great warrior he hath been, and praising his wisdom for all things that he hath accomplished very honourably to his great fame of such as knew him. When this King of Congo cometh to his host, all the soldiers, as he passeth, fall flat on their faces to the ground. He never cometh into his host after any battle, but he dubbeth at the least twenty Knights Portugals, and as many Moors, giving them very great living according to their callings, and the service that they have done. The brother of this King was in Spain at my coming from thence for ambassador from his brother.287 Here the Portugal Captain would have taken me perforce, to have been a common soldier, but the King commanded that they should let me go whither I would, and my determination at that time was to have gone for the country of Prester John [Abyssinia], for I had a great desire to see the River of Nilo and Jerusalem (for I accounted myself as a lost man, not caring into what country or kingdom I came) But it was not the will of God that I should at that time obtain my desire, for travelling through the kingdom of Congo, to have gone to the kingdom of Angila,288 it was my fortune to meet a company of Portugal soldiers that went to a conquest that the King of Spain had newly taken, called Masangana; which place is on the borders of Anguca. Here they made me serve like a drudge, for both day and night I carried some stone and lime to make a fort. It lyeth right under the Line, and standeth in a bottom in the middle of four hills, and about are many fogges [bogs] but not one river.289 It is the unfirmest country under the sun. Here the Portugals die like chickens. You shall see men in the morning very lusty, and within two hours dead. Others, that if they but wet their legs, presently they swell bigger than their middles;290 others break in the sides with a draught of water. O, if you did know the intolerable heat of
  • 64. the country, you would think yourself better a thousand times dead, than to live there a week. There you shall see poor soldiers lie in troops, gaping like camelians [camels?] for a puff of wind. Here lived I three months, not as the Portugals did, taking of physick, and every week letting of blood and keeping close in their houses when they had any rain, observing hours, and times to go abroad morning and evening, and never to eat but at such and such times. I was glad when I had got anything at morning, noon, or night; I thank God I did work all day from morning till night; had it been rain or never so great heat, I had always my health as well as I have in England. This country is very rich. The king had great store of gold291 sent him from this place: the time that I was there, the King of Angica had a great city at Masangana; which city Paulas Dias, Governor of Angola, took and situated there; and finding hard by it great store of gold, fortified it with four forts, and walled a great circuit of ground round about it, and within that wall; now the Portugals do build a city, and from this city every day they do war against the King of Angica, and have burnt a great part of his kingdom. The Angicas292 are men of goodly stature; they file their teeth before on their upper jaw, and on their under jaw, making a distance between them like the teeth of a dog; they do eat man’s flesh; they are the stubbornest nation that lives under the sun, and the resolutest in the field that ever man saw; for they will rather kill themselves than yield to the Portugals. They inhabit right under the line, and of all kinds of Moors these are the blackest. They do live in the law of the Turks, and honour Mahomet. They keep many concubines, as the Turks do; they wash themselves every morning upwards, falling flat on their faces towards the east. They wear their hair all made in plaits on their heads, as well men as women; they have good store of wheat, and a kind of grain like vetches, of which they make bread: they have great store of hens like partridges, and
  • 65. turkeys, and all their feathers curl on their backs. Their houses are like the other houses of the kingdoms aforenamed. And thus I end, showing you as brief as I can, all the nations and kingdoms, that, with great danger of my life, I travelled through in twelve years of my best age, getting no more than my travel for my pain. From this kingdom, Angica, was I brought in irons again to my master, Salvador Corea de Sasa, to the City of San Sebastian in Brazil, as you have heard. APPENDIX II. A SKETCH OF THE HISTORY OF KONGO TO THE end of the seventeenth century. The Early History of Kongo. F traditions may be accepted where written history fails us, the foundation of the Empire of Kongo lies back no further than the middle of the fifteenth century.
  • 66. The founder of the dynasty and first King of Kongo— Ntotela ntinu nekongo—was Nimi a Lukeni, the son of Nimi a nzima and of Lukeni lua nsanzi, the daughter of Nsa ku ki-lau. His father appears to have been a mere village chief in Kurimba (Corimba),293 a district of the kingdom of Kwangu. He had established himself at a ferry on a great river (nzari), now known to us as the Kwangu, and levied a toll upon all travellers who crossed the stream. One day the young man’s aunt came that way, and claimed exemption on the ground of being the old chief’s sister. Her brother was absent, and not only was the claim denied, but young Nimi a Lukeni, notwithstanding that she was with child, caused her to be disembowelled. The younger members of his clan looked upon this act of brutality as one of bravery, and shielded him against his father’s just wrath. He then placed himself at their head, assumed the title of ntinu (king), and started westward upon a career of conquest. The country he was about to invade was inhabited by a people kindred to those of Angola and of the country to the north of the Zaire, split up into numerous small clans294 ruled by independent kinglets. This, no doubt, would account for the rapidity and the extent of his conquests, which have been matched however, in our own days, by the Makololo. Having defeated Mbumbulu mwana Mpangala of Mpemba-kasi, he founded his capital—Mbazi a nkanu—295 upon a rock within that chief’s territory. By degrees he extended his conquests southward to the Kwanza and even beyond, installed his uncle Nsa ku ki-lau as ruler of the important province of Mbata, bestowed large territories upon others of his adherents, and even restored some of their father’s territories to the children of the Mwana Mpangala. His “sons,” attended by the great Nganga Ngoyo, he sent across the Zaire, and they became the founders of the “kingdoms” of Kakongo and Luangu; whilst a third son, by a slave woman, is supposed to be the ancestor of the “counts” of Sonyo or Soyo.296 Anciently the King of Kakongo, before he assumed his kingship, was bound to marry a
  • 67. princess of the blood royal of Kongo, whilst he of Luangu married a princess of Kakongo; yet the ruler of Luangu was highest in rank, for he enjoyed the title of nunu (“aged person”), whilst his brother of Kakongo had to be contented with the inferior title of nkaji (“spouse”). The Kings were elected by the feudal princes, but their choice was limited to the sons of princesses, as in a great part of negro Africa.297 Of the early institutions of Kongo we know next to nothing, though we may presume that the law of succession was originally the same there as in the sister-states to the north, for the first Ntotela was succeeded by two nephews (Nanga kia ntinu and another, whose name has not reached us). But even thus early, and anterior to the introduction of Christianity, the old law of succession was broken through, for Nkuwu a ntinu, the fourth Ntotela, was a son of Ntinu Nimi a Lukeni, and was succeeded by a son of his own, Nzinga a Nkuwa, the first Christian Ntotela, better known in history as John I. If Dapper may be believed, it was the custom to bury twelve virgins with the earlier kings—a distinction much sought after, as in other parts of Africa; but the people of Kongo have never been charged with cannibalism, nor its rulers with the bloody rites practised by the Jaga. Cão’s Discovery of the Kongo, 1482.298 It was towards the end of 1482, that the natives at the mouth of the River Kongo for the first time saw rising above the horizon the white wings of a European vessel, ascending, as it were, from the Land of Spirits; and we can imagine their surprise when they for the first time beheld the bleached faces of its inmates. Yet they came on board, offering ivory in exchange for cloth. The interpreters from the Guinea coast who were with Cão naturally failed to make themselves understood, but they learnt from signs that far inland there dwelt a powerful king. Cão at once despatched some Christian negroes in search of this potentate. They were the bearers of suitable presents,
  • 68. and were instructed to assure the King of the friendly intentions of his visitors, whose only desire it was to trade with him. Before continuing his voyage, Cão set up the first of the stone pillars, or padroes, which he had on board. He then sailed south along the coast, noting its prominent features, but curiously missed the Kwanza or River of Angola, although its clayey waters discolour the sea for ten or fifteen miles. On a low foreland, Cabo do Lobo,299 ten miles beyond the cliffs named by him Castello d’Alter Pedroso, he set up a second pillar, to mark the furthest point reached by him. On again returning to the Kongo, he was annoyed to find that his messengers had not returned; and as he was naturally anxious to make known in Portugal his discovery of a magnificent river and a powerful kingdom, he left them behind him, and seized instead four unsuspecting visitors to his ship as “hostages;” giving their friends to understand that they should be restored to them after the lapse of fifteen months, when they would be exchanged for his own men. These latter appear to have been treated with distinction at first, but when the King heard of Cão’s high-handed proceedings he refused to admit them any longer to his presence, and even threatened them with death, should his own people not be restored. Among the hostages carried off by Cão there was a man of some distinction in his own country, Nsaku (Caçuto) by name, who picked up Portuguese quickly, and much pleased King John by the information he was able to give. He, as well as his companions, were much petted in Portugal, and, in defiance of all sumptuary laws, were dressed in fine cloths and silks. Cão himself, soon after his arrival, in April, 1484, was appointed a cavalier in the Royal household, granted an annuity of 18,000 reals, and on the 14th of that month he was “separated from the common herd,” and granted a coat-of-arms charged with the two pillars erected by him during this memorable voyage. Cão’s Second Voyage, 1485-6.
  • 69. Cão’s departure on a second voyage was much delayed, either because the King’s Council were opposed to these adventures, which strained the resources of a small kingdom like Portugal, or—and this is more likely—because it was desired that a change in the Royal Arms, which was only made in June, 1485, should be recorded on the stone pillars which Cão was to take with him. Great was the rejoicing when Cão’s “fleet” appeared in the Kongo, and the hostages, loud in praise of the good treatment they had received, were once more among their friends. Cão at once forwarded rich presents to the King, with an invitation to throw aside all fetishes, and to embrace the only true and saving faith; promising that, on his return from a voyage to the south, he would personally visit the capital of his kingdom. This promise Cão was not permitted to fulfil, for having set up a pillar on Monte Negro (15° 40´ S.) and another on Cape Cross (21° 50´),300 he died a short distance beyond. Of the details of his death we know nothing.301 It seems, however, that the loss of their commander induced a speedy return home: for Cão’s vessels must have arrived in Portugal before August, 1487, as in that month Dias sailed on his famous voyage, taking with him the negroes whom Cão had kidnapped to the south of the Kongo, with a view to their learning Portuguese, and being employed as interpreters in future voyages. Cão, therefore, never saw the King of Kongo; and there are good grounds for believing that Nsaku who was sent by the King to Portugal to ask for priests, masons, carpenters, agricultural labourers, and women to make bread, only reached Europe in one of Dias’s vessels, in December, 1488. Nsaku, most certainly, was first introduced to King John at Beja, in January, 1489, when he and his companions were baptised, the King himself, the Queen, and gentlemen of title acting as sponsors.(312) He was sent back to the Kongo with Don Gonçalo de Sousa, in December, 1490, about two years after he had been baptised.302 The Embassy of 1490-1.303
  • 70. Don João de Sousa, the ambassador, left Portugal on December 19th, 1490, with a fleet commanded by Gonçalo de Sousa, as captain-major. Among the pilots were Pero d’Alemquer and Pero Escovar, men famous in the maritime history of Portugal. Ten Franciscan Friars304 went out with this fleet, and so did Nsaku, the ambassador of the King of Kongo. The plague was raging at Lisbon at the time, and before the vessels reached the Cape Verde Islands, this dreaded disease had carried off João de Sousa (the ambassador), the captain-major, and many others. Ruy de Sousa, a nephew of the captain-major, was then chosen to take the place of D. João de Sousa. After a voyage of a hundred days the vessels reached the Kongo, and the Mwana of Sonyo and his son, who had already been instructed in the Christian doctrine by a priest from S. Thomé, were baptised on Easter Sunday, April 3rd, 1491, and were thenceforth known as Don Manuel and Don Antonio da Silva; for it was the practice of the Portuguese, from the very beginning, to bestow Portuguese names and titles upon the negroes who submitted to the sacrament of baptism. This ceremony performed, Ruy de Sousa started for the King’s capital,305 which he reached on April 29th. The King received him seated on a platform, in a chair inlaid with ivory. He wore a loin- cloth, presented to him by Cão, copper bracelets, and a cap of palm- cloth. A zebra tail depended from his left shoulder—a badge of royalty.306 The King was about to join his son Mbemba a Nzinga, Duke of Nsundi, who had taken the field against the Bateke;307 but before doing so he was anxious to be baptised. The foundations of a church having been laid on Rood Day, May 3rd,308 the King and his Queen were baptised at once by Frei João de Santa Maria, and were named Don João and Donna Leonor, after the King and Queen of Portugal.
  • 71. The King, marching for the first time under the banner of the Cross, and supported by the firearms of his Portuguese allies, came back a victor to his capital. His eldest son and many nobles were then baptised. When Ruy de Sousa departed, he left behind him Frei Antonio309 with other priests, and gave instructions for an exploration of the Kongo river above the cataracts, which do not appear to have been acted upon. He also founded a factory near the mouth of the Kongo, where the enterprising people of S. Thomé had already established commercial relations, although formal permission to do so was only granted them by King Manuel on March 26th, 1500. Dom Pedro, a cousin of the King of Kongo, accompanied him, with nine attendants, who, having been taught to read and write, returned to their native country with D. João Soares, early in 1494.310 The missionaries lost no time in preaching the doctrines of their Church; but whilst Don Affonso proved an ardent Christian, who recklessly destroyed all fetishes discovered in his province of Nsundi, the King himself soon grew lukewarm, owing to the priests’ interference with polygamy and other valued social institutions. In the country at large, the heathen still held their ground. D. Affonso I, 1509-1540.311 And thus it happened that when João I died in 1509, the chiefs favoured his second son, Mpanzu a nzinga,312 a heathen, whilst the dowager queen and the Count of Sonyo took the part of the elder brother. Don Affonso, immediately on hearing of his father’s illness, hurried up to the capital, accompanied by only thirty-six Christians. He found that his father had died. His brother approached with a mighty army, but five flaming swords seen in the heavens on the eve of battle gave courage to his small following, whilst a white cross and the appearance of St. James at the head of the celestial host struck terror into the hearts of the assailants. They fled in a panic.313 Mpanzu himself was taken, wounded, and decapitated.
  • 72. Order having been restored throughout the country, King Affonso availed himself of the presence of Gonçalo Rodriguez Ribeiro, who had come from Portugal with a number of priests, and was about to return to that country, to send an embassy to Pope Julius II and King Manuel.314 The head of this mission was Don Pedro (de Castro?), a cousin of the King (who was accompanied by his wife), and with him went D. Manuel, a brother of the King, and D. Henrique, a son. The presents conveyed to Portugal included seven hundred copper bracelets, elephant tusks, slaves, parrots, civet cats and other animals, and native cloth. D. Henrique remained behind at Rome, where he was ordained and created Bishop of Utica in 1518.315 The mission sent by King Manuel in return was far-reaching in its effects upon the political development of Kongo.316 Of its magnitude we may judge when we learn that it embarked in five vessels. Its leader, Simão da Silva, dying on the road to S. Salvador, his place was taken by Alvaro Lopes, the Royal factor. In his company were priests, experienced soldiers, masons and carpenters to build churches and a royal palace, and a lawyer (leterado) to explain the law books which figured among the royal gifts, besides horses, mules, cloth, banners, church furniture and images. The ambassador was instructed to explain the management of the royal household in Portugal, and King Affonso quickly learnt the lessons he received, and at once introduced the Portuguese titles of Duke, Marquis, and Count. The ambassador likewise had with him an elaborate coat-of- arms for the King,317 and twenty less ambitious heraldic designs for his principal noblemen; and the monarch himself adopted a title closely imitated from that of his “brother” of Portugal.318 The ambassador was likewise instructed to make inquiries about the origin of the Kongo in a lake, and to bring home cargoes of slaves, copper and ivory. The King was delighted with all these gifts, not being aware that by accepting them he virtually acknowledged himself to be a vassal of the King of Portugal; and he published a long manifesto to his
  • 73. people, in which he dwelt upon his past career, the blessings of the Christian faith, and the honours now done him. He actually read the six bulky folios, but he told Ruy d’Aguiar (in 1516) that if complicated laws like these were to be introduced in his dominions, not a day would pass without a legal offence of some kind being committed.319 The intercourse between Kongo and Lisbon must have been very active in those days. We learn, for instance, that in 1526 the King asked for physicians and apothecaries, and in 1530 he forwarded to his “brother” Manuel two silver bracelets, which he had received from Matamba. Many young Kongoese were sent to Portugal to be educated; but, to judge from a letter written by the King in 1517, the results were not always very gratifying.320 Nay, he accuses Antonio Viera, to whom he entrusted twenty young relations to be taken to Portugal, of having parted with several among them to Mpanzu- alumbu, his enemy, and of having left others behind him at S. Thomé.321 A second embassy left Kongo in 1540, to do homage to Pope Paul III. It was headed by D. Manuel, a brother of the King, who had been a member of D. Pedro’s mission. King Affonso expected the King of Portugal to pay 3,000 cruzados towards the expenses of this mission, in consideration of the large profits which he derived from the trade with Kongo.322 As a member of the Church militant, King Affonso deserved well of the priesthood. He ruthlessly ordered all fetishes to be destroyed throughout his dominions, but supplied their place with images of saints, crosses, agni dei, and other ecclesiastical paraphernalia, which he held to be more effectual. The clergy were numerous in his day, and in addition to secular priests included Franciscans, Dominicans and Austin Friars. They were wealthy, too, for lands and slaves had been given them, and Christian churches arose even in remote parts of the country. A Franciscan friar, Antonio de Dénis (known in the world as D. Diogo de Vilhegas) had been appointed Bishop of S. Thomé and Kongo,323 and took possession of his see in 1534, on which occasion exceptional honours were shown him. He
  • 74. was a man of energy and much sincerity, but, unhappily for his Church, survived only a few years. On his death-bed he desired that D. Henrique, the King’s son, whom he himself had ordained a priest, when in Rome, and whom the Pope (as already mentioned) had created Bishop of Utica in 1518, should succeed him in the episcopal chair. The Pope, however, before he would consent to the appointment of a native, desired personally to inquire into the matter. D. Henrique went to Rome, but died on the voyage home, in 1539 or earlier. King Affonso deserved his reputation as a zealous Christian, and had certainly proved himself a good friend to the regular and secular clergy who undertook to convert his people. Yet, as early as 1515, he had occasion to call upon the King of Portugal to aid him in suppressing the irregularities of these “unworthy preachers of the Holy Catholic Faith,” whose inordinate desire of power and covetousness brought scandal upon the Church, and promised little for the future.324 Towards the close of his reign, in 1540, one of these priests, Frei Alvaro, actually attempted to assassinate the King, in church, and after Mass!325 The Portuguese living at the time in Kongo were placed under a royal factor and a Corregedor (magistrate), and enjoyed ex-territorial jurisdiction. They had a factory at Mpinda, at the mouth of the Kongo, where the King of Portugal levied heavy duties. The commercial relations do not appear to have been at all times of the most friendly nature. In 1514 the King complained that Fernão de Mello, the Governor of S. Thomé, traded with the Mpangu-lungu326 who were his enemies; and in 1526 he remonstrated against the conduct of the Portuguese slave-merchants. Indeed, so preposterous were the claims put forward by the Portuguese officials, that King Affonso, in 1517, humbly begged to be allowed to employ a ship of his own when trading; or, at least to be exempted from paying the heavy duties exacted by a foreign, albeit suzerain, power upon the outlanders trading in his kingdom. These ill-advised exactions explain, too, why trade gradually deserted the Kongo, and sought
  • 75. more favourable openings to the south, at Luandu, as is shown by an inquiry held in 1548.327 The Portuguese made an effort to exploit the mineral wealth of the country. Ruy Mendes, the “factor of the copper mines,” is stated to have discovered lead; and Gimdarlach (Durlacher?), a German “fundidor,” in 1593 discovered copper, lead, and silver. The King, however, would not allow the mines to be worked, for he feared that such a concession might cost him his kingdom. Proposals for the exploration of the interior were made, but bore no fruit. Gregòrio de Quadra, who had spent several years as a prisoner among the Arabs, was sent to Kongo in 1520, with instructions to make his way thence to the country of Prester John. The King refused his consent; Quadra returned to Portugal, and died a monk.328 Balthasar de Castro, the companion of Manuel Pacheco in Angola, desired to explore the upper Kongo in 1526; but neither his scheme nor that of Manuel Pacheco himself, who was to have built two brigantines, seems to have been carried out. Of the domestic wars corned on by the King, we know next to nothing. Angola and Matamba seem to have been virtually independent in his day, though the island of Luandu, with its valuable cowry-fishery, was held by him and his successors until 1649. He conquered, however, Mpanzu-alumbu (Mpangu-lunga?)329 on the lower Kongo, a district inhabited by a predatory tribe.330 That his successes in these “wars” were due to his Portuguese mercenaries and their fire-locks is a matter of course. Don Affonso died in 1540, or soon afterwards, leaving behind him a son, D. Pedro, who succeeded him, and three daughters.331 D. Pedro and his Successors, 1540-1561. Pedro I had been educated in Portugal, and is described by Cavazzi as a wise prince who had inherited all the virtues of his father, and was a great friend of the missionaries. His reign was apparently a
  • 76. short one,332 and he was succeeded by a cousin, D. Francisco, who only reigned two or three years, and left the kingdom to a son,333 D. Diogo.334 Duarte Lopez describes this prince as a man of noble mind, witty, intelligent, prudent in council, an upholder of the missionaries, and at the same time a great warrior who, in the course of a few years, conquered many of the neighbouring countries. His “wars” certainly did not enlarge the borders of his kingdom, and the only war we know of ended in disaster. The Portuguese at S. Salvador, jealous of the growing commercial importance of Luandu, had persuaded the King to send an army against Ngola Mbandi, they themselves furnishing an auxiliary corps. The Kongoese, in spite of this, were defeated on the river Dande (about 1556); and Ngola not only appealed to Portugal for protection, but also allied himself with the Jagas, with whose aid he invaded Kongo (in 1558). Nor were the relations of D. Diogo with the missionaries quite as friendly as Lopez would lead us to believe. As early as 1549, D. Diogo complained of the overbearing conduct of the Jesuits who had arrived in that year in the company of D. João Baptista, the Bishop of S. Thomé;335 the priests, on their side, accused the King of having shown little respect to the bishop, and of having ordered them to be pulled out of their pulpits, when they denounced his vices and those of his people.336 The Jesuits may have been over-zealous in the performance of what they conceived to be their duty, and too prone to meddle in politics; but they seem to have led clean lives, which cannot be said of all of their clerical brethren. When D. Gaspar Cão,337 the Bishop of S. Thomé and Kongo, a man who took the duties of his office seriously, visited S. Salvador, these priests openly defied his authority. But after several of the recalcitrant priests had been deported to Portugal, whilst others had left voluntarily with such wealth as they had been able to amass, discipline was re- established.338 A Reign of Anarchy, 1561-1568.
  • 77. When Diogo died, about 1561, the Portuguese residents endeavoured to secure the throne for one of their own creatures, and caused the duly elected favourite of the people to be assassinated. As a result, the people of S. Salvador rose upon the Portuguese, many of whom were killed, not even priests being spared. The accounts339 of this period of disorder are too confused to enable us to be certain even of the names of the reigning kings. D. Affonso II, a son (probably illegitimate) of D. Diogo, ascended the throne of his father, but was murdered by his brother, D. Bernardo, who appears to have been the candidate favoured by the Portuguese. He at once sent Father Estevão de Laguos on an embassy to Queen Catherine of Portugal, who, in a letter dated June 26th, 1562,340 congratulated him upon his accession, whilst gently chiding him for the murder of his brother. This King was evidently friendly disposed towards the Portuguese; and Antonio Vieira, a negro, who had visited Portugal as member of an embassy, when writing to Queen Catherine in April 1566,341 suggested that he might be induced to allow the mines of copper and tin to be worked. D. Bernardo is stated by the Duke of Mbamba to have fallen in a war with the Anzicas, “in defence of Christianity and the Fatherland.” He was succeeded by D. Henrique, a brother of D. Diogo, who, after a short and troubled reign, died of a wound received in a battle, either against some revolted vassals,342 or fighting the Anzicanas.343 He was the last king of the original dynasty, for Alvaro I, his successor, was only a step-son. D. Alvaro I and the Ayaka, 1568-1574.344 D. Alvaro, immediately on his accession, sent an embassy to Portugal, to apologise for the massacre of many Portuguese during the reigns of his predecessors, which he excused on the ground of the vices and abuses of the clergy. These excuses were apparently accepted in Portugal, fortunately for D. Alvaro, for the very next year the dreaded Ayaka345 invaded his kingdom by way of Mbata; and, being worsted, the King fled with his adherents to the Hippopotamus
  • 78. Island,346 on the lower Kongo, where they suffered many hardships, and whence he appealed piteously to the Portuguese for help. This help was not denied him. Francisco de Gouvea, corregedor of S. Thomé, in 1570, hastened to his aid with six hundred Portuguese, expelled the Ayaka, reinstated the King in his capital, and built a wall round S. Salvador for greater security. The King fully recognised the value of the service that had been rendered him, for Paulo Dias de Novaes told Garcia Mendes347 that he acknowledged himself a vassal of Portugal;348 and as neither gold or silver had been discovered in his country, he agreed to pay a tribute in njimbos, which he actually did for a few years. No sooner was Alvaro once more seated securely upon his throne than he sent the Count of Sonyo against Ngola (1572). Several encounters took place in Musulu and Mbuila (Ambuila); but in the end Ngola was allowed to retain his father’s conquests, the river Dande being fixed upon as the boundary between the two kingdoms. Kongo, however, retained possession of the valuable island of Luandu. Among other events of this reign we should mention a second visit of D. Gaspar Cão, the bishop, shortly before his death (in 1574); and the scandal caused by the burial of a notorious infídel, D. Francisco Mbula matadi, in the church of S. Cruz, the roof of which was taken off by night, and the body, carried away by the Devil!349 D. Alvaro only enjoyed his prosperity for a short time, for when Paulo Dias landed at Luandu, in 1575, he was already dead.350 D. Alvaro II, 1574-1614. Alvaro II, a son of Alvaro I, is described by Bishop D. Manuel Baptista as a “zealous Christian, father and friend of all;”351 but it is evident that he looked not with overmuch favour upon the Portuguese residents in his country, and he is charged, in a memoir addressed by Domingos d’Abreu Brito to King Philip I, in 1592 with
  • 79. having plotted with the kings of Ndongo and Matamba against the Portuguese. An army which he sent ostensibly to the aid of the Portuguese in 1583 retired, apparently without striking a blow, whilst he furnished a contingent to the forces of Matamba which invaded Angola in 1590. He hindered, by specious excuses, the completion of a stone fort at Mpinda, which had been commenced in 1609 by Antonio Gonçalves Pitta, until all the workmen had died. He favoured Dutch traders to the great detriment of the Portuguese; and we know from Samuel Braun,352 that an effort was made in 1612 to expel the Dutch from the Kongo, and that it would have been successful, had not the natives sided with these heretical enemies, whose dealings appeared to them to be more generous. Moreover, the King, although he had promised Sebastian da Costa (1580) that he would allow the supposed silver mines to be sought for, eventually refused his consent.353 Turning to Church affairs, we hear of the usual applications for missionaries, and of several episcopal visitations by D. F. Antonio de Goiva (1578), D. Manuel de Ulhoa, D. Miguel Baptista Rangel, and D. Manuel Baptista. D. Manuel de Ulhoa presided over a synod at S. Salvador, in 1585, and laid down statutes for the government of his see. D. Miguel Baptista Rangel was the first Bishop of Kongo, which had been separated from the diocese of S. Thomé by a Bull of May 20th, 1596. His successor, D. Manuel Baptista, resided for several years in Kongo, where he died in 1621; and a letter addressed to King Philip II, in 1612,354 speaks of the results of over a century of missionary effort as insignificant, and describes the people as incurable barbarians, full of vice. D. Pedro II Affonso, 1622-1624. Bernardo II, a son of Alvaro II, only reigned for a few months, for he was killed by his brother, Alvaro III, and a complaint addressed to him by the Governor of Angola about the admission of heretical Dutchmen to trade in Sonyo was answered by his successor. This Alvaro III, the fratricide, is nevertheless described by Cavazzi as
  • 80. having been “wise, modest, courageous, and above all a zealous Christian.” It was during his reign, in 1619, that the Jesuits founded a college at S. Salvador. A proposed mission of Italian Capuchins came to nothing, for King Philip of Spain, by royal letters of September 22nd, 1620, forbade foreign missionaries to enter Portuguese colonies without first obtaining a royal license.355 Alvaro III died on May 26th, 1622, and was succeeded by D. Pedro II Affonso, whom Cavazzi describes as a son of Alvaro III; whilst a Jesuit canon of S. Salvador,356 who wrote an interesting life of this prince in 1624, makes him out to have been a son of Mbiki a ntumba, Duke of Nsundi, and a descendant, in the female line, of the first King of Kongo. If this biographer can be trusted, he was a man of much promise, and of a mild, forgiving temper; for although the Duke of Mbamba had sought his life, he conferred upon him the marquisate of Wembo. His reign was a short and troubled one. In August, 1622, the Duke of Mbata had been killed by rebels, and his vassal, the King of Kwangu (Ocango), had suffered a defeat. João Corrêa de Souza, the Governor of Angola, summoned him to surrender Luandu Island and all the copper mines; and this being refused, the Portuguese under Luiz Gomez, aided by the Jagas, crossed the Dande at Ikau and invaded Nambu a ngongo, and (in December) also Mbumbi, where the Duke of Mpemba and many others were killed and eaten by the Jagas, in spite of their being Christians. The people of the invaded districts revenged themselves by killing the Portuguese living in their midst, the King vainly endeavouring to protect them. These invaders had scarcely been driven off, when Captain Silvestre Soares, with a body of Jagas, entered Ngombe and Kabanda. But that which gave most pain to the King was the destruction of the kingdom of Bangu, and the murder of its King by the Jagas, with the aid of the King of “Loango,” which was the “trunk and origin of the kingdom of Kongo.”357 In the midst of these afflictions, the King was rejoiced to learn the arrival of D. Simão Mascarenhas at Luanda; but he met with an accident, and died on April 13th, 1624, after a short reign of less than two years, and mourned by six sons and two daughters.358
  • 81. D. Pedro’s successors, 1624-1641. Garcia, the eldest son of D. Pedro, when elected was only twenty years of age, He was succeeded by D. Ambrosio, in October, 1626, whose reign, up till March, 1631, was one continuous warfare with his powerful vassals. The country became unsafe, and the Portuguese retired for a time from S. Salvador. Alvaro IV, a son of Alvaro III, made himself master of the kingdom, and retained possession until his death, February 25th, 1636. He was succeded by his son, Alvaro V, who, doubting the loyalty of his half-brothers, the Duke of Mbamba and the Marquis of Kiowa, made war upon them, was defeated and taken prisoner, but liberated. Unmindful of the generosity of his opponents, he once more tried the fortune of battle, was taken again, and executed (in August, 1636). The Duke of Mbamba was unanimously elected in his place, and reigned, as Alvaro VI, until his death on February 22nd, 1641. He waged two unsuccessful wars against the Count of Sonyo, in 1636 and again in 1637; and was obliged to surrender the district of Makuta (Mocata) to his adversary. Garcia II Affonso, o Kimbaku, 1641-1663,359 the half-brother and old companion in arms of Alvaro VI, took possession of the throne at a critical time; for in August of the year of his accession, the Dutch captured Luandu, and the fortunes of the Portuguese were at the lowest ebb. The Dutch lost no time in sending an embassy to Kongo (1642),360 and these new allies lent him their assistance in a small war against Mwana Nsala, who had defied the royal authority.361 But they declined to give effective help against a more powerful vassal, the Count of Sonyo, as it might have interfered with their trade interests on the Lower Kongo.362 The King’s army was defeated twice on April 29th, 1645, when Affonso, the King’s son, was taken prisoner, and again in July 1648, in the forest of Mfinda angulu. Meanwhile the Dutch had broken the padrão set up by Cão at the mouth of the Kongo; they had re- named S. Antonio’s Bay after their river Pampus at Amsterdam; had
  • 82. gone to S. Salvador; and at least one of them, Johan Herder,363 had travelled far inland, and visited the Mwana Nkundi on the Kwangu. The heretical tracts and books which they liberally distributed were in due course burnt by the Capuchin friars. Portugal was, moreover, irritated by the admission of Italian and Castilian Capuchins, a batch of whom, headed by P. Bonaventura of Alessano,364 arrived at S. Salvador, on September 2nd, 1645, without having previously called at Lisbon. This first mission was followed by three others in 1648, 1651 and 1654,365 and mission stations were established in Mbata, in Nkusu, Nsundi, Mpemba, Mbwela, and Wembo (Ovando).366 Among the more noteworthy missionary travels of the time was that of P. Girolamo of Montesarchio, who visited Konko a bele (Concobello), in 1652.367 Even greater offence was given to Portugal by a mission which the King despatched to Rome in 1646, and which arrived there, by way of Holland, in May, 1648. P. Angelo de Valenza, the head of this mission, had been instructed to beg the Pope to appoint three bishops for Kongo, Matamba and the Makoko’s country, without reference to the claims of Portugal. This the Pope declined to do; but to show his pleasure at receiving this mission, he had a medal struck in memory of its visit, with the inscription “Et Congo agnovit Pastorem,” and sent the King a Royal crown blessed by himself. The King, however, when his mission returned (1651), and when he heard that the Pope had refused to change Kongo from an elective into a hereditary monarchy, grew wroth. He openly renounced Christianity, forbade the Capuchins to preach the word of God, and recalled his native ngangas. But when some bags containing relics and ornaments, which the King had taken out of the churches, were miraculously spared by a fire which broke out in his palace, he reconsidered his position. A reconciliation with the Capuchins was effected, and soon afterwards the King, in penitential robes, actually marched at the head of a procession which had been organised to turn away a threatened plague of locusts; he allowed himself to be
  • 83. crowned by P. Giannuario of Nola, in the name of his Holiness, and took an active part in the celebration of the Pope’s jubilee.368 Meanwhile the Portuguese had recovered Luandu, and the King was called upon to pay the penalty for having made friendship with the Dutch heretics, and admitted foreigners as missionaries. Bartholomeu de Vasconcellos invaded Kongo. The King at once sent P. Domingos Cardoso, a Jesuit, and the Capuchin Friar Bonaventura Sardo, to Luandu, where they had an interview with the Governor (on February 19th, 1649), and preliminary terms of peace were arranged.369 The treaty was reported upon by the Conselho Ultramarino, and confirmed in 1651 at Lisbon, whither Friar Bonaventura370 of Sorrento had gone to do homage to the King of Portugal, on behalf of the Prefect of the Capuchins, as also to plead the cause of his Order in reference to the proposed treaty. The terms of this treaty, as modified, were as follows:—Castilians or Dutchmen not to be permitted to reside or travel in Kongo nor their ships to be admitted, unless provided with a Portuguese passport; the Capuchin friars to communicate with Rome only by way of Luandu or Lisbon, and no Castilians to be admitted among them; the Kings of Kongo and Portugal to mutually assist each other if attacked by an enemy; an ambassador of the King of Kongo to take up his residence at Luandu, as also a royal prince, as hostage, or in his absence two or three men of rank; compensation to be granted for all the losses suffered by the Portuguese since the arrival of the Dutch, and fugitive slaves to be surrendered; Portuguese merchants to be exempted from the payment of tolls; a site to be granted at the mouth of the Kongo for a fortress; all gold and silver mines to be ceded to the crown of Portugal, and the country to the south of the river Dande to be ceded absolutely; and finally the King of Kongo to acknowledge himself a “tributario” of Portugal. The King seems to have long hesitated before he ratified this treaty, for in 1656, Diogo Gomes de Morales was ordered to invade Kongo to enforce it, and was on the point of crossing the river Loje into
  • 84. Mbamba, when he was recalled, as envoys from the King had arrived at Luandu, definitely to arrange the terms of peace. During the later years of his life, D. Garcia once more fell away from his Christian teachers, whom he accused of being influenced by political motives. Suspecting the Duke of Mpemba of a desire to deprive his son of the succession, he had him executed; and when the native diviners accused his eldest son, Affonso, of aiming at his life, he had his second son elected as his successor. He died in 1663. D. Antonio I, 1663-66. D. Antonio had been enjoined by his dying father to avenge the humiliation forced upon him by the Portuguese. He inaugurated his reign by killing his own brother and other relatives, whom he suspected of disloyalty. The warnings of heaven—fiery balls, an earthquake, which destroyed part of his capital, a plague, which decimated the population—were disregarded by him. He very soon found himself involved in a war with the Portuguese, who claimed possession of the mines which had been promised by treaty, and complained of raids made upon friendly chiefs. On July 13th, 1665, the King called upon his people to rise in defence of their country and liberty.371 His diviners had promised him an easy victory. The Portuguese had recently been reinforced from Brazil, yet the army which they were able to put into the field only numbered four hundred Europeans, with two field guns and six thousand negroes. It was commanded by Luiz Lopez de Sequeira, the captain- major, with whom were Manuel Rebello de Brito, Diogo Rodriguez de Sá, Simão de Matos and Antonio Araujo Cabreira, the serjeant-major. The hostile forces met on January 1st, 1666, at Ulanga, near the Pedras de Ambuilla.372 Antonio, seeing the small force opposed to him, hoped to gain an easy victory; but the Portuguese, formed in square, resisted the onslaught of his hosts for six hours. At last the King left the ranks, desirous of a personal encounter with Lopez de Sequeira; but he was shot down, his head was cut off, and stuck
  • 85. upon a pike. His followers fled in dismay. The missionaries assert that the Virgin Mary, with her Child, was seen to stand by the side of the Portuguese leader, directing the battle, and that a fiery rain fell upon the idolaters.373 The Governor of Angola, in commemoration of this victory, built the chapel of N.S. da Nazareth at Luandu, whilst the King of Portugal amply rewarded the victors. A Time of Anarchy, after 1666. We are indebted to Pedro Mendes for an account of the history of Kongo from the death of D. Antonio in 1666 to the beginning of the eighteenth century.374 During that time, according to this authority, there were fourteen Kings of Kongo, of whom four were beheaded (or killed) by the Musurongo, five by the Ezikongo, three died a natural death, and two were survivors when he wrote, namely, D. Pedro IV, at Salvador, and D. João at Mbula.375 At one time there were actually three kings in the field. Alvaro VII, a royal prince who had passed his early life in retirement, but who, on being raised to the throne, turned out a monster of iniquity, was killed by his own subjects, abetted by the Count of Sonyo (1666), under whose auspices took place the election of his successor, D. Alvaro VIII (1666-70), who was in turn removed by the Marquis of Mpemba. Alvaro VIII376 had allowed the Portuguese to search for gold, but this search turned out as fruitless as the search for silver at Kambambe. Meanwhile D. Affonso III Affonso had been proclaimed at Kibangu, the new capital (1667), whilst D. Pedro III nsukia ntamba was put up as an opposition King in Mbula. The latter defeated his rival, who fled beyond the Mbiriji (Ambriz), and died there (of poison?). His widow, D. Anna, a daughter of a former King, Garcia, retired to Nkondo (Mucondo), and survived her husband until 1680. The people proclaimed D. Garcia III nenganga mbemba377 his successor, whilst the opposition, at the old capital (S. Salvador), declared D. Daniel de Guzman, descendant of Mpanzu (Alvaro I), to be
  • 86. the rightful King. D. Daniel took the field against D. Garcia III, but, before he reached the residence of that King, he was overtaken by D. Pedro of Mbula; his army was dispersed, and himself beheaded. His children sought refuge with the Count of Sonyo, and by treachery they succeeded in getting D. Pedro into their power, and killed him. The people of Mbula thereupon raised his brother, D. João, to the throne, who survived until after 1710. S. Salvador, after D. Daniel had deserted it, became the haunt of wild beasts. Meanwhile D. Rafael, Marquis of Mpemba, who had been proclaimed King some time anterior to this, had been obliged to seek refuge among the Portuguese, and his reinstatement was one of the objects of the disastrous expedition of 1670,378 by which it was sought to punish Count Estevão da Silva of Sonyo for his desecration of Christian churches and the ill-treatment of Portuguese traders: or, rather, his dealings with heretic competitors. João Soares de Almeida, the commander of this expedition, had with him five hundred Portuguese, supported by a strong force of native allies, among whom was a Jaga Kalandula. He won a battle, in which Estevão was killed; but Pedro, the brother of the unfortunate Count, rallied the forces of Sonyo, unexpectedly fell upon the Portuguese near the Mbiriji (Ambriz),and scarcely a man among them escaped. Count Pedro then expelled the Italian Capuchins, who were supposed to be friendly to Portugal, and invited in their stead Belgian members of the same Order, who arrived in September, 1673, under the lead of P. Wouters. But, having been accused of stopping the rain, and having in reply excommunicated the Count, they were speedily expelled.379 Peace between Sonyo and Portugal was only restored in 1690, when the former promised to abolish idolatry and to sell no slaves to heretics. It was about this period (between 1669 and 1675) that Francisco do Murça, the captain-major of Dande, visited S. Salvador, and proceeded thence to Mbata and the Kwangu, where he was told that this river flowed through the kingdom of the Makoko, and entered
  • 87. the sea at Mpinda, a fact long before known to the missionaries. These latter had not quite abandoned the Kongo, notwithstanding these troubles, and in 1668 the Capuchins still occupied their monasteries at the capital of Mbamba and at Mpembu;380 whilst Girolamo Merolla (1682-88) and Antonio Zucchelli steadily laboured (1700-02) in Sonyo and Luangu.381 D. Andre succeeded D. Garcia, but died after a short reign. D. Manuel nzinga elenge, a descendant of Mpanzu, was duly elected, but expelled by the sons of the late D. Garcia, who raised Alvaro IX to the throne in his stead. This prince was never recognised by the Count of Sonyo, who looked upon D. Manuel, who had sought refuge with him, as the legitimate King. He was reinstated by him for a time, but ultimately fell into the power of his enemies, and was beheaded. Alvaro IX was succeeded in 1694 by his brother Pedro IV nsanu a mbemba, also known as agoa rosada,382 who once more returned to the ancient capital. He and D. João of Mbula were the only Kings alive in 1701, when the Capuchin Friar Francisco de Pavia, and his colleague Friar João Maria went throughout the kingdom of Kongo, preaching peace, and calling upon the leading men to recognise D. Pedro as their King; and thus put an end to quarrels which had distracted the country for an entire generation. A Retrospect. And if we ask to what extent, and in what manner, have the natives of Kongo been benefited by two centuries of contact with the civilisation of Europe, and of missionary effort, we feel bound to admit that they have not been benefited at all—either materially or morally. On the contrary. There were, no doubt, a few earnest men among the missionaries, and the Church of Rome deserves some credit for the zeal with which she addressed herself to the object of converting the natives. At the same time it cannot be denied that the instruments she employed, the methods she pursued, and the
  • 88. 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