Simple and Efficient Programming with C# : Skills to Build Applications with Visual Studio and .NET 2nd Edition Vaskaran Sarcar download
Simple and Efficient Programming with C# : Skills to Build Applications with Visual Studio and .NET 2nd Edition Vaskaran Sarcar download
https://ebookmeta.com/product/simple-and-efficient-programming-
with-c-skills-to-build-applications-with-visual-studio-and-
net-1st-edition-vaskaran-sarcar-2/
https://ebookmeta.com/product/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-vaskaran-sarcar/
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/
https://ebookmeta.com/product/ollie-goes-the-distance-all-about-
electric-cars-claire-winslow/
https://ebookmeta.com/product/methods-for-the-analysis-of-
asymmetric-proximity-data-giuseppe-bove-akinori-okada-donatella-
vicari/
https://ebookmeta.com/product/dieting-overweight-and-obesity-
self-regulation-in-a-food-rich-environment-2nd-edition-wolfgang-
stroebe/
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
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 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.
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?
Figure I-1 Download link for Visual Studio 2022 and Visual Studio Code
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
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:
Output
Here is the output:
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.");
}
}
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.
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():
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:
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:
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:
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:
Second Run:
Third Run:
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);
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();
}
}
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:
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.
If you run this code in C# 10, you’ll see the compile-time error. Here
is a sample:
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:
You can follow a better approach when you write something like this:
"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