100% found this document useful (2 votes)
16 views

Simple and Efficient Programming with C# : Skills to Build Applications with Visual Studio and .NET 2nd Edition Vaskaran Sarcar download

The document is an overview of the book 'Simple and Efficient Programming with C#' by Vaskaran Sarcar, which aims to teach readers how to build applications using Visual Studio and .NET. The second edition includes new content, such as chapters on error handling and updated programming techniques, while maintaining the core goals of the first edition. It is intended for readers with a basic understanding of C# and object-oriented programming concepts, focusing on practical application and design principles for developing robust software.

Uploaded by

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

Simple and Efficient Programming with C# : Skills to Build Applications with Visual Studio and .NET 2nd Edition Vaskaran Sarcar download

The document is an overview of the book 'Simple and Efficient Programming with C#' by Vaskaran Sarcar, which aims to teach readers how to build applications using Visual Studio and .NET. The second edition includes new content, such as chapters on error handling and updated programming techniques, while maintaining the core goals of the first edition. It is intended for readers with a basic understanding of C# and object-oriented programming concepts, focusing on practical application and design principles for developing robust software.

Uploaded by

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

Simple and Efficient Programming with C# :

Skills to Build Applications with Visual Studio


and .NET 2nd Edition Vaskaran Sarcar install
download
https://ebookmeta.com/product/simple-and-efficient-programming-
with-c-skills-to-build-applications-with-visual-studio-and-
net-2nd-edition-vaskaran-sarcar/

Download more ebook from https://ebookmeta.com


We believe these products will be a great fit for you. Click
the link to download now, or visit ebookmeta.com
to discover even more!

Simple and Efficient Programming with C#: Skills to


Build Applications with Visual Studio and .NET 1st
Edition Vaskaran Sarcar

https://ebookmeta.com/product/simple-and-efficient-programming-
with-c-skills-to-build-applications-with-visual-studio-and-
net-1st-edition-vaskaran-sarcar-2/

Simple and Efficient Programming with C#: Skills to


Build Applications with Visual Studio and .NET 1st
Edition Vaskaran Sarcar

https://ebookmeta.com/product/simple-and-efficient-programming-
with-c-skills-to-build-applications-with-visual-studio-and-
net-1st-edition-vaskaran-sarcar/

Simple and Efficient Programming with C# Vaskaran


Sarcar

https://ebookmeta.com/product/simple-and-efficient-programming-
with-c-vaskaran-sarcar/

The January 6th Report The Report of the Select


Committee to Investigate the January 6th Attack on the
United States Capitol 1st Edition Bennie Thompson

https://ebookmeta.com/product/the-january-6th-report-the-report-
of-the-select-committee-to-investigate-the-january-6th-attack-on-
the-united-states-capitol-1st-edition-bennie-thompson/
Clinical manual of psychopharmacology in the medically
ill 2nd Edition Stephen J. Ferrando

https://ebookmeta.com/product/clinical-manual-of-
psychopharmacology-in-the-medically-ill-2nd-edition-stephen-j-
ferrando/

Ollie Goes the Distance All About Electric Cars Claire


Winslow

https://ebookmeta.com/product/ollie-goes-the-distance-all-about-
electric-cars-claire-winslow/

Methods for the Analysis of Asymmetric Proximity Data


Giuseppe Bove Akinori Okada Donatella Vicari

https://ebookmeta.com/product/methods-for-the-analysis-of-
asymmetric-proximity-data-giuseppe-bove-akinori-okada-donatella-
vicari/

Dieting Overweight and Obesity Self Regulation in a


Food Rich Environment 2nd Edition Wolfgang Stroebe

https://ebookmeta.com/product/dieting-overweight-and-obesity-
self-regulation-in-a-food-rich-environment-2nd-edition-wolfgang-
stroebe/

Crown and Cinder (The Austen Fairy Tales #2) 1st


Edition Kendra E. Ardnek

https://ebookmeta.com/product/crown-and-cinder-the-austen-fairy-
tales-2-1st-edition-kendra-e-ardnek/
Conquering JavaScript: D3.js Sufyan Bin Uzayr

https://ebookmeta.com/product/conquering-javascript-d3-js-sufyan-
bin-uzayr/
Vaskaran Sarcar

Simple and Efficient Programming with


C#
Skills to Build Applications with Visual Studio and
.NET
2nd ed.
Vaskaran Sarcar
Kolkata, West Bengal, India

ISBN 978-1-4842-8736-1 e-ISBN 978-1-4842-8737-8


https://doi.org/10.1007/978-1-4842-8737-8

© Vaskaran Sarcar 2021, 2023

This work is subject to copyright. All rights are solely and exclusively
licensed by the Publisher, whether the whole or part of the material is
concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in
any other physical way, and transmission or information storage and
retrieval, electronic adaptation, computer software, or by similar or
dissimilar methodology now known or hereafter developed.

The use of general descriptive names, registered names, trademarks,


service marks, etc. in this publication does not imply, even in the
absence of a specific statement, that such names are exempt from the
relevant protective laws and regulations and therefore free for general
use.

The publisher, the authors, and the editors are safe to assume that the
advice and information in this book are believed to be true and accurate
at the date of publication. Neither the publisher nor the authors or the
editors give a warranty, expressed or implied, with respect to the
material contained herein or for any errors or omissions that may have
been made. The publisher remains neutral with regard to jurisdictional
claims in published maps and institutional affiliations.

This Apress imprint is published by the registered company APress


Media, LLC, part of Springer Nature.
The registered company address is: 1 New York Plaza, New York, NY
10004, U.S.A.
I dedicate this book to the programming lovers of C#.
Introduction
It is my absolute pleasure to write the second edition of Simple and
Efficient Programming with C#: Skills to Build Applications with Visual
Studio and .NET. You can surely guess that I got this opportunity
because you liked the previous edition of the book and shared your
feedback with us. So, once again I’m excited to join you and help you to
learn more. This time I present a further simplified, better organized,
and more content-rich edition to you.
Let me remind you of the key goals of this book. I wrote about them
in the first edition as well. C# is an object-oriented programming (OOP)
language. You may already know C# keywords or even some interesting
features. You may also know how to write simple programs in C#. You
can learn these things from an introductory book or an online tutorial.
These are useful things to know, but they are not sufficient to
understand an enterprise codebase. This is why a novice programmer
often finds it difficult to understand an expert’s code. They may wonder
why an experienced programmer wrote the program in a particular
way. It may appear to the novice that the expert could have used an
easier approach to solve the problem. But there are reasons why an
experienced programmer might follow a different approach. The word
experienced indicates that these programmers have more experience in
programming and know the pros and cons of different approaches.
They know how the C# features can be used in the best possible way to
develop an application. So, the applications they make are usually
powerful. What do I mean by a powerful application? For me, a
powerful application is robust, extensible, and easily maintainable, but
simple to use. This book is an introductory guide for developing such
applications. This was the core aim of this book.
To write better-quality programs, senior programmers follow
experts’ footprints. They learn from the collective wisdom and recorded
experience of the past. So, instead of attempting an entirely new
solution, you should first consider this knowledge base, which will help
you produce better-quality code. It is always better if you know about
why you should or shouldn’t follow any specific guideline.
Malcolm Gladwell, in his book Outliers (Little, Brown and Company),
discussed the 10,000-hour rule. This rule says that the key to achieving
world-class expertise in any skill is, to a large extent, a matter of
practicing the correct way, for a total of around 10,000 hours. I
acknowledge that it is impossible to consider all experiences before you
write a program. Also, sometimes it is OK to bend the rules if the return
on investment (ROI) is nice. So, keep in mind the Pareto principle, or
the 80-20 rule. This rule simply states that 80 percent of outcomes
come from 20 percent of all causes. This is useful in programming too.
When you identify the most essential characteristics of top-quality
programs and use them in your applications, you also qualify yourself
as an experienced programmer, and your application will be robust,
flexible, and maintainable. In this book, I share with you these
important principles using some case studies, which will help you write
better programs. Some of these principles you may know already, but
when you see them in action and compare these case studies, you’ll
understand their importance.
So, what is new in this second edition? Well, the first thing I want
to tell you is that this edition maintains the same goals that were
mentioned in the first edition. Second, you can easily guess that it is a
further simplified, enlarged, and polished version. This time you see the
use of top-level statements throughout the book. You may know that
top-level statements have been supported since C# 9.0. In addition, the
.NET 6+ project template for C# console apps uses top-level statements.
At the time of this writing, C# 11 is not released, but you can test the
preview features. I have taken this opportunity to use some of them,
particularly raw-string literals. I talk about static abstract interface
members too. I used many preview features in my other book, Test Your
Skills in C# Programming. But for this book, not all of them are required.
Additionally, this is an expanded edition. Two new chapters in Part
IV, Chapter 10 and Chapter 11, talk about handling errors in a better
way. Particularly, you’ll see a discussion of organizing exceptions and
handling null values with different case studies.
How Is the Book Organized?
The book has five major parts, which are as follows:
The first three chapters form Part I, in which there is a detailed
discussion of polymorphism and the use of abstract classes and
interfaces. Here, code comments will be examined, and you will learn
when to use them effectively. These are the fundamental building
blocks for the rest of the book.
In the world of programming, there is no shortage of programming
principles and design guidelines. Each of these suggestions has its
own benefits. To become a professional programmer, you do not need
to learn everything at the same time. In Part II, I discuss six design
principles, which include the SOLID principles and the DRY principle.
These are the foundation of well-known design patterns.
The best way to learn is by doing and analyzing case studies. So, in
Part III of the book, you will see interesting applications that use
some well-known patterns. This part gives you hints about how a
professional coder develops an enterprise application.
Handling errors is an unavoidable part of programming. Particularly,
runtime exceptions are dangerous, and often they appear in the form
of NullReferenceException in C#. Part IV focuses on them,
discusses different case studies with easy-to-understand examples,
and provides useful suggestions about possible improvements.
There is no end to learning. So, Part V includes some interesting
topics such as how to prevent memory leaks, how to choose between
a static method and an instance method, and some common terms
from software development that are not discussed in detail in this
book. A quick overview of these topics will help your future learnings
and experiments.
You can download all the source codes for the book from the
publisher’s website. I have a plan to maintain the “errata,” and, if
required, I can also make some updates/announcements there. So, I
suggest you visit those pages to receive any important corrections or
updates.

Prerequisite Knowledge
This book is intended for those who are familiar with the common
language constructs of C# and have a basic understanding of pure
object-oriented concepts such as polymorphism, inheritance,
abstraction, encapsulation, and, most importantly, how to compile or
run a C# application in Visual Studio. This book does not invest time in
easily available topics, such as how to install Visual Studio on your
system, how to write a “Hello World” program in C#, how you can use
an if-else statement or a while loop, etc. This book is written using
the most basic features of C# so that for most of the programs herein
you do not need to be familiar with advanced topics in C#. The
examples are simple, and I believe that they are written in such a way
that even if you are familiar with another popular language such as
Java, C++, and so on, you can still easily grasp the concepts in this book.
Who Is This Book For?
In short, you can pick up this book if the answer is “yes” to the
following questions:
Are you familiar with basic constructs in C# and object-oriented
concepts such as polymorphism, inheritance, abstraction, and
encapsulation?
Do you know how to set up your coding environment?
Have you completed at least one introductory course on C# and now
are interested in writing better programs?
Are you also interested to know how a professional programmer
designs their applications?
You probably shouldn’t pick this book if the answer is yes to any of
the following questions:
Are you absolutely new to C#?
Are you looking for advanced concepts in C#, excluding the topics
mentioned previously?
Are you interested in exploring a book where the focus is not on
standard design principles?
Do you not like Windows, Visual Studio, and/or .NET and want to
learn and use C# without them?

Guidelines for Using This Book


To use this book more effectively, consider the following:
This book works best if you’ve gone through an introductory course
on C# and are familiar with the common terms, such as
polymorphism, and have heard about abstract classes and interfaces.
If this is not the case, please read about these topics before you start
reading this book.
I suggest you go through the chapters sequentially. This is because
some fundamental design techniques may have been discussed in a
previous chapter, and I have not repeated those techniques in later
chapters.
I started this book using Microsoft Visual Studio Community 2022
in a Windows 10 environment. This community edition is free of
charge. When I started the book, I started with the latest versions of
C# that were available at that time. You can easily guess that version
updates kept coming, so I kept updating my code repository. When I
finished my first draft, I had the most recent version of Visual Studio
Community 2022 (version 17.3.3). Almost in every case, my target
framework was .NET 7.0, which supports C# 11.
In this context, it is useful to know that nowadays the C# language
version is automatically selected based on your project’s target
framework(s), so you can always get the highest compatible version
by default.
For example, C# 11 is for .NET 7 and later versions. Similarly, C# 10 is
supported only on .NET 6 and newer versions. C# 9 is supported only
on .NET 5 and newer versions. C# 8.0 is supported only on .NET Core
3.x and newer versions. If you are interested in the C# language
versioning, you can go to this link:
https://docs.microsoft.com/en-
us/dotnet/csharp/language-reference/configure-
language-version.
The fact is that these version updates will come continuously, but I
strongly believe that these version details should not matter much to
you because I have used the fundamental constructs of C#. So, the
code in this book should execute smoothly in the upcoming versions
of C#/Visual Studio as well. Though I also believe that the results
should not vary in other environments, you know the nature of
software—it is naughty. So, I recommend that if you want to see the
exact same output, you mimic the same environment.
If you do not use the Windows operating system, you can use Visual
Studio Code, which is also a source-code editor developed by
Microsoft to support Windows, Linux, or Mac operating systems. This
multiplatform IDE is also free.
You can download and install the Visual Studio IDE from
https://visualstudio.microsoft.com/downloads/. You
will the screen shown in Figure I-1.
Note At the time of writing, this information is correct. But the
link and policies may change in the future.

I have also installed the class designer component in Visual Studio


2022 to draw class diagrams for my programs. They’ll help you
understand the code better.

Figure I-1 Download link for Visual Studio 2022 and Visual Studio Code

Conventions Used in This Book


All the output and code of the book follow the same font and structure.
To draw your attention to some places, I have made them bold. For
example, consider the following code fragment and the lines in bold
(taken from Chapter 4 when I discuss the LSP):

// The previous codes are skipped

// Instantiating two registered users


RegisteredUser robin = new("Robin");
RegisteredUser jack = new("Jack");
helper.AddUser(robin);
helper.AddUser(jack);

GuestUser guestUser1 = new();


helper.AddUser(guestUser1);

// Processing the payments using


// the helper class.
// You can see the problem now.
helper.ShowPreviousPayments();
helper.ProcessNewPayments();

// The remaining codes are skipped

Final Words
You are an intelligent person. You have chosen a subject that can assist
you throughout your career. As you learn about these concepts, I
suggest you write your own code; only then will you master this area.
There is no shortcut to true learning. In a similar context, can you
remember Euclid’s (the ancient Greek mathematician who is often
considered the father of geometry) reply to the ruler? If not, let me
remind you of his reply: “There is no royal road to geometry.” Similarly,
in programming, there is no shortcut. So, study and code; understand a
new concept and code again. Do not give up when you face challenges.
They are the indicators that you are growing better.
I believe that this book is designed for you in such a way that upon
its completion, you will develop an adequate knowledge of the topic,
and, most importantly, you’ll know how to go further. Lastly, I hope that
this book can provide help to you and that you will value the effort.
Any source code or other supplementary material referenced by the
author in this book is available to readers on GitHub
(https://github.com/Apress). For more detailed information, please
visit www.apress.com/source-code.
Table of Contents
Part I: Fundamentals
Chapter 1:​Flexible Code Using Polymorphism
Recap of Polymorphism
Initial Program
Demonstration 1
Output
Analysis
Better Program
Demonstration 2
Analysis
Useful Notes
Summary
Chapter 2:​Abstract Class or Interface?​
Recap of Abstract Classes and Interfaces
Initial Program
Demonstration 1
Better Program
Demonstration 2
Output
Analysis
Summary
Chapter 3:​Wise Use of Code Comments
Recap of Code Comments
Initial Program
Demonstration 1
Output
Analysis
Better Program
Demonstration 2
Analysis
Use the Power of C#
Demonstration 3
Analysis
Summary
Part II: Important Principles
Chapter 4:​Know SOLID Principles
Single Responsibility Principle
Initial Program
Better Program
Open/​Closed Principle
Initial Program
Better Program
Liskov Substitution Principle
Initial Program
Better Program
Analysis
Interface Segregation Principle
Initial Program
Better Program
Dependency Inversion Principle
Initial Program
Better Program
Summary
Chapter 5:​Use the DRY Principle
Reasons for DRY
Initial Program
Demonstration 1
Output
Analysis
Better Program
Demonstration 2
Output
Analysis
Further Improvement
Demonstration 3
Output
Demonstration 4
Output
Summary
Part III: Make Efficient Applications
Chapter 6:​Separate Changeable Code Using Factories
The Problem Statement
Initial Program
Demonstration 1
Output
Analysis
Better Program
Demonstration 2
Output
Analysis
A New Requirement
Demonstration 3
Output
Analysis
Demonstration 4
Output
Summary
Chapter 7:​Add Features Using Wrappers
The Problem Statement
Initial Program (Using Subclassing)
Demonstration 1
Better Program (Using Object Composition)
Class Diagram
Demonstration 2
Output
Analysis
Summary
Chapter 8:​Make Efficient Templates Using Hooks
The Problem Statement
Initial Program
Class Diagram
Demonstration 1
Output
Analysis
Enhanced Requirement
Demonstration 2
Output
Summary
Chapter 9:​Simplify Complex Systems Using Facades
The Problem Statement
Initial Program
Demonstration 1
Output
Analysis
Better Program
Class Diagram
Demonstration 2
Output
Analysis
Summary
Part IV: Handling Surprises in a Better Way
Chapter 10:​Organizing Exceptions
Recap of Exceptions
Case 1:​Handling Different Exceptions in the Same Way
Initial Program
Better Program
Case 2:​Handling the Same Exception in Different Ways
Initial Program
Better Program
Summary
Chapter 11:​Special Attention to the Null Values
Initial Program
Demonstration 1
Output
Analysis
Better Programs
Demonstration 2
Output
Analysis
Demonstration 3
Analysis
Summary
Part V: The Road Ahead
Chapter 12:​Memory Management
Overview
Stack Memory vs.​Heap Memory
Q&​A Session
The Garbage Collector in Action
Different Phases of Garbage Collection
Different Cases of Invoking the Garbage Collector
Demonstration 1
Output
Analysis
Q&​A Session
Disposing of an Object
Finalize vs.​Dispose
Demonstration 2
Output
Analysis
Q&​A Session
Summary
Chapter 13:​Analyzing Memory Leaks
Managed vs.​Unmanaged Memory Leaks
Memory Leak Analysis
Demonstration
Snapshots from Diagnostic Tools
Summary
Chapter 14:​More Tips
Learn Design Patterns
Brief History of Design Patterns
The Good News
Q&​A Session
Avoid Anti-patterns
Brief History of Anti-patterns
Examples of Anti-patterns
Q&​A Session
Final Suggestions
Decide Between a Static Method and an Instance Method
Know the Common Terminology
Accept Failures!
Q&​A Session
Summary
Appendix A:​Winning Notes
Appendix B:​Resources
Index
About the Author
Vaskaran Sarcar
obtained his master’s degree in software
engineering from Jadavpur University,
Kolkata (India), and his MCA from
Vidyasagar University, Midnapore
(India). He was a National Gate Scholar
(2007–2009) and has more than 12
years of experience in education and the
IT industry. Vaskaran devoted his early
career (2005–2007) to the teaching
profession at various engineering
colleges, and later he joined HP India
PPS R&D Hub Bangalore. He worked
there until August 2019. At the time of
his retirement from HP, he was a senior
software engineer and team lead. To
follow his dream and passion, Vaskaran
is now an independent full-time author. Other Apress books by
Vaskaran include:
Test your Skills in C# Programming (Apress, 2022)
Java Design Patterns, Third Edition (Apress, 2022)
Simple and Efficient Programming in C# (Apress, 2021)
Design Patterns in C#, Second Edition (Apress, 2020)
Getting Started with Advanced C# (Apress, 2020)
Interactive Object-Oriented Programming in Java, Second Edition
(Apress, 2019)
Java Design Patterns, Second Edition (Apress, 2019)
Design Patterns in C# (Apress, 2018)
Interactive C# (Apress, 2017)
Interactive Object-Oriented Programming in Java (Apress, 2016)
Java Design Patterns (Apress, 2016)
The following are other books he’s written:
Python Bookcamp (Amazon, 2021)
Operating System: Computer Science Interview Series (Createspace,
2014)
About the Technical Reviewers
Shekhar Kumar Maravi
is a lead engineer in design and
development whose main interests are
programming languages, algorithms, and
data structures. He obtained his master’s
degree in computer science and
engineering from the Indian Institute of
Technology – Bombay. After graduation,
he joined Hewlett-Packard’s R&D Hub in
India to work on printer firmware.
Currently he is a technical lead engineer
for automated pathology lab diagnostic
devices at Siemens Healthcare R&D
division. He can be reached by email at
shekhar.maravi@gmail.com or via
LinkedIn at www.linkedin.com/in/shekharmaravi.

Carsten Thomsen
is a back-end developer primarily but
works with smaller front-end bits as
well. He has authored and reviewed a
number of books and created numerous
Microsoft Learning courses, all to do
with software development. He works as
a freelancer/contractor in various
countries in Europe, using Azure, Visual
Studio, Azure DevOps, and GitHub. He
also enjoys working with architecture,
research, analysis, development, testing,
and bug fixing.
Part I
Funda
mentals
Part I consists of three chapters, in which we will discuss the following
questions:
How can we use the power of polymorphism, and why is it
beneficial?
How can we combine an abstract class and interfaces to make an
efficient application?
How can we use meaningful code comments and avoid unnecessary
comments in a program?
Almost every C# application uses comments, the concept of
polymorphism, and abstract classes and interfaces. When we
implement these techniques in a better way, the program is better. I
consider them the fundamental techniques for an efficient application.
© The Author(s), under exclusive license to APress Media, LLC, part of Springer
Nature 2023
V. Sarcar, Simple and Efficient Programming with C#
https://doi.org/10.1007/978-1-4842-8737-8_1

1. Flexible Code Using Polymorphism


Vaskaran Sarcar1

(1) Kolkata, West Bengal, India

Ask a developer the following question: “What are the fundamental


characteristics of object-oriented programming (OOP)?” You will hear
an immediate reply saying that classes (and objects), inheritance,
abstraction, encapsulation, and polymorphism are the most important
characteristics of OOP. In addition, when you analyze OOP-based
enterprise code, you’ll find different forms of polymorphism. But the
truth is that a novice programmer rarely uses the power of
polymorphism. Why? It is said that object-oriented programmers pass
through three important stages. In the first stage, they become familiar
with non-object-oriented constructs. In this stage, they use decision
statements, looping constructs, etc. In the second stage, they start
creating classes and objects and use the inheritance mechanism. Finally,
in the third stage, they use polymorphism to achieve late binding and
make their programs flexible. But writing the polymorphic is not always
easy. Honestly, it is a little bit tough compared to the other features of
OOP. Using some simple but powerful code examples, this chapter will
make this concept easy for you to understand.

Recap of Polymorphism
Polymorphism simply means there is one name with many forms. In the
real world, it is a common phenomenon. Consider the behavior of your
pet dog: when it sees an unknown person, it starts barking. But when it
sees you, it makes different noises and behaves differently. In both
cases, this dog sees with its eyes, but based on the observation, the dog
behaves differently.
You can relate this concept to other areas as well. For example,
consider the customer support departments in different organizations.
They each provide support to the customers in their own way. Similarly,
each of the search engine providers such as Google, Yahoo, or Microsoft
Bing searches the Internet following its own algorithm.
OOP likes to mimic real-world scenarios, and conceptually, the
polymorphic code works in the same way. In C#, a class can have
methods (or properties). Optionally, you can provide implementations
for them. C# also allows the derived classes to override those
implementations as per their needs. As a result, these related types can
have methods with the same name, but they can show different
behaviors. This is the key concept to understand before you deal with
the polymorphic code.

Initial Program
The importance of a feature is often realized in the absence of it. So, I
start with a program that does not use the concept of polymorphism.
This program compiles and runs successfully. Here you have three
different types of animals—tigers, dogs, and monkeys. Each of
them can produce a different sound. So, I made classes with their
corresponding names, and in each class, you see a Sound() method.
Check whether you can improve this program.

Demonstration 1
Here is the complete demonstration:

Console.WriteLine("***Sounds of the different


animals.***");
Tiger tiger = new();
tiger.Sound();
Dog dog = new();
dog.Sound();
Monkey monkey = new();
monkey.Sound();
Console.ReadKey();
class Tiger
{
public void Sound()
{
Console.WriteLine("Tigers roar.");
}
}
class Dog
{
public void Sound()
{
Console.WriteLine("Dogs bark.");
}
}
class Monkey
{
public void Sound()
{
Console.WriteLine("Monkeys whoop.");
}
}

Output
Here is the output:

***Sounds of the different animals.***


Tigers roar.
Dogs bark.
Monkeys whoop.

Analysis
I have used the simplified new expressions here. For example, the line
Tiger tiger = new(); is the simplified version of Tiger tiger
= new Tiger(); Starting with C# 9.0, you can use this form. It says
that during the constructor invocation if the target type of an
expression is known, you can omit the type name.
When you use Tiger tiger = new Tiger();, the tiger is a
reference to an object that is based on the Tiger class. This reference
refers to the object, but it does not contain the object data itself. Even
Tiger tiger; is a valid line of code that creates an object reference
without creating the actual object.
Understand that when you use Tiger tiger = new
Tiger();, we say that you are programming to an implementation.
Notice that in this case the reference and object both are of the same
type. You can improve this program using the concept of
polymorphism. In the upcoming implementation, I show you such an
example. I use an interface in this example. Before I show you the
example, let me remind you of a few important points:
I could achieve the same effect using an abstract class. When you use
an abstract class or an interface, the first thing that comes to mind is
inheritance. How do you know whether you are correctly using
inheritance? The simple answer is that you do an IS-A test. For
example, a rectangle IS-A shape, but the reverse is not necessarily
true. Take another example: a monkey IS-An animal, but not all
animals are monkeys. Notice that the IS-A test is unidirectional.
In programming, if you inherit class B from class A, you say that B is
the subclass and A is the parent class or base class. But most
importantly, you can say B is a type of A. So, if you derive a Tiger
class or a Dog class from a base class called Animal (or an interface
say IAnimal), you can say that Dog IS-An Animal (or IAnimal) or
Tiger IS-An Animal (or IAnimal). Similarly, a rectangle IS-A
special type of shape. A square IS-A special type of rectangle. So, a
square IS-A shape too.
If you have an inheritance tree, this IS-A test can be applied
anywhere in the tree.
Let us assume that I represent rectangles and shapes using the
Rectangle and Shape classes, respectively. Now when I say
Rectangle IS-A Shape, programmatically I tell that a Rectangle
instance can invoke the methods that a Shape instance can invoke.
But, if needed, a Rectangle class can include some specific
methods that are absent in the Shape class. To invoke these specific
methods, you need to use a Rectangle instance only; since the
Shape class does not include those methods, the Shape instances
cannot call them.
In C#, a parent (or base) class reference can refer to a subclass
object. Since each tiger, dog, or monkey is an animal, you can
introduce a parent type and inherit all these concrete classes from it. I
told you that I am going to use a C# interface now. Following the C#
naming convention, let’s name the supertype as IAnimal.
Here is a code fragment that shows the IAnimal interface. It also
gives you an idea of how to override its Sound() method in the Tiger
class. The Monkey and Dog class can do the same thing.

interface IAnimal
{
void Sound();
}
class Tiger : IAnimal
{
public void Sound()
{
Console.WriteLine("Tigers roar.");
}
}

Programming to a supertype gives you more flexibility. It allows you


to use a reference variable polymorphically. The following code
segment demonstrates such a usage:

IAnimal animal = new Tiger();


animal.Sound();
animal = new Dog();
animal.Sound();
// The remaining code skipped

Better Program
Now I rewrite this program which produces the same output. Let’s take
a look at the following demonstration.

Demonstration 2
Here is demonstration 2. It is a modified version of demonstration 1.

Console.WriteLine("***Sounds of the different


animals.***");

IAnimal animal = new Tiger();


animal.Sound();
animal = new Dog();
animal.Sound();
animal = new Monkey();
animal.Sound();

interface IAnimal
{
void Sound();
}
class Tiger : IAnimal
{
public void Sound()
{
Console.WriteLine("Tigers roar.");
}
}
class Dog : IAnimal
{
public void Sound()
{
Console.WriteLine("Dogs bark.");
}
}
class Monkey : IAnimal
{
public void Sound()
{
Console.WriteLine("Monkeys whoop.");
}
}

Analysis
Have you noticed the difference? This time I used the superclass
reference animal to refer to different derived class objects.
Following this approach, not only do you type less, but you also use
a program that is more flexible and easier to maintain. If needed, now
you can iterate over a list too. For example, you can replace the
following code segment inside Main():

IAnimal animal = new Tiger();


animal.Sound();
animal = new Dog();
animal.Sound();
animal = new Monkey();
animal.Sound();

with the following code:

List<IAnimal> animals = new List<IAnimal>


{
new Tiger(),
new Dog(),
new Monkey()
};

foreach (IAnimal animal in animals)


animal.Sound();

If you run the program again with these changes, you see the same
output.
Notice that in demonstration 1, when a client reads the line
dog.Sound(), they can assume that the Sound() method from the
Dog class will be invoked.
But in demonstration 2, when the client reads the line
animal.Sound(), it is not obvious which subtype of IAnimal will
invoke the Sound(). Why is this important? As a programmer, you do
not provide every possible detail to your clients.
This discussion is not over yet. Here I have used one of the simplest
forms of polymorphism. In this case, a question may come to mind: we
know a supertype reference can refer to a subtype object in C#. So,
when I use the following lines:

IAnimal animal = new Tiger();


animal.Sound();

you can surely predict that the Sound() method of Tiger class
will be used. So, it appears that you know the output in advance and
you doubt the concept of polymorphism. If this is the case, let us further
dig into this.
Let us assume that you create a subtype based on some runtime
random number generator (or user input). In this case, you cannot
predict the output in advance. For example, see the following lines of
code:

IAnimal animal = AnimalProducer.GetAnimal();


animal.Sound();

What is the difference? Anyone who sees this code segment can
assume that GetAnimal() of the AnimalProducer class returns an
animal that can make some sound. How can you achieve this? It is
pretty simple: let me rewrite the program. Notice the changes in bold:

Console.WriteLine("***Sounds of the different


animals.***");
IAnimal animal = AnimalProducer.GetAnimal();
animal.Sound();
animal = AnimalProducer.GetAnimal();
animal.Sound();
animal = AnimalProducer.GetAnimal();
animal.Sound();
interface IAnimal
{
void Sound();
}
class Tiger : IAnimal
{
public void Sound()
{
Console.WriteLine("Tigers roar.");
}
}
class Dog : IAnimal
{
public void Sound()
{
Console.WriteLine("Dogs bark.");
}
}
class Monkey : IAnimal
{
public void Sound()
{
Console.WriteLine("Monkeys whoop.");
}
}

class AnimalProducer
{
internal static IAnimal GetAnimal()
{
IAnimal animal;
Random random = new Random();
// Get a number between 0 and 3(exclusive)
int temp = random.Next(0, 3);

if (temp == 0)
{
animal = new Tiger();
}
else if (temp == 1)
{
animal = new Dog();
}
else
{
animal = new Monkey();
}
return animal;
}
}
Run this application now and notice the output. Here is the sample
output that I got on the various runs:

First Run:

***Sounds of the different animals.***


Monkeys whoop.
Dogs bark.
Monkeys whoop.

Second Run:

***Sounds of the different animals.***


Dogs bark.
Dogs bark.
Tigers roar.

Third Run:

***Sounds of the different animals.***


Tigers roar.
Monkeys whoop.
Dogs bark.
It is now clear that no one can predict the output of this program in
advance. You can see the effective use of polymorphism in this example.

POINTS TO REMEMBER
If you like to shorten this code, instead of using the if-else chain,
you can use the switch expression as follows:

animal =
temp switch
{
0 => new Tiger(),
1 => new Dog(),
_ => new Monkey()
};

One more point: you can use a simplified new expression again.
For example, the line Random random = new Random(); can
be shortened if you use Random random = new();. When you
download the source code from the Apress website, refer to the
folder Demo3_Polymorphism inside Chapter1 to see the
complete program.

Now I’ll show you some code that helps you understand and use
polymorphic code in an alternative way. You can replace
animal.Sound(); with the following code:

AnimalProducer.MakeSound(animal);

MakeSound() is defined inside the AnimalProducer class as


follows:

internal static void MakeSound(IAnimal animal)


{
animal.Sound();
}
Why am I showing this to you? Following this approach, you can
pass a supertype reference to this method to invoke the appropriate
subtype method. This also gives you flexibility and helps you write
better, more readable code. Here is an alternative version of the
program that we have just discussed:

Console.WriteLine("***Sounds of the different


animals.***");
IAnimal animal = AnimalProducer.GetAnimal();
AnimalProducer.MakeSound(animal);
animal = AnimalProducer.GetAnimal();
AnimalProducer.MakeSound(animal);
animal = AnimalProducer.GetAnimal();
AnimalProducer.MakeSound(animal);

interface IAnimal
{
void Sound();
}
class Tiger : IAnimal
{
public void Sound()
{
Console.WriteLine("Tigers roar.");
}
}
class Dog : IAnimal
{
public void Sound()
{
Console.WriteLine("Dogs bark.");
}
}
class Monkey : IAnimal
{
public void Sound()
{
Console.WriteLine("Monkeys whoop.");
}
}

class AnimalProducer
{
internal static IAnimal GetAnimal()
{
IAnimal animal;
Random random = new Random();
// Get a number between 0 and 3(exclusive)
int temp = random.Next(0, 3);

animal =
temp switch
{
0 => new Tiger(),
1 => new Dog(),
_ => new Monkey()
};

return animal;
}
internal static void MakeSound(IAnimal animal)
{
animal.Sound();
}
}

Note You should not assume that the GetAnimal() and


MakeSound(...) methods need to be static only. You can use them
as instance methods too. When you download the source code from
the Apress website, refer to the folder Demo4_Polymorphism
inside Chapter1 to see this modified program.

Useful Notes
Before I finish this chapter, let me point out some important
information for your immediate reference.
C# types including the user-defined types are polymorphic because
they inherit from Object.
To implement a polymorphic behavior, I started with an interface. I
could achieve the same result using an abstract class. In this case, you’d
use the abstract and override keywords in the respective code
segments. Here is a sample:

abstract class Animal


{
public abstract void Sound();
}
class Tiger : Animal
{
public override void Sound()
{
Console.WriteLine("Tigers roar.");
}
}

But when you use a concrete parent class and want its derived
classes to redefine its method(s), you see the use of virtual
keywords in the parent class. Here is a sample:

class Animal
{
public virtual void Sound()
{
Console.WriteLine("I make sounds.");
}
}
class Tiger : Animal
{
public override void Sound()
{
Console.WriteLine("Tigers roar.");
}
}
In short, a base class can define (or implement) virtual methods,
and if needed, the derived classes override them as per their needs. As a
result, at runtime, when client code calls the method, the common
language runtime (CLR) can invoke the appropriate method based on
the runtime type of the object. These are the key things to understand
in the polymorphic code.

Note C# primarily supports OOP. But being hybrid in nature, it can


support functional programming (FP) too. FP prefers immutability
and pure functions. A function is pure if it returns the same value for
the same input. Otherwise, it is an impure function. So, from a FP
developer’s point of view, you may consider the dynamic behavior of
a method as a problem instead of an advantage. But I remind you
that our focus is on OOP in this book, but not on FP. So, you should
not be confused.

In this chapter, I discussed the code examples using C# interfaces. So,


I’d like to point out one important change that came in C# 11. Consider
the following code:

Console.WriteLine("Testing a C#11 feature");


public interface ISample
{
static abstract void ShowInterfaceName();
}

If you run this code in C# 10, you’ll see the compile-time error. Here
is a sample:

CS8703 The modifier 'abstract' is not valid for


this item in C# 10.0. Please use language version
'preview' or greater.

This message is self-explanatory. So, you need to understand that


this feature was planned for C# 11. At the same time, you also need to
remember that only interface members that aren’t fields can be
static abstract. So, if you write something like the following:

public interface ISample


{
static abstract int SomeFlag; // ERROR CS0681
}
you’ll see the following error: CS0681 The modifier
'abstract' is not valid on fields. Try using a
property instead.
In short, you can refer to the following code segment and keep the
supporting comments in mind when you use a C# interface in your
program:

public interface ISample


{
//static abstract int SomeFlag1; // ERROR
CS0681
static int SomeFlag2=1; // OK, but warning
message
// (CA 2211)
// Interfaces cannot contain instance fields
int _someFlag3; // ERROR CS0525
const int SomeFlag3 = 3; // OK
static abstract void ShowInterfaceName1(); //
OK in C#11
void ShowInterfaceName2(); // OK
}

Summary
To implement polymorphic behavior, I started with an interface. I could
achieve the same effect using an abstract class. There are situations
when an interface is a better choice over an abstract class, and vice
versa. You will see a discussion about this in Chapter 2.
When you code to a parent type (it can be an interface, an abstract
class, or simply a parent class), the code can work with any new classes
implementing the interface. This helps you to adjust to lots of new
changes in the future, and you can adopt those requirements easily.
This is the power of polymorphism. But if you use only concrete classes
in your program, it is likely that you may need to change your existing
code in the future such as when you add a new concrete class. This
approach does not follow the Open/Closed principle, which says your
code should be open for extension but closed for modification.
I have shown you the advantages of polymorphism. But it’s not
always easy to write polymorphic code, and you need to be careful
when you use it. You’ll get a better idea about this when I discuss SOLID
principles in Chapter 4.
Everything in this chapter may not be new to you, but I believe that
you have a better idea about polymorphism now. Before you move on to
the next chapters, let me make sure that we agree on the following
points.
When you write the following:

Tiger tiger = new Tiger();


tiger.Sound();

you are programming to concrete implementation.


When you write the following:

IAnimal animal = new Tiger();


animal.Sound();

you are programming to a supertype. It is often referred to as


programming to an interface.

Note When we say programming to an interface, it does not


necessarily mean that you use a C# interface only. It can be an
abstract class or a parent/base class too.

You can follow a better approach when you write something like this:

IAnimal animal = AnimalProducer.GetAnimal();


animal.Sound();
Another Random Scribd Document
with Unrelated Content
They started again toward the lighthouse.
They reached the cottage connected with the lighthouse. The door
was open, but all was dark inside. For a moment the boys hesitated.
Afterwards Bob and Frank admitted that they were thinking of the
same thing Sammy was—that perhaps there was a trap, and that the
wreckers were waiting for them.
Finally Frank called:
"Hello, Mr. Floyd! Are you there? What's the matter? Why isn't the
light going?"
At first only a groaning voice answered them, and then they heard
the stronger tones of the light-keeper crying out:
"Oh, thank Providence someone has come! Quick, boys, you're just
in time! Light the lamp! Never mind me! Light the lantern!"
"Are you hurt?" asked Bob.
"Did the wreckers attack you?" cried Sammy.
"Wreckers! Good land, no!" shouted the light-keeper. "I fell down
stairs, and I guess my leg is broken. And when I fell I hit against the
lever that puts out the lantern, and that made it all dark. And I've
been lying here ever since, calling for help, but no one heard me. I
didn't know what to do, for I can't seem to move.
"But you're just in time, boys. Come in, and I'll tell you how to light
the lantern. Hurry, or some ship may go on the rocks! Wreckers?
Good land, what made you think of them?"
"Fooled again!" murmured Sammy Brown, as he and his companions
entered the cottage.
CHAPTER VII
ON THE TRAIL

"Where are you?" called Bob to the light-keeper, as the boys went
into the living room. All was so dark they could see nothing.
"Right here, at the foot of the stairs," answered Mr. Floyd. "I haven't
been able to move since my fall."
"Are you badly hurt?" asked Frank.
"I don't know, but I hope not. Never mind about me, though. You
must set the lantern going, for I can't do it. That is most important. I
have never yet let it go out—this is the first time; but I could not
help that."
"Wait, I'll strike a match," said Sammy. "Then we can see what we
are doing."
The tiny glow illuminated the room, and the boys could see the light-
keeper huddled in a heap at the foot of the stairs that led to the
tower, at the top of which was the big lantern.
"There's a lamp on the table," said the aged man, pointing to it.
"Light that, and then go up to the lantern. Do you think you can light
it?"
"I guess so," answered Bob. "Your daughter showed us how it was
done."
"That's good. She little knew how soon you might have to do it. But
if you think you can't do it, you must go for help. My wife and
daughter have gone to visit relations, and will be away all night, but
you can get some of the fishermen; they will know how to light the
lantern."
"Oh, I'm sure we can do it!" exclaimed Frank. "Lucy showed us just
how it was done."
"I'm thankful for that," went on the light-keeper. "Now, boys, don't
bother with me!" he went on, as they advanced toward him. "Just
get up aloft and set the lantern going. You see I have an
arrangement so I can put it out from down here, without going all
the way up. That's to save me climbing the stairs in the morning.
"Well, I was coming down, from having trimmed it, a little while ago,
when I slipped. I put out my hand to save myself, and, by mistake I
grabbed hold of the wire I had rigged up to put out the light. It put
it out, all right, and here I've lain ever since, not knowing what to
do. Oh, it was terrible!
"I couldn't tell when anyone would come, being all alone as I was. I
called and called, but no one heard me."
The boys thought of the strange figure of the old man, with the
lantern, running away, and they wondered if he had heard and had
not heeded.
"I couldn't tell what moment some ship might go on the rocks,"
continued the light-keeper. "For the sailors, not seeing the light,
might get off their course. I was glad there was no storm, for that
would have made it much worse.
"But never mind about that now. You're here, thank Providence, and
you can start the light going before it's too late."
"Come on!" cried Bob, and with a lantern which they had found and
set aglow, to light them up the dark stairs of the tower, the three
boys ascended. First, however, they had in spite of his protests,
made Mr. Floyd more comfortable, by putting a pillow under his
head, and straightening him out. They did not want to move him too
much for fear one of his legs might be broken.
Up into the lantern tower the lads went. Then with hands that
trembled a little, they ignited the big wicks, first having raised the
extinguishers that Mr. Floyd had accidentally pulled down over them
in his fall.
The machinery, that made the glass prisms turn, was still in motion,
not having been stopped since it was set going early in the evening,
so with this the boys had nothing to do. As soon as they had lighted
the lantern, the welcome flash went sparkling out over the waters of
the cove, to warn captains off the dangerous rocks.
"And now we'd better get down and help Mr. Floyd," said Bob, when
they had made sure that the lantern was going all right, and would
not smoke. "I guess we'd better get a doctor."
"I think so, too," added Frank. "Too bad about your wreckers,
Sammy," he went on, with a laugh.
"Aw, quit your fooling!" exclaimed the lad who sometimes let his
imagination run away with him. "Something like that might have
happened, anyhow."
"Yes, it might," admitted Bob. "But it didn't."
"I'm sure there's something queer about that man with the lantern
we saw," continued Sammy. "He's after that pirate gold, I'm
positive."
"Well, he does act queer," admitted Frank. "We can have a try for his
secret, as soon as we get this lighthouse business fixed up."
"We do seem to run into the queerest things," remarked Bob. "If it
isn't one thing it's another."
"I like it!" exclaimed Sammy, who was always on the lookout for
something to happen. That it seldom did take place never
discouraged him.
"Well, is everything all right?" asked Mr. Floyd, as the boys came
down stairs.
"Yes," answered Frank. "The lantern is going all right."
"And now we'll look after you," went on Bob. "Are you badly hurt?"
"I can't tell. Best have the doctor look me over, I guess. I'm more
comfortable since you boys came. It isn't so much for myself that I
care, but the light depends on me. Uncle Sam trusts me to keep it
going, no matter what happens, and I've got to do it. If I get
knocked out someone else will have to look after it."
"We'll go for a doctor," said Sammy.
"Yes, and maybe we'd better go tell your wife and daughter what
has happened," suggested Frank. "They'll want to be with you."
"I guess that would be a good plan," agreed the light-keeper. "They
ought to be here, for I'm afraid I won't be able to get up and down
stairs much for a while."
While the boys were planning who should stay at the lighthouse, and
who should go for the physician, hurried footsteps were heard
outside, and a number of fishermen and sailors came crowding in.
They were much surprised at what they saw.
"Look here!" exclaimed one big lobsterman, "what's all this here
about, John Floyd?"
"We saw the light out," added another, "and we made up a
committee to come and investigate."
"Thinking there was trouble," put in a third.
"Yes, thinking there was trouble," agreed the second speaker. "Has
these boys been up to any tricks?" and he looked at the three chums
suspiciously.
"Indeed they have not!" exclaimed Mr. Floyd, earnestly. "If it hadn't
been for these boys the light would be out yet. And if you fellows
had come a little quicker, instead of waiting to form a committee, it
might have been better."
"Well, we didn't notice, until a few minutes ago, that the light wasn't
flashin'," said a clam dealer. "You know you can't see it very well
from shore. But Ted Knowlton was out in his boat after eels, and he
noticed right away that there wasn't any flash. So he rowed in as
fast as he could and told us."
"But the boys got here first, and I'm mighty thankful to 'em!"
exclaimed Mr. Floyd. "Howsomever, now that you men are here, you
might lift me up on that lounge, and then get the doctor."
"And we'll go for your wife!" said Bob. "We can do that, if you'll tell
us where she is."
The light-keeper gave them the directions for finding Mrs. Floyd and
Lucy, who had gone to a relative about two miles away. The boys
left, after waiting to learn that, in the opinion of the fishermen, Mr.
Floyd's leg was only sprained, and not broken.
Stopping at Barnacle Cottage to tell Mrs. Bouncer what had
happened, and where they were going, Bob and his chums hurried
to where Mrs. Floyd was staying. She and Lucy were at first much
alarmed at the news, but were soon told that nothing serious had
happened. They at once returned to the lighthouse with the boys.
The keeper was feeling much better now, and the doctor had
bandaged his leg. He would be unable to walk around for several
days, it was said, and some of the fishermen agreed to come and
help with the heavier work about the lighthouse until Mr. Floyd was
able to be about.
"Well, that's over," remarked Bob, as he and his chums went back to
Barnacle Cottage again. "Quite some little excitement for a while;
eh?"
"That's right," agreed Frank.
"But it isn't over yet," said Sammy Brown.
"Why not?" asked Bob. "That is unless you're going to have a look
for the wreckers, Sammy," and he nudged Frank, to show that he
was only joking.
"Humph! Wreckers, yes!" exclaimed Sammy. "If there had happened
to be any you fellows would have been glad enough to want part of
the credit. But as long as there wasn't, you can only poke fun at
me."
"Oh, we didn't mean anything!" said Bob, quickly. "I was only joking,
Sammy. Go ahead; tell us what you mean by it not being over yet."
"I mean we haven't found out who that queer old man is with the
lantern," said Sammy. "I'm sure there's some mystery about him."
"Pirate gold; do you mean?" asked Frank.
"Well, I'm not going to say that again, and have you fellows laugh at
me!" exclaimed the lad who did so much sensational thinking. "But
that man is after something around here."
"I agree on that," said Frank.
"But what is it?" asked Bob.
"That's what we've got to find out!" declared Sammy, promptly.
"Fellows, what's the matter with us trailing that queer man, until we
find out all about him."
"Trail him?" questioned Bob.
"Yes," went on Sammy. "We'll try to find where he lives, and what he
is after."
"And why he goes about nights with a lantern," added Frank. He and
Bob were now as much interested as was Sammy, and they were
eager to help their chum clear up the mystery.
Getting to the cottage, they found company had come to call on Mr.
and Mrs. Bouncer, and before the boys went to bed they had to tell
all about their adventure at the lighthouse.
"My, you boys certainly do things!" exclaimed one of the callers.
"Yes, too much, sometimes," said Mrs. Bouncer, with a sigh, as she
looked at her son and his chums. "I never know what they'll be up to
next. That's one reason I rather dreaded coming here. I didn't so
much mind it at home, for though they were out on Rainbow Lake
much of the time, there was a limit to that water. But here, so near
the big ocean,—I don't know. I'm always afraid they'll be carried out
to sea!" and she shivered slightly, as if from some unknown fear.
"Carried out to sea!" exclaimed Bob. "How could we be? We never
go as far as the inlet."
"And I hope you never will!" exclaimed his mother.
The boys told more in detail of their doings at the lighthouse and
then were sent off to bed, for the hour was growing late. They only
made a mention of the strange man with the lantern, whom they
had passed in the darkness, and they did not tell of their intention to
get on his trail, and try to find out who he was and what he was
after. They thought that, had they spoken of him, permission to seek
after his secret might not be given.
"Well, what's on the program this morning?" asked Bob, after
breakfast one day.
"Me for a swim, as soon as it gets a little warmer," decided Frank, for
the morning was a bit chilly.
"I'm with you!" agreed Bob.
"Can't you boys get a few crabs first?" asked Mrs. Bouncer. "I'd like
some to make a salad. The tide is right now; isn't it?"
"Yes, it's coming in, and they always bite best on the incoming tide,"
replied Bob, who had learned that from an old fisherman. "What do
you say, fellows; shall we go crabbing?"
"Sure," agreed his chums. "We can swim later."
Accordingly with crab nets, pieces of meat tied on strings for bait,
and a deep basket in which to keep the catch, the boys set off in
their boat, for the other side of the cove, since there the larger crabs
could be gotten.
They had good luck, and were busy pulling in some large ones, with
big blue claws, when Bob suddenly called to his companions:
"Look, there he is now!"
They glanced up, to see, some distance back from the beach, in a
clump of scrub evergreen trees, a man digging.
"There's our man of mystery!" exclaimed Sammy. "Let's trail him,
fellows!"
CHAPTER VIII
DRIVEN BACK

Sammy's two chums did not answer for a minute. They looked at
each other, and then Frank exclaimed:
"I've got a bite, and a big one, too. Pass that net down here!"
For a moment the prospect of catching another crab was greater
even than the chance of finding out something about the strange
man. Bob handed his companion the net, and Frank cautiously
began pulling up on the cord to which was fastened the chunk of
meat-bait. With his other hand he held the net ready to plunge into
the water, and scoop up his prize.
"There he is!" cried Bob, whose bait was not then being taken. "Get
him, Frank!"
"I will. Don't get excited and rock the boat. I'll have him in a
minute!"
"There!" exclaimed Sammy, whose attention was also taken away
from the man for the moment. "Net him!"
Frank plunged the net into the water, trying to get it under the crab,
which was clinging to the meat with its claws. But the boy was not
quite quick enough, or else he hit the crab with the iron ring of the
net, for the creature suddenly let go, and with a quick motion of his
broad, swimming flippers went scurrying off into the depths again.
"Oh, he got away!" cried Bob, in disappointed tones.
"You weren't quite quick enough," spoke Sammy.
"I was so! You jiggled my arm, and made the net hit him!" exclaimed
Frank. "It was the biggest one I had, too; a yellow fellow, full of
meat!" and he gazed reproachfully at Sammy.
"I did not jiggle your arm!" returned Sammy.
"You did so!"
"I did not!"
"Fellows, if we're going to trail that mysterious man, let's do it, and
not scrap," suggested Bob. This was as near to a quarrel as any of
the chums ever got. Frank's little burst of temper was soon over.
"Well, we've got enough crabs, anyhow," he said, looking into the
basket where they were kept, covered with seaweed, so the sun
would not make them die. For crabs are only good when cooked
alive, or soon after they have died. Otherwise they are very likely to
be poisonous.
"Yes, we have a good mess," agreed Sammy. "I didn't mean to jiggle
your arm, if I did, Frank," he went on. "I'll give you one of my crabs
to pay for it, if you say so."
"You will not! They all go in the same kettle, anyhow. Say, Bob," he
went on, "what's the matter with having a clam roast out on the
beach some night?"
"Sure we can," said Bob. "We'll build a fire, roast clams and boil
crabs, and have some of the other fellows over. That'll be fun!"
"It sure will," agreed Sammy. "But say, fellows, what about him?"
and he nodded in the direction of the old man in the clump of
evergreen trees. He was still digging away, seemingly paying no
attention to anything, or anyone, around him. "Are we going to
follow him, or not?"
"We can't follow him, when he isn't going anywhere," observed Bob.
"No, but he may start off at any time," said Sammy. "We could tell
where he lives, and then we could find out something about him. As
it is now we can't even tell who he is, and there are a lot of men
who look like him around Lighthouse Cove."
"Well, what's your plan?" asked Frank, carefully pulling up his crab
line, in the hope that the big fellow had again taken the meat. One
was there, but it was so small that he shook it off, not wanting to
net it.
"I say let's row close over to where he is," suggested Sammy. "Then,
when he starts off, we can go ashore and follow him."
"Maybe he's got a boat hidden somewhere on shore," said Bob.
"Let's take a look."
The boys scanned the beach, but could see nothing of another craft.
Meanwhile, the old man in the clump of evergreens continued to dig
away. He paid no attention to the boys.
"Tell you what it is," said Sammy, at length, "we've got to play foxy
now. We don't want any more of that hermit business."
"What do you mean?" asked Frank.
"Well, you know what happened when we followed that old man on
Pine Island. He pushed us over a cliff into a snow bank."
"Ha! Ha!" laughed Bob.
"What's the matter?" demanded Sammy. "I don't see anything to
laugh at."
"You don't? Well, there's no snow bank, for one thing."
"Well, you now what I mean," said Sammy. "He might make trouble
for us. I say we'd better be careful."
"That's what I say, too," agreed Frank. "Now the best way, I think,
will be to let our boat drift. We can pretend we are crabbing, but we
can pull up the anchor, and the tide will take us nearly to where he
is digging. He can't say anything, if we do that, for we have a right
to drift."
"Yes, and then we can see if he has a boat," added Sammy. "I guess
that's the best plan. But what about these crabs, Bob? Won't your
mother want them for dinner?"
"No, she's going to make them into a salad for supper. We fellows
will have to cook 'em, and pick 'em out of the shells, I expect. There
will be time enough when we get in. Let's trail this old man now."
Accordingly the small pronged anchor, that held the boat from
drifting while the crabbing was going on, was hauled up, and put in
the bow. Then, while pretending to be busy with their crab lines, the
boys let their craft drift with the tide over toward the shore.
The old man was still digging away, but he had moved his position
and was now deeper in the clump of trees.
"I'm sure he's after pirate gold!" exclaimed Sammy, in a whisper, for
he knew sounds carry very distinctly over water, and he did not want
the digging man to hear him.
"He's after something, right enough," agreed Frank. "What it is we
can find out later."
"There's a boat, anyhow," put in Bob, pointing to one partly hidden
under some brush and seaweed not far from the shore.
"That's right!" cried Sammy. "That shows he came from some other
part of the Cove. We'll follow him!"
But, for the present, the man did not show any sign of being about
to leave the clump of trees. He was digging away, paying no
attention to anything around him, save to glance up now and then.
If he saw the boys, as he must have done, he gave no sign.
Bob and his two chums, now that they were where they wanted to
get, again threw the anchor overboard, and resumed their crabbing.
But luck was not so good here, the boat being too near shore.
However, they wanted an excuse for remaining near the man, and
this gave them one.
"Here he comes!" suddenly exclaimed Sammy, as he wound up his
crab line for future use. "Get ready now, boys."
The others looked up. Coming down toward the beach was the
strange old man. Over his shoulder were a pick and a shovel, and in
one hand he carried a square wooden box, with a strap for a handle.
"What do you s'pose he has that for?" asked Frank.
"To put the gold in," said Sammy, promptly, "or else that holds the
map, and directions for finding the treasure."
"The directions can't be very good," spoke Bob, "for he's been
digging in lots of places, far apart, too. I think that gold business is
all bosh!"
"Hush! He'll hear you!" cautioned Frank, for the old man had looked
sharply in the direction of the boys.
"I don't care," spoke Bob. "This is a free country."
The boys had again pulled up anchor, and taken to the oars. They
were pulling out from shore now. The old man went to where the
other boat was partly hidden, and slid it down over the sand to the
water. Then, putting in his tools and the box, he entered the craft
himself, and began to row up toward the head of the Cove.
"Come on!" said Sammy, to his chums. "We've got to follow."
"Do you think we'd better?" asked Frank.
"Sure; why not?" was the answer. "We've got to find out about him;
haven't we?"
To this the others had no objection. They were as interested, now,
as Sammy was in solving the mystery. So, when the old man rowed
off, more quickly than the boys supposed one of his age could do,
they followed, but at a distance.
The day was a fine one, there was only a little wind, and the tide
was with them.
"But it won't be so easy rowing back against the current," said Bob.
"Oh, don't worry," advised Sammy, eager to find where the strange
man lived.
They did not have long to wait. A little later, after turning a point of
land, the man rowed up to a small dock, in front of a small house,
and, tieing his boat there, got out and went up the slope.
"Come on!" called Sammy, a moment later. "Let's go ashore."
"Maybe he won't like it," suggested Frank.
"Oh, he won't care," was the answer. "He's seen us following him,
and he didn't say anything. Come on."
Rather against their will, Frank and Bob followed Sammy. He sent
the boat up on the beach, and threw out the anchor in the sand to
hold the craft against the tide. Then, followed by his chums, he
approached the small cottage.
But if the boys imagined the aged man was going to witness their
approach in silence they were disappointed. He reached his porch,
and putting his pick, shovel and box down there, turned and hurried
to meet Sammy and his chums.
"Did you boys want to see me?" he asked, and his voice was rather
stern. He did not speak like the fishermen of the cove, but more, as
Sammy said afterward, like Mr. Tetlow, the school principal, when he
was angry.
"We—we just wanted to see," began Sammy, uncertain whether or
not to tell his suspicions about the pirate gold, and to be allowed a
share in the secret.
"Now look here, boys!" interrupted the aged man, sternly. "I don't
want to be harsh toward you, but you must get away from here. I
said nothing when you followed me, not thinking you would land on
my property. This is private land, and there has been a 'no trespass'
sign up, but it has fallen down. I will put it up again. I want no
strangers around here.
"My neighbors around me know this, and do not bother me. It is
probably because you are strangers that you have come here. Now I
will not have it. Later on I may be glad to see you, but now I must
ask you to leave!"
He stood looking at the boys sternly. They had been ordered away,
and there was nothing for them to do but to obey.
CHAPTER IX
IN THE BOAT

"Well, we didn't find out anything."


"No, we had all our trouble for our pains."
"But we know where he lives—that's something we didn't know
before."
This last was said by Sammy Brown. His two chums, Bob and Frank,
had made the other remarks. The boys were rowing toward Barnacle
Cottage, having been practically driven away from the place to which
they had trailed the strange old man. His manner had been severe
and stern, yet the boys knew he had right and justice on his side.
"We couldn't do anything but go," said Bob. "He could have had us
arrested for trespass if we didn't."
"That's right," admitted Frank.
"Well, I didn't think he'd be quite so sharp," said Sammy, after a
moment. "I thought he was a sort of simple old man, like some of
the fishermen around here."
"But he's a lot different," spoke Frank. "Did you see how his eyes
snapped, when he told us to get away?"
"I should say I did!" answered Bob. "He was real angry."
"But he spoke good enough to us," said Sammy. "I s'pose it was a
crazy idea to go there in broad daylight, when he was at home. Next
time I'll go at night, or when he's away."
"What! Are you going again?" cried Bob.
"I should say I am! I'm going to get at the bottom of this yet!"
declared Sammy.
"And when you do get to the bottom, it will fall out, just as it always
does, and you'll have all your trouble for nothing," said Frank, with a
laugh.
"Will I? Well, I'll see," answered Sammy, confidently. "I'm sure that
man is trying to hide something."
"I thought he was trying to find something, from what you said at
first—the pirates' gold!" laughed Bob.
"Oh, you know what I mean," returned Sammy. "Quit your fooling!"
They rowed on in silence for a few minutes, and suddenly Frank,
who was in the stern, gave a loud yell.
"What's the matter?" asked Bob. "See a shark?"
"No, but a crab's got my toe! Look out! They're getting out of the
basket!"
He jumped up on the stern seat, holding out one bare foot—to the
big toe of which a large crab was clinging with his strong claw.
"Take him off!" cried Frank, dancing about.
"Take him off!" cried Frank.
"Take him off yourself!" exclaimed Sammy. "Think we want to get
nipped?"
"Look out! You'll upset the boat!" cautioned Bob. "Keep still; can't
you?"
"No, I can't, and I guess you couldn't, either, with a big blue-claw
crab nipping you!" cried Frank. "Ouch! Get him off; can't you!"
He was trying to do this for himself, but the crab, that was one of
the biggest caught, had one claw free, and every time Frank reached
out his hand to grasp the creature, and pull it from his toe, the crab
would open his other claw, and wave it around threateningly. So
Frank was a bit cautious about taking hold of the creature.
"Look out! The others are getting out!" cried Sammy, as he glanced
at the basket of crabs.
It was only too true. The boys had paid no attention to their catch
for some time, and the crabs had pushed their way up from beneath
the seaweed, and were crawling over the edge.
"Clap something on top of the basket!" cried Sammy. "Hand me that
board, Frank."
"Can't! I've got troubles of my own! Ouch, let go, can't you!" he
cried to the crab, which did not seem to want to do this.
"Wow! One's got me, too!" exclaimed Bob, turning quickly about.
"Smash him against the side of the boat!" advised Sammy to Frank,
and, seeing this was good advice, the boy did so.
Crack went the hard crab against the gunwale, and the claw by
which it had been clinging to Frank's toe came off. Crabs claws often
come loose and new ones grow on again. So the creature was not
much hurt.
"Whew! That's better!" gasped Frank, as he opened the nippers of
the claw that still clung to his toe, in spite of the fact that it was
severed from the body of the crab.
"Let go, can't you!" cried Bob, to the crab nipping him.
"Try Frank's trick," advised Sammy.
Bob did so, but the result was not exactly what was looked for.
The boy hit the crab, that had hold of his hand, such a blow against
the side of the boat, that, losing his balance, Bob leaned too far
over.
"Look out! You'll upset us!" cried Frank, who was nursing his nipped
toe.
It was too late. The boat tilted, and, aided by the tide and the frantic
efforts of the boys to prevent it, over went the craft, spilling out the
three chums, crabs, and all. Then such confusion as there was!
Gasping and choking, from their sudden and unexpected bath, the
boys came to the surface of the water. They were all good
swimmers, and, fortunately had on only thin shirts and light trousers
—almost bathing suits, in fact.
"Grab the oars!" called Sammy.
"And don't let the boat get away!" added Frank.
"There go the crabs!" shouted Bob, as he saw the basket containing
their catch sail away on the tide, the crabs scrambling out, rejoicing
in their unexpected liberty.
"Too late! We can't save 'em—have to catch some more!" called Bob.
"Get the oars and the boat!"
"Going to right the boat?" asked Frank, as he swam to get a drifting
oar.
"No, it's too much work here. Let's swim with her down to the
lighthouse dock, pull her out there, and dump the water out. Then
we can row home."
It was good advice; and the best and easiest thing to do. With the
recovered oars, and their crab nets, the boys swam along toward
shore, pushing the boat ahead of them. The water was not over
their heads, and soon they could wade.

You might also like