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

Objectoriented Programming With Visual Basicnet Michael Mcmillan download

The document is a comprehensive guide to object-oriented programming using Visual Basic.NET, authored by Michael McMillan. It covers fundamental and advanced OOP concepts, including class design, inheritance, interfaces, and design patterns, along with practical examples for various application types. The book is intended for advanced Visual Basic programmers and serves as a secondary text for learning VB.NET's OOP features.

Uploaded by

damlerdepali
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)
20 views

Objectoriented Programming With Visual Basicnet Michael Mcmillan download

The document is a comprehensive guide to object-oriented programming using Visual Basic.NET, authored by Michael McMillan. It covers fundamental and advanced OOP concepts, including class design, inheritance, interfaces, and design patterns, along with practical examples for various application types. The book is intended for advanced Visual Basic programmers and serves as a secondary text for learning VB.NET's OOP features.

Uploaded by

damlerdepali
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/ 82

Objectoriented Programming With Visual Basicnet

Michael Mcmillan download

https://ebookbell.com/product/objectoriented-programming-with-
visual-basicnet-michael-mcmillan-2004060

Explore and download more ebooks at ebookbell.com


OBJECT-ORIENTED PROGRAMMING
WITH VISUAL BASIC.NET
Michael McMillan provides a complete presentation of the object-oriented
features of the Visual Basic.NET language for advanced Visual Basic pro-
grammers. Beginning with an introduction to abstract data types and their
initial implementation using structures, he explains standard object-oriented
programming (OOP) topics including class design, inheritance, access mod-
ifiers and scoping issues, abstract classes, design and implemention of inter-
faces and design patterns, and refactoring in Visual Basic.NET. More advanced
OOP topics are included as well, such as reflection, object persistence, and
serialization.
To tie everything together, McMillan demonstrates sound OOP design and
implementation principles through practical examples of standard Windows
applications, database applications using ADO.NET, Web-based applications
using ASP.NET, and Windows service applications.

Michael McMillan is Instructor of Computer Information Systems at Pulaski


Technical College. With more than twenty years of experience in the computer
industry, he has written numerous articles for trade journals such as Software
Development and Windows NT Systems. He is author of Perl from the Ground
Up and coauthor of several books including Programming and Problem Solving
with Visual Basic.NET and A Laboratory Course in Visual Basic.NET.
OBJECT-ORIENTED
PROGRAMMING WITH
VISUAL BASIC.NET
MICHAEL MCMILLAN
Pulaski Technical College, North Little Rock, Arkansas
PUBLISHED BY THE PRESS SYNDICATE OF THE UNIVERSITY OF CAMBRIDGE
The Pitt Building, Trumpington Street, Cambridge, United Kingdom

CAMBRIDGE UNIVERSITY PRESS


The Edinburgh Building, Cambridge CB2 2RU, UK
40 West 20th Street, New York, NY 10011-4211, USA
477 Williamstown Road, Port Melbourne, VIC 3207, Australia
Ruiz de Alarcón 13, 28014 Madrid, Spain
Dock House, The Waterfront, Cape Town 8001, South Africa
http://www.cambridge.org


C Michael McMillan 2004

This book is in copyright. Subject to statutory exception


and to the provisions of relevant collective licensing agreements,
no reproduction of any part may take place without
the written permission of Cambridge University Press.

First published 2004

Printed in the United States of America

Typefaces ITC Berkeley Oldstyle 11/13.5 pt. and ITC Franklin Gothic System LATEX 2ε [TB]

A catalog record for this book is available from the British Library.

Library of Congress Cataloging in Publication Data


McMillan, Michael, 1957–
Object-oriented programming with Visual Basic.Net / Michael McMillan
p. cm.
Includes bibliographical references and index.
ISBN 0-521-53983-8 (pb.)
1. Object-oriented programming (Computer science) 2. Microsoft Visual BASIC.
3. BASIC (Computer program language) 4. Microsoft.NET. I. Title
QA76.64.M389 2004
005.1 17 – dc22 2003055949

ISBN 0 521 53983 8 paperback


Contents

Preface page ix

Chapter 1
An Overview of the Visual Basic.NET Language 1

NET Programs 1
Data Types and Variables 7
Arithmetic, String, and Relational Operators 15
Summary 42
Exercises 42

Chapter 2
An Overview of Object-Oriented Programming 44

OOP Defined 44
The Characteristics of an OOP Language 46
OOP as an Abstraction Mechanism 52
Abstract Data Types 55
Designing Object-Oriented Programs 59
Summary 62
Exercises 63

Chapter 3
Structures 64

Using Structures 64
v
vi CONTENTS

A Complete Name Structure Implementation 83


Another Structure Example—The Rational Object 85
From Structures to Classes 90
Summary 91
Exercises 91

Chapter 4
Classes 93

Building a Class 93
Class Constructors 96
Copy Constructors 120
Summary 135
Exercises 135

Chapter 5
Access Modifiers 136

Public Access 137


Private Access 139
Protected Access 141
Friend Access 145
Protected Friend Access 147
Shadows 147
Class-Level Access Modifiers 149
Summary 156
Exercises 156

Chapter 6
Abstract Classes and Interfaces 158

Abstract Classes 158


Summary 177
Exercises 177

Chapter 7
Implementing the IEnumerable and IComparable Interfaces 179

The IComparable Interface 180


Implementing the IComparable Interface 180
Contents vii

The IEnumerable Interface 185


Summary 190
Exercises 191

Chapter 8
Designing and Implementing Exception Classes 192

Exception Handling in VB.NET 192


Creating and Using an Exception Class 197
Summary 200
Exercises 201

Chapter 9
Design Patterns and Refactoring 202

Design Patterns 202


Refactoring 206
Summary 221
Exercises 221

Chapter 10
Object Internals: Reflection and Attributes 223

Using Reflection 224


Using Reflection with Class Objects 225
Manipulating Class Objects Using Reflection 234
Attributes and Reflection 244
Intrinsic Attributes 245
Summary 251
Exercises 251

Chapter 11
Object Persistence: Serialization 252

Serialization Defined 252


Serializing a Class Object 253
Deserializing a Class Object 255
Leaving Data Unserialized 258
Summary 259
Exercises 259
viii CONTENTS

Chapter 12
Building a Windows Application 260

VS.NET-Generated Code 261


Considering a Calculator Design 262
A Calculator Model 263
Designing the Calculator User Interface 268
Writing the Calculator Program Code 269
Summary 275
Exercises 276

Chapter 13
Database Programming Using ADO.NET 277

An Overview of ADO.NET 277


Accessing a Database Table Using Non-OOP Techniques 278
OOP Techniques for Database Access 282
Summary 290
Exercises 290

References 291
Index 293
Preface

Visual Basic is arguably the most popular application development program-


ming language in use today. Thousands, if not millions, of programmers use it
every day to build both commercial and scientific applications. The language
is also one of the most maligned programming languages, second perhaps
only to Cobol.
The newest version of Visual Basic, Visual Basic.NET (VB.NET), should
eventually quiet many of those who call Visual Basic a toy language. Microsoft
performed a major redesign of Visual Basic and added many features that put
the language on equal footing with the other major .NET language, C#, and
with other contemporary languages, especially Java.
One area of the language that has seen significant improvement is VB.NET’s
object-oriented programming features. In previous versions of Visual Basic,
many of these features were partially implemented, not implemented at all, or
implemented in a wrong-headed manner. VB.NET provides the programmer
with a complete set of object-oriented tools. This book explains in detail how
to use these features.
The book is informally partitioned into three parts. Chapters 1 through
6 present the fundamentals of object-oriented programming (OOP) using
VB.NET. Chapter 1 provides a review of the syntax of VB.NET. This chapter
is especially useful for readers who have experience with an older version
of Visual Basic. Chapter 2 discusses the philosophy of OOP, including some
sections on object-oriented design and abstract data types. Chapter 3 covers
programming with structures, which are similar to user-defined types (UDTs)
in Visual Basic 6. Structures are more powerful than UDTs because you can
also define subprograms (methods) within a structure definition.

ix
x PREFACE

Chapter 4 introduces the reader to classes and covers all the fundamen-
tal components of a class—data members, constructors, property methods,
and other methods. Chapter 5 discusses the different access modifiers (Pub-
lic, Private, Protected, and Friend) that can be applied to class objects, data
members, and methods. Understanding how access modifiers work is impor-
tant for creating a properly functioning object-oriented program. Chapter 6
ends the first part of the book by examining how to create abstract classes
and interfaces in VB.NET. Inheritance is a very important concept in OOP,
and one that is easy for the newcomer to misunderstand. By combining the
two major types of inheritance in one chapter, the reader can more easily
compare and contrast inheritance versus interfaces to decide which to use for
any particular application.
Chapter 7 begins the coverage of more advanced OOP topics by examining
two interfaces that are frequently implemented in a class: IEnumerable and
IComparable. The IEnumerable interface is used when class objects are placed
into a collection, and the IComparable interface is used to compare complex
class objects that are made up of more than one primitive data type. Chapter
8 covers exception handling in VB.NET, including how to build custom ex-
ception classes to enable a class to throw its own exceptions rather than rely
on built-in exceptions.
Chapter 9 discusses two software engineering aspects of OOP—design
patterns and refactoring. These techniques are becoming more and more im-
portant to building OOP applications and no introduction to OOP would be
complete without discussing how to use design patterns and refactoring in
making programs more efficient and more maintainable. Chapter 10 examines
how reflection can be used to examine a class at runtime and how to invoke
a class method without using an instance of the class. Chapter 11 introduces
the reader to how serialization is used for object persistence. Persistence is the
ability of a class to save its state from one invocation of an object to another.
The third section of the book consists of Chapters 12 and 13, which
demonstrate how to use OOP techniques to build Windows applications.
Chapter 12 discusses using OOP on a standard, form-based application and
Chapter 13 examines how to use OOP and ADO.NET for designing programs
that interact with a database.
This book is intended as a second course, or text, in the VB.NET language.
The reader should at least be familiar with the basic constructs (sequence,
branching, loops, subprograms, and event handling) of the programming
languages that are currently popular (i.e., Visual Basic, C++, or Java). One
of the strengths of this book is that it does not try to combine teaching the
Preface xi

fundamentals of the VB.NET language along with the language’s OOP features.
Although some OOP purists might disagree, I believe that the programming
student should fully understand the imperative paradigm before attempting
to learn the object-oriented paradigm.
The book can be used as a textbook in a second or third course in VB.NET
or in conjunction with another, more traditional textbook, and it can be
read for self-study. Each chapter has a set of exercises that all readers should
attempt to complete. If you are an instructor and would like solutions to the
exercises, please email me at [email protected] and we will begin a
correspondence so that I can determine whether you are indeed an instructor
and not an enterprising student.
C HAPTER 1

An Overview of the Visual


Basic.NET Language

This chapter presents an overview of the syntax and primary constructs of


the Visual Basic.NET (VB.NET) language for programmers unfamiliar with
VB.NET. This is not a tutorial chapter, however, so if you are new to program-
ming you should study another text on VB.NET before continuing with this
book. If, though, you are coming to VB.NET from some other language, such
as C++ or Java or even Visual Basic 6, you should read through this chapter
to familiarize yourself with the language.

NET PROGRAMS

There are two ways to build programs in VB.NET. One is to use the Vi-
sual Studio.NET Integrated Development Environment (IDE). The other is
to use the command-line compiler packaged as part of the .NET Framework
Software Development Kit (SDK). In this section we’ll discuss developing
programs with the command-line compiler, since this software is free and
can run on any of the modern Windows operating sysems (Windows 98 and
beyond).

1
2 AN OVERVIEW OF THE VISUAL BASIC.NET LANGUAGE

VB.NET Program Types

With VB.NET, you can write many different kinds of programs. A VB.NET
program that makes use of a graphical user interface (GUI) is a Windows
application. A VB.NET program that uses the command-prompt console for
input and output is called a Console application. You can also write Internet
applications, Windows Services applications, and other types of applications.
In this book we will focus on Console and Windows applications, though we
will look at examples of Windows Services and Internet (ASP.NET) applica-
tions in the last few chapters.

Writing a Console Application Using the


Command-Line Compiler

You do not have to be running Visual Studio.NET to compile and run VB.NET
programs. A command-line compiler is shipped with the .NET Framework
and can be used for any VB.NET programs you want to develop.
To get to the compiler, find the Microsoft.NET subdirectory. It is usu-
ally found in the Winnt or Windows (for Windows 98) directory. Then
change directories to the Framework subdirectory. The compiler resides in
yet another subdirectory. The name of the subdirectory depends on which
version of the .NET Framework you are using. The current .NET Frame-
work version stores the compiler in the v1.0.3705 subdirectory, but be sure
to check this on your own system since your version may be different.
The path to the compiler for a typical computer running Windows 2000
is c:\winnt\Microsoft.NET\Framework\v1.0.3705.
Using the compiler is quite simple. First, create a source file using the text
editor of your choice. Make sure the file you create has a .vb extension. Let’s
look at an example of a simple VB.NET program, a program that displays the
text “Hello, world!” on the screen:

Imports System
Module HelloWorld
Sub Main()
Console.WriteLine("Hello, world!")
End Sub
End Module
NET Programs 3

The first line indicates that the program needs to use a class found in the
System namespace. A namespace is a tool used to group related classes and
other types together. Namespaces also allow different classes to share the same
name. Using the keyword Imports allows us to use a class from the specified
namespace (System in this case) without using the namespace name first. We
can just as easily leave the first line of the program out altogether and type in
the fully qualified name of the class:

System.Console.WriteLine("Hello, world!")

Generally, importing a namespace makes your programs easier to write and


easier to read.
The next line defines a module named HelloWorld. A module is one of the
possible packages into which we can write code that we want to compile and
execute. Another package we can use is a class. Generally, though, we want
to save the use of classes for defining our own custom types, so we’ll use
modules for writing Console applications in this book. Modules are begun
with the Module keyword and are closed with the line End Sub.
The first line inside the Module definition defines a subroutine called Main.
This subroutine is the entry point of the application, and the compiler will
report an error if Main is not found somewhere in a module or class. If you
are using a class rather than a module as the packaging for your application,
Main must be defined as a Shared method, which means that the class does
not have to be instantiated for the code to be executed. We’ll explain later in
the book what we mean by a Shared method. Main must be closed with the
line End Sub.
The line that displays the message “Hello, world!” on the display is

Console.WriteLine("Hello, world!")

To display text on the computer’s console, you have to call the Console class
and the proper method for writing text to the console, one of which is the
WriteLine method. This method displays the text passed to it as the argument
on the console and then writes a newline character so that any more text will
be written on the next line.
To end this section, we’ll look at writing the same HelloWorld program
as a class rather than as a module. The codes are similar, and to be honest,
the two techniques are virtually identical. However, because in this book we
4 AN OVERVIEW OF THE VISUAL BASIC.NET LANGUAGE

use classes to define special types, we’ll write all our Console applications as
modules.
Here’s the HelloWorld class code:

Imports System
Class HelloWorld
Shared Sub Main()
Console.WriteLine("Hello, world!")
End Sub
End class

To compile your program (assuming the source file name is test.vb), issue
the following command:

vbc test.vb

If your program compiles successfully, you can simply run the executable file
(test.exe) to run it. If your program has errors in it, the compiler will return
the errors to your console.

Writing a Windows Application Using the


Command-Line Compiler

One of the surprising things about VB.NET is that you don’t have to use Visual
Studio.NET to build a Windows application. Unlike previous versions of the
language, VB.NET gives the programmer the ability to build a GUI directly
from code. Although you probably won’t want to use this feature all that often,
there will be situations when building a GUI from scratch will be necessary.
This is certainly true if you are using Windows 98 or ME and can’t run Visual
Studio.NET.
To demonstrate how to write a Windows application, we’ll rewrite the
HelloWorld program so that the text is displayed in a label on a form. First,
let’s look at the code:

Imports System
Imports System.Drawing
Imports System.Windows.Forms

Public Class HelloWorld


Inherits Form
NET Programs 5

Private lblHelloLabel As Label

Public Shared Sub Main()


Application.Run(New HelloWorld())
End Sub

Public Sub New()


lblHelloLabel = New Label()
With lblHelloLabel
.Location = New Point(50, 50)
.Size = New Size(392, 64)
.Font = New Font("Courier", 24)
.Text = "Hello, world!"
.TabIndex = 0
.TextAlign = ContentAlignment.TopCenter
End With

Me.Text = "A Hello, world! Windows Example"


AutoScaleBaseSize = New Size(10, 20)
FormBorderStyle = FormBorderStyle.FixedSingle
ClientSize = New Size(599, 125)

Controls.Add(lblHelloLabel)

End Sub
End Class

You’ll notice first that there are two new namespaces imported into the pro-
gram. These namespaces are needed for building Windows applications. The
next line is just the definition of the class that holds the program. The follow-
ing line

Inherits Form

tells the compiler that the HelloWorld class is inheriting the Form class, which
is found in the Systems.Windows.Forms namespace. Inheritance is a powerful
technique in object-oriented programming and we will spend at least one
chapter discussing it later in the book.
The next line declares a label for displaying the “Hello, world!” text. Follow-
ing this declaration is the Main subroutine. Be sure to use the Shared modifier
in the heading since we have to use a class for a Windows application.
6 AN OVERVIEW OF THE VISUAL BASIC.NET LANGUAGE

The single line inside Sub Main is

Application.Run(New HelloWorld())

The Application class (which is part of System.Windows.Forms) includes


the Run method, which performs the tasks necessary to run the HelloWorld
program as a Windows application.
Following Sub Main is another subroutine definition—New. The New sub-
routine is a special type called a constructor. Constructors are used to create a
new Class object. This process is called instantiation and every new Class ob-
ject must be instantiated using a constructor. The code inside the constructor
definition is run when the constructor is called, which in this program is the
line

Application.Run(New HelloWorld())

Constructors are discussed in much more detail in Chapter 4.


Inside the constructor method are the details for displaying “Hello, world!”
in a form. First, a new label is instantiated. We’ll place our text inside this
label. The next several lines set several of the label’s properties, including the
font type, the font size, and the location of the label. These lines are placed
inside a With statement, a convenient shortcut to use when you need to make
several changes to or perform other operations on the same object.
The line after the End With statement sets the caption of the current form.
Since there isn’t really a name for the form, we refer to it as Me. We’ll see other
uses for Me throughout the book.
The next three lines set some properties having to do with our form. The
last line before the end of the subroutine adds the label to the form’s Control
collection. The program ends by closing off the subroutine definition and the
class definition.
Windows applications are compiled a little differently than Console appli-
cations. The command to compile the HelloWorld program is as follows:

vbc HelloWorld.vb /reference:System.dll,System.Drawing._


dll, System.Windows.Forms.dll /target:winexe

(Note that the command would be all one line when typed, but here it is
broken into two lines for readability.)
Data Types and Variables 7

FIGURE 1.1. A Hello, World Windows Example

The first thing you notice is the switch—/reference. We have to add ref-
erences to the different namespaces we use in this program for creating a
Windows application. We didn’t need this switch in the Console application
because the compiler automatically includes the System.dll file. The other
files (including System.dll), though, must be referenced specifically.
The last part of the command tells the compiler to build a Windows appli-
cation (winexe). A Console application is compiled to just an .exe file. If you
look at the file created by the compiler, though, it still displayed as wtest.exe.
The compiler adds data internally to the file to enable it as a Windows appli-
cation.
Now we’re ready to run the program and examine the output (see
Figure 1.1).

DATA TYPES AND VARIABLES

VB.NET contains the standard data types for storing numeric, string, char-
acter, and object values, as well as special data types for times, dates, and
monetary values. The primary data types in VB.NET are the following:

 Boolean: True or False.


 Byte: 0–255 (unsigned).
 Char: 0–65535 (unsigned).
 Date: A date and time combination.
 Decimal: 0 through ±79,228,162,514,264,337,593,543,950,335 with no
decimal point; 0 through
±7.9228162514264337593543950335 with 28 places to the
right of the decimal; smallest nonzero number is
±0.0000000000000000000000000001 (±1E−28).
8 AN OVERVIEW OF THE VISUAL BASIC.NET LANGUAGE

 Double: −1.79769313486231570E+308 through


−4.94065645841246544E−324 for negative values;
4.94065645841246544E−324 through
1.79769313486231570E+308 for positive values.
 Integer: −2,147,483,648 through 2,147,483,647.
 Long: −9,223,372,036,854,775,808 through
9,223,372,036,854,775,807.
 Object: Any object.
 Short: −32,768 through 32,767.
 Single: −3.4028235E+38 through −1.401298E−45 for negative
values; 1.401298E−45 through 3.4028235E+38 for positive
values.
 String: 0 to approximately 2 billion Unicode characters.
 Structure: A user-defined type built from other data type components.

Variable Declaration

Variables are declared using the Dim keyword. For example,


Dim mySalary As Integer
Dim empID As String

The reason we use the Dim keyword when declaring a variable dates back to
the early days of the Basic language. In those days, variables did not have to be
declared; they could just pop into existence when needed. Arrays, however,
had to declared first with the dimension of the array. The Dim keyword, then,
identified a variable as an array and not just a plain variable. The use of Dim
has continued through the many different versions of the language right up
to VB.NET.
Multiple variables of the same type can be declared on the same line by
separating each variable with a comma, like this:
Dim num1, num2, num3, num4 As Single

Initializers

An initializer is a variable declaration in which a value is also assigned to the


variable. Initalizers are new to VB.NET, although many other languages have
them. Here are some examples of initializers:
Data Types and Variables 9

Dim salary As Integer = 35000


Dim lastName As String = "Durrwood"

Named Constants

A named constant is a variable whose value is assigned when it is declared and


whose value cannot be changed. Named constants are often called “magic”
values because they are usually used to represent important and/or frequently
used values in a program.
Named constants are declared with the Const keyword. Here are some
examples:

Const PI As Single = 3.14159


Const GREETING As String = "Hello, there."
Const LOGIN_CODE As String = :"letmein"

It is a common programming practice, though not a requirement of the


VB.NET compiler, to use all uppercase letters when declaring a named con-
stant. This helps these “magic” values stand out in your code so that they’re
easier to find.

Implicit Type Conversions and the Option Strict Switch

There are two ways to perform data type conversions in VB.NET. One way
is to simply let the compiler do it for you. This is the easiest way and the
one that is most likely to lead to both subtle and not-so-subtle errors in your
programs. As an example, let’s look at a simple code fragment that converts a
Single value to an Integer:

Dim pi As Single = 3.14159


Dim intPi As Integer = pi

Because intPi is an Integer variable, when it is assigned the value of pi the


compiler assigns the value 3 to the variable. This is called a narrowing con-
version because the value 3.14159. . . is “narrowed” to 3 to fit in an Integer
variable.
10 AN OVERVIEW OF THE VISUAL BASIC.NET LANGUAGE

There are also widening conversions. When an Integer value is stored in


a Single or Double variable, the value increases in size (widens) to hold
the places to the right of the decimal point. Consider the following code
fragment:

Dim intVal As Integer = 3


Dim dblVal As Double = intVal

Here an Integer variable storing the value 256 is assigned to a Double variable,
so that the value 256.0 is stored in the Double. These types of conversions
are called implicit conversions because the compiler performs the conversion
behind the scenes.
Although implicit conversions are allowed, as just shown, that’s not to say
we should prefer allowing the compiler to make conversions for us. There will
be situations when implicit conversions are made that are not what we want
to happen, leading to logical errors or worse. The VB.NET compiler allows
implicit conversions to take place when the Option Strict switch is off.
This switch tells the compiler whether or not to perform strict type check-
ing. When Option Strict is off, implicit conversions will be performed; when
Option Strict is on, a design-time error is flagged when an implicit conver-
sion is attempted. Most, though certainly not all, programmers consider it
good programming practice to set the Option Strict switch on so that any
conversions that take place must be explicitly performed using a conversion
function.
The Option Strict switch is set by writing either Option Strict On or Option
Strict Off at the beginning of your program. In fact, the statement must precede
any declarations or Imports statements, like this:

Option Strict On
Imports System
Module Module1
Sub Main()
' Code here
End Sub
End Module

One more word of caution on leaving the Option Strict switch off. It can
lead to slower code. A simple example will illustrate the problem:
Data Types and Variables 11

Dim n As Object
Dim names As String
For Each n In NameList
names & = n & ","
Next

In this code, NameList is an ArrayList that holds a list of names. The loop
builds a comma-delimited string of the names in the ArrayList. With Option
Strict off, this code compiles and runs because the compiler will convert each
value of n to a String before appending it to names. And that’s the problem with
leaving Option Strict off. Each conversion will take more time than necessary
because the compiler has to perform a test of the data types and then perform
the conversion. An explicit conversion via a conversion function will speed
this up considerably. In the next section we’ll examine how to perform explicit
type conversions using VB.NET’s type conversion functions.

Type Conversion Functions

VB.NET has a full set of built-in conversion functions for performing ex-
plicit type conversions. The following list shows each function and the type
converted to:
 CBool: Boolean
 CByte: Byte
 CChar: Char
 CDate: Date
 CDbl: Double
 CDec: Decimal
 CInt: Integer
 CLng: Long
 CObj: Object
 CSng: Single
 CStr: String

Now let’s look at some examples:

Salary = CInt(Console.ReadLine()) ' Converts console


' input to Integer
' value
12 AN OVERVIEW OF THE VISUAL BASIC.NET LANGUAGE

Salary = CInt(txtSalary.Text) ' Does the same with a


' textbox
taxRate = CDbl(5)

There are many other type conversions you can perform that are not as
intuitive as these. For example, you can convert from a Boolean value to a
String. The Boolean values True and False become “True” and “False” after
the conversion. You can convert an Integer to Boolean—zero converts to False
and a nonzero value converts to True.

Arrays

There are many times when you need to store related values within one vari-
able name. Since regular variables only allow you to store one value in them
at a time, you have to use something else—an array.
An array is a variable that stores multiple values of the same data type. Each
value in an array (also called an element) is indexed by number. Arrays are
created by specifying an array name, the number of elements to store, and the
data type of the elements. The general form for an array declaration is

Dim array-name(n) As Data-type

Here are some array declaration examples:

Dim grades(9) As Integer


Dim names(39) As String
Dim averages(99) As Single

In VB.NET, as in of most other languages, the first index of an array is 0.


For that reason, the number you use to declare the size of an array should
always be one less than the total number of elements you want to store in
the array. In the preceding examples, the grades array stores 10 elements, the
names array stores 40 elements, and the averages array stores 100 elements.
An alternative way to declare an array is to provide an initialization list,
which is a list of values to store in the array. The values are separated by
commas and surrounded within curly braces. Here is an example:

Dim grades() As Integer = {65, 72, 83, 97}


Data Types and Variables 13

The compiler automatically sizes the array based on the number of items in
the initialization list. Putting a number inside the parentheses after the array
name will lead to an exception.
Array objects are treated like class instances in VB.NET. There is a set of
methods associated with arrays you can use in your programming. One of the
most useful of these methods is GetUpperBound. This method returns the
last index number (referencing the last element) in an array. You can use this
method when looping through an array, which is demonstrated later in this
chapter when we discuss repetition statements.
There are also array methods that perform tasks that used to take spe-
cially written code to perform, such as sorting an array and reversing an
array. The two methods for these operations are Sort and Reverse. Here’s an
example:

Imports System
Module Array
Sub Main()
Dim names() As String = {"Mike", "Francis", "Ed", _
"Joan", "Terri"}
names.Sort(names)
Dim name As String
For Each name In names
Console.Write(name & " ")
Next
names.Reverse(names)
Console.WriteLine()
For Each name In names
Console.Write(name & " ")
Next
End Sub
End Module

Multi-dimensional Arrays

Arrays are not limited to one dimension. You can create arrays of multiple
dimensions, though it is uncommon to see arrays of more than three dimen-
sions. The most common multidimensional arrays are two-dimensional arrays
that model a table of data.
14 AN OVERVIEW OF THE VISUAL BASIC.NET LANGUAGE

A two-dimensional array creates a set of data in the form of rows and


columns. The rows make up the first, or 0th, dimension of the array, and the
columns make up the second, or 1st, dimension of the array. The general form
of a two-dimensional array declaration is

Dim array-name(rows, cols) As Data-type

For example, the following code declares an Integer array with five rows and
six columns:

Dim nums(4,5) As Integer

You can also use an initialization list in a two-dimensional array declaration.


Each dimension is delimited by curly braces and separated from each other
by a column. Here’s an example:

Dim grades(,) As Integer = {{76, 83, 91}, {100, 75, 66}}

Within the parentheses is a single comma. This comma indicates to the


compiler that the array should be created with two dimensions. An array
created with three dimensions would have two commas.

Array Element Access

Array elements are accessed by referencing their position in the array by index
number. For example, the 0th element of a single-dimensional array named
grades is accessed like this:

current_grade = grades(0)

Accessing an element in a two-dimensional array is similar:

current_grade = grades(1, 3) ' Accesses grade in second


' row, fourth column

You can assign data to an array element in the same way:


Arithmetic, String, and Relational Operators 15

grades(0) = 82
grades(1,3) = 94

Processing Array Elements

The most interesting processing you can do with arrays involves looping con-
structs, which we haven’t discussed yet. We will look at examples of processing
arrays when we cover loops later in this chapter.

ARITHMETIC, STRING, AND RELATIONAL OPERATORS

VB.NET provides a full set of operators for performing arithmetic, operations


on strings, and other processes. In this section we’ll review these operators.

Arithmetic Operators

The arithmetic operators are the following:

 + (addition)
 - (subtraction)
 * (multiplication)
 / (division)
 \ (integer division)
 Mod (modulo)

The first four operators should be familiar to you. We will not discuss them
here. The last two operators, however, might be new to those who don’t have
much of a mathematics background.
When one operand is divided by a second operand using the integer division
operator, the result is rounded up to the integer nearest zero. The modulo
operator, in contrast, returns the remainder of the division of two operands.
Next we look at some examples using these operators.

result = 4 \ 2.25 ' result is assigned the value 2


result = 23 mod 2 ' result is assigned the value 1
16 AN OVERVIEW OF THE VISUAL BASIC.NET LANGUAGE

String Operators

There are two string operators in VB.NET and they both perform the same
operation—concatenation. These operators are the ampersand (&) and the
plus sign (+). Generally, you should choose the ampersand when performing
string concatenation in order to make your intentions obvious, but be aware
that using the plus sign will work also. Here are some examples:

Dim new_string As String


Dim string1, string2, string3 As String
string1 = "Object-Oriented Programming "
string2 = "With Visual Basic.NET"
new_string = string1 & string2
new_string = new_string & " Edition " + "1"
Console.WriteLine(new_string)

The value of new string is “Object-Oriented Programming With Visual


Basic.NET Edition 1”. If you remove the quotes from “1”, an error results
because the + sign is defined only for concatenation when a string is one of
the operands.

Special Relational Operators and Logical Operators

VB.NET features the normal complement of relational operators necessary


for modifying the control flow of a program and for performing comparisons
between two operands. These are discussed below when we discuss branching
statements.
There are also some special relational operators used with referency types
in VB.NET. These special relational operators are:

 Is (For testing reference types for equality)


 TypeOf . . . Is (For testing to see if a reference type is a particular type)
 Like (For string comparisons using pattern matching)

The Is operator is used to test the equality of reference objects. Quite


often, the Is operator is used to determine if a reference object has been “de-
referenced” or set to Nothing. The TypeOf . . . Is operator is used to determine
Arithmetic, String, and Relational Operators 17

if a reference object is a specific type. The program below demonstrates how


these operators are used:

Module Module1

Public Class Name


Private first As String
Private last As String

Public Sub New()


first = ""
last = ""
End Sub
End Class
Sub Main()
Dim myName As New Name()
If (TypeOf (myName) Is Name) Then
Console.WriteLine("Object is a Name type")
End If
myName = Nothing
If (myName Is Nothing) Then
Console.WriteLine("Object is now nothing.")
End If
Console.Read()
End Sub

End Module

The Like operator performs pattern matching on strings in order to perform


“close matches.” For example, if you need to determine if a string begins with
a certain two characters, but can contain any other characters after those two,
you can write a statement like this:

If (name Like "Mi*") Then . . .

The rules for determining matches using the Like operator are as follows:

 The ? character matches any single character.


 The * character matches zero or more characters.
 The # character matches any single digit.
18 AN OVERVIEW OF THE VISUAL BASIC.NET LANGUAGE

 The [] brackets indicate that any characters withing the brackets match
any single character.

Branching Statements

There are two statements used for branching in VB.NET: the If statement and
the Select Case statement. In this section, we’ll look at the various ways you
can form an If statement and then look at how to perform more structured
branching using the Select Case statement.

The If Statement
Branching is the term used for altering the flow of a computer program based
on testing a value or set of values. For example, when writing a program
that calculates a company’s payroll, the program should perform one set of
calculations if an employee has worked forty hours or less and the program
should perform a different set of calculations if an employee has worked more
than forty hours. Branching is most commonly performed in VB.NET with
the If statement.
The most common form of an If statement is:

If (expression) Then
Statement body
End If

The expression inside parentheses is always an expression that evaluates to


True or False. The expression is usually formed using one or more of the
following relational operators:

 > (greater than)


 >= (greater than or equal to)
 < (less than)
 <= (less than or equal to)
 = (equal to)
 <> (not equal to)

Expressions using these operators are often called relational expressions.


Examples of these types of expressions would be:
Arithmetic, String, and Relational Operators 19

(hours > 40)


(salary = 35000)
(myName <> yourName)

Relational expressions can be combined using one of the logical operators.


These operators are used to combine two or more relational expressions that
evaluate to one truth value. The logical operators are:

 And
 Or
 Not

Here are some examples of relational expressions combined with logical


operators:

(hours > 40) Or (salary > 22000)


(pwd = "Guess") And (id = "Admin")
Not (time = 1300)

When the expression tested by an If statement is True, the statement(s)


inside the body of the If are executed. If the expression is False, the statement
body is skipped and control passes to the line after the end of the If statement.
Here’s an example:

hours = 42
If (hours > 40) Then
pay = (hours * (salary * 1.5))
End If

Often, when writing an If statement, you want to perform one set of oper-
ations if the expression is True and another set of operations if the expression
is False. To do this, use the If–Else form of the If statement:

If (expression) Then
Statement body
Else
Statement body
End If
20 AN OVERVIEW OF THE VISUAL BASIC.NET LANGUAGE

We can use this form of the If statement in the previous example to calculate
an employee’s pay based on how many hours he or she worked:

If (hours > 40) Then


pay = hours * (salary * 1.5)
Else
pay = hours * salary
End If

If statements can be nested inside other If statements if necessary, though


this often leads to logic that is hard to understand. Here’s an example extending
the payroll code we’ve been looking at:

If (hours > 40) Then


If (hours >= 50) Then
pay = hours * (salary * 2.0)
Else
pay = hours * (salary * 1.5)
End If
Else
pay = hours * salary
End If

If an employee’s hours are greater than 40 and the hours are greater than or
equal to 50, then the employee is paid double time. If the hours are just greater
than 40, then the employee is just paid time and a half. If neither of these are
true, then the employee is just paid for regular time.
There is one final form of the If statement you can use when there are many
possible choices to test. This form is the If–ElseIf:

If (expression) Then
Statement body
ElseIf (expression) Then
Statement body
ElseIf (expression) Then
Statement body
Else
Statement body
End If
Arithmetic, String, and Relational Operators 21

Each expression is tested in order. If the first expression is True, then


the statement body for that expression is executed and control passes to the
statement after the End If statement. If the first expression is False, then the
second expression is tested. If it is True, then the statement body is executed
and control passes out of the If statement. This continues until there are no
more expressions to test. If no expressions are True and there is an Else clause,
the statement body within the Else is executed. Otherwise, the If statement
is finished executing and the program continues.
Here’s some code using the If–ElseIf form:

If (hours < 20) Then


pay = hours * salary
ElseIf (hours > 20) And (hours <= 40) Then
pay = (hours * salary)
pay = pay - deductions
ElseIf (hours > 40) Then
pay = hours * (salary * 1.5)
pay = pay - deductions
End If

Short-Circuiting
When you combine two logical expressions with a logical operator, the com-
piler follows the standard “truth table” rules for determining whether the
entire expression is True or False. For example, the expression

(12 > 23) Or (33 < 100)

is True because the first expression is True, making the whole expression True.
Since only the first expression need be tested in an Or expression, it makes
sense to design the logical operators so that they’ll recognize this situation
and return True as soon as the compiler recognizes the operator to be Or and
that the first expression is True. This is called short-circuiting, and VB.NET
has two special logical operators for short-circuiting: AndAlso and OrElse.
Let’s look first at OrElse. Here, if the first expression evaluates to True, the
compiler can assign True to the complete expression and move on, as in the
following example:

Dim grade1 As Integer = 92


Dim grade2 As Integer = 100
22 AN OVERVIEW OF THE VISUAL BASIC.NET LANGUAGE

If (grade1 > 90 OrElse grade2 > 90) Then


Console.WriteLine("Exempt from final.")
End If

The compiler doesn’t have to test the expression grade2 > 90 since grade1 >
90 is True. If the value of grade1 is less than 90, making the first expression
False, then the compiler must continue on to test the second expression.
The AndAlso operator works similarly, but with different rules, of course.
Here’s a code fragment that demonstrates how AndAlso works:

Dim FirstName As String = ""


Dim LastName As String = "Lennon"
If (FirstName <> "" AndAlso LastName <> "") Then
Console.WriteLine("Name section complete.")
Else
Console.WriteLine("Name section incomplete. Please _
finish.")
End If

The output from this code is

Name section incomplete. Please finish.

because the first expression in the If statement is False. The second expression
is not even tested since both expressions must be True for the whole expression
to be True.

The Select Case Statement


When you have a long series of expressions to test, a more structured way to
write the code is to use a Select Case statement. The general form of the Select
Case statement is

Select Case value


Case (expression 1)
Statement body
Case (expression 2)
Statement body
Case (expression n)
Statement body
Arithmetic, String, and Relational Operators 23

Case Else
Statement body
End Select

The value at the beginning of the statement can be any expression that
evaluates to a value. Each Case clause then tests an expression against the
value, evaluating to either True or False. If True, the statement body inside
the Case clause is executed and control is passed to the first statement after
the Select Case statement; if False, the next Case clause is evaluated. If none
of the expressions evaluate to True, and there is a Case Else clause, the state-
ment body inside the clause is executed. If there is not a Case Else clause,
and none of the expressions evaluate to True, control transfers to the first
statement outside the Select Case statement.
Let’s look at an example of using a Select Case statement. The following
code fragment assumes a value has been assigned to the variable grade:

Select Case grade


Case 90 To 100
Console.WriteLine("You made an A!")
Case 80 To 89
Console.WriteLine("You made a B!")
Case 70 To 79
Console.WriteLine("You made a C.")
Case 60 To 69
Console.WriteLine("You made a D.")
Case Is < 60
Console.WriteLine("Sorry. You failed.")
Case Else
Console.WriteLine("Bad input.")
End Select

There are many different ways to test the value in the Select Case statement.
One way, as just shown, is to use the To keyword to express a range of values
that the tested value can fall within. You can also write out individual values,
separating them with commas, like this:

Case 96, 97, 98, 99, 100


Console.WriteLine("You made an A+!")
Case 90 To 95
24 AN OVERVIEW OF THE VISUAL BASIC.NET LANGUAGE

Console.WriteLine("You made an A!")


. . .

You can use a relational operator in the Case clause, as we did in the earlier
example to test for a failing grade. Here is another example, where all we’re
looking for is a passing or a failing grade:

Imports System
Module SelectCase
Sub Main()
Dim grade As Integer
Console.Write("Enter your grade: ")
grade = CInt(Console.ReadLine)
Select Case grade
Case Is >= 60
Console.WriteLine("You passed!")
Case Is < 60
Console.WriteLine("Sorry, you failed.")
Case Else
Console.WriteLine("Bad input.")
End Select
End Sub
End Module

The Select Case statement should be used whenever you would have to
write a very long If–ElseIf statement or whenever you want your branching
code to be as readable as possible.

Repetition Statements

Another way the flow of control of a computer program can be altered is with
repetition. Repetition allows a set of statements to be executed several times
in succession, in essence executing the statements in a loop. There are several
different types of looping statements in VB.NET. We will divide them into
two categories—While loops and For loops.

The While Statement


The While statement loops through a set of statements “while” a tested ex-
pression is True. The loop only stops when the expression becomes False. The
Arithmetic, String, and Relational Operators 25

general form of a While statement is

While (expression)
Statement body
End While

Let’s look at an example. If we want to determine how fast a city’s population


will grow over a period of years at a certain growth rate, we can do so with a
While statement. Here’s the code:

Imports System
Module Loops
Sub Main()
Dim growth As Single = 1.03
Dim population As Single = 150000
Dim numYears, start As Integer
start = 1
Console.Write("Enter the years of growth: ")
numYears = CInt(Console.ReadLine)
Console.WriteLine("The current population is: " & _
population)
While (start <= numYears)
population *= growth
start += 1
End While
Console.WriteLine("The population will be: " & _
population & " after " & _
numYears & " years.")
End Sub
End Module

The Do While Statement


An alternative way to write a While statement is to use the Do While statement.
These two looping statements are functionally equivalent and can be used
interchangeably. The general form of the Do While statement is

Do While (expression)
Statement body
Loop
26 AN OVERVIEW OF THE VISUAL BASIC.NET LANGUAGE

Here’s the city growth example rewritten with a Do While statement:

Imports System
Module Loops
Sub Main()
Dim growth As Single = 1.03
Dim population As Single = 150000
Dim numYears, start As Integer
start = 1
Console.Write("Enter the years of growth: ")
numYears = CInt(Console.ReadLine)
Console.WriteLine("The current population is: " & _
population)
Do While (start <= numYears)
population *= growth
start += 1
Loop
Console.WriteLine("The population will be: " & _
population & " after " & _
numYears & " years.")
End Sub
End Module

The Do. . .Loop While Statement


There are often times when you want your loop test expression to be at the
bottom of a loop. The Do. . .Loop While statement puts the test expression at
the bottom of the statement, as shown here in its general form:

Do
Statement body
Loop While (expression)

An example of an opportune time to use a Do. . .Loop While statement


is when you are testing user input. The following code fragment prompts a
user to enter his or her password and then tests this entry against the system
password, looping back to have the user enter the password again if the tested
password is incorrect:
Arithmetic, String, and Relational Operators 27

Console.Write("Enter your password: ")


password = Console.ReadLine
Do While (password <> sysPassword)
Console.Write("Enter your password: ")
password = Console.ReadLine
Loop

Writing code this way, we have to prompt the user to enter a password
twice. A better way to do this to use a Do. . .Loop While statement, like this:

Do
Console.Write("Enter your password: ")
Password = Console.ReadLine
Loop While (password <> sysPassword)

The Do Until Statement


The Do Until statement is used when you want to express the idea that the
loop should run “until” the test expression becomes True. The general form
of the Do Until statement is

Do Until (expression)
Statement body
Loop

Some problems are best written using a Do Until statement. Let’s look at a
variation of the city growth problem. Instead of determining the population
growth after a certain number of years, let’s write a program that determines
when the population of the city will reach half a million people, given a 3%
growth rate again:

Imports System
Module Loops
Sub Main()
Dim growth As Single = 1.03
Dim population As Single = 150000
Dim numYears, start As Integer
start = 1
28 AN OVERVIEW OF THE VISUAL BASIC.NET LANGUAGE

Do Until (population >= 500000)


population *= growth
start += 1
Loop
Console.WriteLine("The population will reach _
500,000 in " & start & " years.")
End Sub
End Module

The Do. . .Loop Until Statement


The Do. . .Loop Until statement puts the test expression at the bottom of the
loop, just as the Do. . .Loop While statement did. The general form of the
statement is

Do
Statement body
Loop Until (expression)

We can rewrite the password-checking code fragment using the Do. . .Loop
Until statement like this:

Do
Console.Write("Enter your password: ")
password = Console.ReadLine
Loop Until (password = sysPassword)

You can substitute a Do While–type loop with a Do Until–type loop in just


about any situation. The type of loop you use should be guided by which logic
for the test expression is the clearest or easiest to express.

The For Statement


The While and Do statements are used when you want to execute a series
of statements while a test expression is True or until the expression becomes
True. There are many situations in programming, however, when you want a
loop to run a specific number of times. A prime example of such a situation
is when you want to perform an operation on every element of an array. The
statement you should use in this type of situation is the For statement.
Arithmetic, String, and Relational Operators 29

The general form of the For statement is

For counter-variable = val1 To val2 Step n


Statement body
Next

where counter-variable is an Integer variable that assumes values from val1 to


val2. Step n is an optional increment that, if left out, defaults to 1.
The next program demonstrates one way to use a For statement. The array
grades stores a set of student test grades. The program accesses each grade in
the array, adding 5 points to the grade. Finally, another For statement is used
to display each element in the array. Here’s the code:

Imports System
Module Grades
Sub Main()
Dim grades() As Integer = {83, 73, 90, 100, 62}
Dim element As Integer
For element = 0 To grades.GetUpperBound(0)
If (grades(element) <> 100) Then
grades(element) += 5
End If
Next
For element = 0 to grades.GetUpperBound(0)
Console.Write(grades(element) & " ")
Next
End Sub
End Module

The optional Step clause can be used to change the default increment. Here’s
an example that sums the odd integers from 1 to 100:

Imports System
Module OddInts
Sub Main()
Dim int, sum As Integer
For int = 1 to 100 Step 2
sum += int
Next
30 AN OVERVIEW OF THE VISUAL BASIC.NET LANGUAGE

Console.WriteLine("The sum of the first 100 odd _


integers is: " & sum)
End Sub
End Module

You can also specify a negative increment in a For statement. The following
program displays the elements of an array in reverse order by starting at the
last element and moving backward through the array:

Imports System
Module Reverse
Sub Main()
Dim chars() As Char = {"a"c, "b"c, "c"c, "d"c, "e"c}
Dim pos As Integer
For pos = chars.GetUpperBound(0) To 0 Step -1
Console.Write(chars(pos) & " ")
Next
End Sub
End Module

If you don’t specify a negative number in a decrementing For statement, you


won’t get an error. The program will execute the statement body one time and
then exit the For statement.
For the last example of using For loops, we look at processing a two-
dimensional array. This array stores a set of grades for several sections of
the same course. The program calculates the average grade for each section,
displaying the section number and the average. The program is as follows:

Module Module1

Sub Main()
Dim grades(,) As Integer = {{72, 83, 67}, {92, 74, _
86}, {100, 84, 93}}
Dim average As Single
Dim row, col, endrow, endcol, total As Integer
endrow = grades.GetUpperBound(0)
endcol = grades.GetUpperBound(1)
For row = 0 To endrow
total = 0
Arithmetic, String, and Relational Operators 31

For col = 0 To endcol


total += grades(row, col)
Next
average = total / grades.GetLength(1)
Console.WriteLine("The average for section " & _
row + 1 & " is " & average)
Next
Console.Write("Press enter to quit")
Console.Read()
End Sub

End Module

Notice how the length of a column is calculated using the GetLength


method of the Array class. The value 1 is passed as an argument because
the column is dimension 1 of the array, whereas the row is dimension 0. The
same technique is used to return the upper bound of a dimension using the
GetUpperBound method.
This example also demonstrates a valuable time-saving technique. You
probably noticed that the row and column upper bound values were stored
in variables before beginning the nested For statements. This minimizes the
number of times the System has to calculate those values. For small arrays,
the time saved is not all that great, but for large arrays the time saved can be
significant. It is a good idea to get in the habit of using this technique for all
sizes of arrays.

The For Each Statement


In the examples in the previous section, a For statement was used to iterate
through an array, moving from the 0th element to the last element. An alterna-
tive method for accessing the elements of an array (or any other collection-type
data structure in VB.NET) is to use the For Each statement. This statement
accesses every element of a data collection, pulling the element out of the col-
lection and storing it in a variable, giving the program access to the element
value.
The general form of the For Each statement is

For Each variable In coll


Statement body
Next
32 AN OVERVIEW OF THE VISUAL BASIC.NET LANGUAGE

where variable is a variable of the data type of the elements in the collection,
and coll is a named collection type, such as an array or a collection.
For Each statements are typically used when you want to perform an op-
eration with or to every element of a data collection. Here is a program that
accesses an array of grades for the purposes of calculating the average grade:

Imports System
Module Grades
Sub Main()
Dim grades() As Integer = {83, 73, 90, 100, 62}
Dim total, grade As Integer
Dim average As single
For Each grade In grades
total += grade
Next
average = total / grades.Length()
Console.WriteLine("The grade average is: " & _
average)
End Sub
End Module

The operation performed by the For Each statement is called an enumer-


ation. All well-behaved collections in VB.NET are written to allow enumer-
ations via the For Each statement. Later in the book we will build our own
collection classes that include code to allow them to be enumerated with For
Each statements.

Writing Subprograms

A first layer of abstraction in a computer program consists of the subpro-


grams you create. Subprograms modularize your code, allowing you to reuse
subprograms in other programs and making your programs easier to read and
debug. In this section we’ll review how to create the two types of subprograms
allowed in VB.NET—functions and subroutines.

Functions
A function is a subprogram that returns a value to the calling program. Func-
tions in VB.NET are declared outside of Sub Main() using the following form:
Arithmetic, String, and Relational Operators 33

Function Function-name(argument-list) As Data-type


Function-definition
Return expression
End Function

A function is called by writing the function name and its arguments wher-
ever an expression can be placed. The following program, which uses a func-
tion to square a number, demonstrates both how to define a function and how
a function is called:

Imports System
Module Square
Sub Main()
Dim num As Integer = 12
Dim squareNum As Integer
squareNum = square(num)
Console.WriteLine(num & " squared is " & squareNum)
End Sub
Function square(n As Integer) As Integer
Return n * n
End Function

End Module

It is important that the data types of the arguments and the function’s return
value match the function definition or an exception will be thrown.
Arguments to functions are passed by value if you don’t specify otherwise.
To pass arguments by reference to a function, add the ByRef keyword to the
argument in the argument list. In the following program, the square function
not only squares the argument passed to it but also permanently changes the
argument’s value to its square:

Imports System
Module Square
Sub Main()
Dim num As Integer = 12
Dim squareNum As Integer
Console.Write(num)
squareNum = square(num)
Console.WriteLine(" squared is " & squareNum)
34 AN OVERVIEW OF THE VISUAL BASIC.NET LANGUAGE

Console.WriteLine("The value of num now is " & num)


End Sub

Function square(ByRef n As Integer) As Integer


n = n * n
Return n
End Function

End Module

Because we used an assignment statement in the function definition, the value


num is permanently changed to the square of its previous value.

Subroutines
Subroutines differ from functions in that a subroutine does not return a value
to the calling program. The general form of a subroutine is

Sub Subroutine-name(argument-list)
Subroutine definition
End Sub

Subroutines are used most often to perform frequent tasks that take several
lines of code to write. For example, in a Windows application, a subroutine
is written to clear the textboxes on a form:

Sub ClearText()
txtFirstName.Text = ""
txtMiddleName.Text = ""
txtLastName.Text = ""
txtAddress.Text = ""
txtCity.Text = ""
txtState.Text = ""
txtZipCode.Text = ""
End Sub

Less frequently, subroutines are written to perform more complex compu-


tational tasks. The following program uses a subroutine to swap two values
in the calling program:
Arithmetic, String, and Relational Operators 35

Imports System
Module Swap
Sub Main()
Dim value1, value2 As Integer
value1 = 12
value2 = 24
Console.WriteLine("The value of value1 is: " & _
value1)
Console.WriteLine("The value of value2 is: " & _
value2)
swap(value1, value2)
Console.WriteLine("After the swap - ")
Console.WriteLine("The value of value1 is: " _
value1)
Console.WriteLine("The value of value2 is: " _
value2)
End Sub

Sub swap(ByRef v1 As Integer, ByRef v2 As Integer)


Dim temp As Integer
temp = v1
v1 = v2
v2 = temp
End Sub

End Module

Subprograms Using Varying and/or Optional Parameters


Subprograms can be written both with a variable number of parameters and
with optional parameters that do not have to be present in every call. You
should utilize these features when necessary to make your subprograms more
powerful and flexible.
A function or subroutine can receive a varying number of arguments by
specifying that the argument list be a parameter array. A parameter array is
denoted by the ParamArray keyword before the array name is given in the
parameter list. Parameter arrays must always be passed by value; otherwise
the array is treated just like any other array being used as a subprogram
parameter.
Parameter arrays are typically used in functions that must sum a set of
values and return the total. The following short program illustrates this use
36 AN OVERVIEW OF THE VISUAL BASIC.NET LANGUAGE

of the parameter array:

Module Module1

Sub Main()
Dim g1, g2, g3, g4 As Integer
Dim sum1, sum2 As Integer
g1 = 100
g2 = 95
g3 = 90
g4 = 85
sum1 = SumGrades(g1, g2)
sum2 = SumGrades(g1, g2, g3, g4)
Console.WriteLine("The first sum equals " & sum1)
Console.WriteLine("The second sum equals " & sum2)
Console.Write("Press enter to quit")
Console.Read()
End Sub

Function SumGrades(ByVal ParamArray grades() _


As Integer) As Integer
Dim x, total, endGrades As Integer
endGrades = grades.GetUpperBound(0)
For x = 0 To endGrades
total += grades(x)
Next
Return total
End Function

End Module

By using a parameter array, the SumGrades function can accept any number
of grades. The first call to the function passes two grades; the second call passes
four grades. Giving the function this type of flexibility adds considerable
power to subprograms in VB.NET.
Another useful subprogram method is to allow a function or subroutine to
have optional parameters. An optional parameter is a parameter that is either
explicitly passed to the subprogram definition or left out completely, in which
case the compiler takes a default value for the parameter as specified in the
subprogram definition.
An optional parameter is denoted in a subprogram definition with the
keyword Optional. The parameter must also have a default value expressed,
Arithmetic, String, and Relational Operators 37

so that if the parameter is left out as an argument when the subprogram is


called, the compiler will have a value to use when the parameter is used in
the subprogram definition.
The following program demonstrates a simple use of optional subprogram
parameters. PopGrowth is a function that calculates the growth of a population
given a certain growth rate. The parameter for the rate of growth is the optional
parameter. Here’s the code:

Module Module1

Sub Main()
Dim pop As Integer
Dim new_pop As Integer
Console.Write("Enter the current population: ")
pop = CInt(Console.ReadLine())
new_pop = PopGrowth(pop, 2.0)
Console.WriteLine("The new population is " _
& new_pop)
_
new pop = PopGrowth(pop)
Console.WriteLine("The new population is " _
& new_pop)
Console.Write("Press enter to quit")
Console.Read()
End Sub

Function PopGrowth(ByVal initPop As Integer, _


Optional ByVal rate As _
Single = 1.0)
Return initPop * rate
End Function

End Module

In the first call to PopGrowth, both arguments are provided, so the function
uses the second argument, 2.0, as the rate of growth for the calculation. In
the second call to PopGrowth, just the initial population is provided, so the
function uses the default value, 1.0, for the second parameter.

Named Parameters
When a function or subroutine is called, you almost always pass arguments
to the subprogram in the same order in which the parameters are listed in
Other documents randomly have
different content
I have had to eat a number of different kinds of humble pie in my
day, and tramp life let me into some of the inner recesses of
humiliation that no one but a tramp ever knows about; but no
journey has ever made me feel quite so cheap and small as that
return trip from St. Petersburg to Tula, the railway station where
visitors to Yasnaya Polyana leave the train. I telegraphed ahead
advising the Count's neighbor of my coming, and expected that he
would meet me at the station. What was my surprise, on arriving at
Tula, to find the old Count himself waiting for me.
"Ah! Meester Fleent," he exclaimed as I got off the train and greeted
him, "have you brought me news from Prince Chilkoff?"
I wished at the time that I could sink out of sight under the
platform, so pathetically eager was the Count's expectancy. There
were only a few moments to spare, and I clumsily blurted out the
truth, trying at the same time to explain how sorry I was. The Count
calmly opened the envelope and glanced at the letters.
"Oh, it wouldn't have mattered," he said, and after shaking hands,
went back to his house. He neither seemed vexed nor embarrassed.
A suggestion of a tired look came into his face—he had ridden
seventeen versts—that was all.
One of his "disciples," referring to this affair and my connection with
it, some weeks later, ventured the statement that I had "funked" in
the matter. I hardly think the Count felt this way about it, whatever
else he may have thought. At the time, however, as he rode away on
his horse, the letters tucked carelessly under his blouse, I would
have given a good deal to know exactly what was in his mind. I
remember very accurately what was in mine—a resolution, that,
whatever else I did or did not do in life, I would never accept an
official letter to the effect that I was a gentleman and then proceed
to do something which was likely to get the letter-writer into trouble.
"Either leave such letters alone," I counseled myself, "and be your
own interpreter of gentlemanliness, or know, before accepting them,
what will be expected of you."
Tolstoy, no doubt, has long since forgotten this episode, but I never
will. In a way it left a bad taste in my mouth, and I felt that I had
spoiled my experience at Yasnaya Polyana. I outgrew this feeling,
however, and often think now of my visit to the Count and his family
as I did when I drove away to Tula in the two-wheeled cart. I likened
myself at the time to a dog "caught with the goods on," so to speak,
and slinking away with his tail between his legs, but with the
"goods" held tight in his mouth. Something, I know not what, unless
it was the sweet peace and kindliness of the Count and his
surroundings, seemed such forbidden fruit for me of my
tempestuous career to taste of, that I felt very much as I used to
feel as a boy when caught trespassing in other people's orchards. It
did not seem right that one who had been through what I had
should be allowed to enter into such an atmosphere of good cheer.
Nevertheless, I was glad that entrance had not been denied me, and
made many solemn resolutions to profit by the experience. Whether
the resolutions have been kept with the fervor and determination
that animated me in 1896, I would rather not say. But one
remembrance is as vivid and dear to me to-day as when I rode away
in the cart: the Count and his desire to do the right thing. "If to be
like him," I have often caught myself saying, "makes one a fakir,
then let us all be fakirs as quickly as possible." Unpractical, yes, in
some things; a visionary, perhaps; a "literary" reformer, also
perhaps. But my simple testimony about him and his is that I have
yet to spend ten days in a gentler and sweeter neighborhood than
those I enjoyed in and about Yasnaya Polyana.
CHAPTER XIX
I MEET GENERAL KUROPATKIN
It is a far cry from Count Tolstoy and Yasnaya Polyana to General Kuropatkin
and Central Asia, but while dealing with men and things Russian I might as
well tell here as elsewhere of my visit to Central Asia in the fall of 1897.
Again the motive was journalistic, and again I was the proud holder of a
pass over all the Russian State Railways, not over the private lines, however,
as the year before. I have to thank Prince Chilkoff, the Minister of Railways,
for this second pass. He had become considerably interested in my travels,
and on learning that I contemplated excursions into remote parts of Russia
he kindly offered to ask the Tsar to grant me free transportation for three
months "in order that my investigations might be facilitated." When the
transportation finally reached me, it read: "With Imperial Permission." I have
always thought that there was an undue amount of red-tape in getting the
pass, but Prince Chilkoff personally assured me that he must formally ask
the Tsar for it before it could be issued. This being true, the poor Tsar has
more to attend to, particularly in these later days, than ought to fall to the
lot of one man. Truly, he is an overworked man, if he must give attention to
such minor details. No wonder if some anarchist pots him. There is not a
railroad manager in the United States that could do all that the Tsar is
alleged to have his hand in on the railroads, and at the same time run a
great nation, a national church, and the largest army in the world.
Consequently the Imperial permission did not make the impression upon me
that it would have, had I believed that the Tsar had done anything more
than nod his head, or make a scratch of the pen, when Prince Chilkoff asked
for the pass.
I had seen the Tsar the year before, just after his coronation in Moscow. The
occasion was the Imperial return to St. Petersburg, following the terrible
accident on the Chodyuka Field in Moscow where thousands of men, women
and children were crushed to death in the mad scramble for the coronation
mugs. Rumor darkly hinted at the time that the scramble was a forced affair,
that certain officials charged with furnishing the crowd with mugs and
refreshments, had made a deal with the purveyors of these things whereby
a much smaller supply than was necessary should be furnished, the surplus
money paid out for an adequate supply going to the crooked officials and
dealers—that the scramble, in a word, was a preconcerted scheme to cover
up their devilish machinations. Charges of graft and corruption are so
numerous and haphazard in Russia that one can seldom find out the truth.
Whether this particular deal was actual or not, however, the look on the
Tsar's face when he rode down the Neffsky Prospect on his return from
Moscow was dismal enough to make almost any rumor credible. I had a
window on the Prospect directly opposite the Duma (City Hall), where the
Tsar and Tsarina accept bread and salt from the city fathers on such
occasions. A good shot could have picked off the Tsar at that moment with
ease.
A more tired-out, disgusted, bilious-looking monarch than was Nicholas
during that Neffsky ride I have never seen. The ceremony at the Duma over,
he and his wife were whisked away toward the Winter Palace, bowing
languidly to the right and left. "Insignificant" was the word I heard from
those about me at my window, and it sums up the man's looks, and I am
afraid his importance as well.

In 1897, the local Tsar of Russian Central Asia was General Kuropatkin, the
soldier who seems at the present writing to have buried his reputation as a
commander-in-chief in Manchuria. At the time in question he was looked
upon as one of the ablest and most popular generals in the Russian army.
He was also supreme "boss" in the district under his command. When the
visit of the party of which I was a member was about over, and we were to
leave Central Asia, two or three enthusiastic Britons thought that it would be
worth while to wire our gratitude to the Tsar. Kuropatkin was asked about
the advisability of such a proceeding. I was not present when the question
was put to him, but one who was present told me that Kuropatkin replied:
"What's the use? I represent the Tsar here and will transmit your message to
him." The telegram was sent nevertheless, via the British Embassy, and, as
usual, in such cases, we eventually learned that the Tsar had, metaphorically
speaking, spent his entire time wondering how he could make our visit in his
dominions more entrancing.
The excursion was the first of the kind ever permitted in Russia's Central
Asia possessions. It was really a commercial undertaking on the part of a
tourists' agency in London, but because it
was unique in Central Asian history and also
on account of Kuropatkin's hospitality, it
received a significance, social as well as
political, which does not ordinarily
accompany such enterprises. The tourist
agency had gathered together thirty-odd
Britons at the last moment, two lone
Americans, a Southern lady from South
Carolina, who, when reaching Samarcand
and learning that she was almost directly
opposite Charleston, South Carolina (on the
other side of the world), cheerfully said:
"How dear!"—and myself. The British Foreign
Office was asked to appeal to the Russian
Foreign Office to let us into the forbidden
country—forbidden in the sense that one
required a special passport from the Russian
War Office before he was allowed to cross Frances E. Willard.
the Caspian. At least this was the story told Maternal Aunt of Josiah
in those days, and Englishmen were eager to Flynt
believe it because the Russians had pushed
their southern frontier so affectionately toward Afghanistan and India. It
seemed to be their idea that the Russians were afraid to let them see what
they (the Russians) were doing on their side of the Afghanistan fence. The
Russian War Office communicated with Kuropatkin at Askabad, asking him
whether he was afraid to let the Britons see how the Russian side was
getting on. Kuropatkin replied: "Let them come in."
I joined the party at Tiflis, crossing the Black Sea from Sebastopol to Batum.
On the steamer were two of the Britons. One evening we were all sitting in
the smoking room. The Britons spoke their English with all its accents, and
some of it I could not help listening to, trying nevertheless not to mind that
they spoke it after the "We own the World" fashion. One of the Britons made
up his mind that I was a Russian spy. On several occasions he looked at me
as if I had no right on any ship that carried him. He also made blasphemous
remarks about me to his friend. I learned later that he represented The
Standard of London. He wrote several letters to his paper about the trip,
and, on one occasion, even tried to send a dispatch concerning an interview
the newspaper correspondents had with Kuropatkin at Askabad. I have been
told since that only a few of his articles ever reached their destination. I
have seldom met a man so submerged in the world of suspicion.
Kuropatkin received us at Askabad, the administrative Russian town. How he
looked and acted during the Russian-Japanese War I do not know, but he
looked the foxy soldier in every detail at Askabad. I say foxy advisedly. He
had a detective's eyes, the reserve of a detective's chief, and the physique of
a man who could stand much more punishment than his uniform would give
him room for. Since the Japanese War it has been said that he is a thief—or
a grafter, if that be more euphemistic. Certain persons claim that he is five
million rubles winner as a result of the war. What certain persons say in
Russia, and, I am sorry to say, out of it, also, so far as many of the
dispatches to American newspapers is concerned, is really nothing but
gossip. Fortunately, the Russians know what gossip is, and merely let it drip.
Unfortunately for readers of American newspapers certain correspondents do
not make the slightest effort to distinguish between gossip and facts.
Our party spent seventeen days all told in Kuropatkin's bailiwick, or Trans-
Caspia as it is officially called. We lived in a special train, stopping at the
different places of interest for a few hours, or overnight, as circumstances
required. The train was in "command" of a colonel. The diplomatic side of
the journey was attended to by a representative of the Foreign Office,
attached to Kuropatkin's staff.
Trans-Caspia is no longer the terra incognito that it was forty to fifty years
ago, thanks to numerous travelers and writers, among them our
countryman, the war correspondent, MacGahan. It consequently does not
behoove me, a mere skimmer, to attempt here much more than the
statement that our party traveled from Krasnovodsk to Samarcand and back,
and saw such places as Geok-tepe, Merv, Bokhara and the River Oxus. Geok-
tepe in 1897 consisted principally of the fragments left by Skobeleff and
Kuropatkin after their forces had slaughtered some twenty-odd thousand
Turcomans—men, women and children. The siege of the fort lasted a full
month, although the Turcomans had anticipated forms of defense. Before
the Russian campaign against them was over Skobeleff had to begin the
present Trans-Caspian Railroad in order to keep in touch with his base of
supplies. Kuropatkin was his chief of staff. They went to war with the natives
with the notion that one everlasting thrashing was imperative to teach the
Turcomans to knuckle under. The slaughter at Geok-tepe proved very
instructive, the Turcomans of to-day being a foolish people—docile, at least,
so long as the Russians can continue to impress them. Skobeleff is long
since dead, and Kuropatkin, the other "butcher," as he has been called, is
under a cloud.
I had various glimpses and talks with this soldier, perhaps the most
interesting glimpse taking place at Askabad during an outdoor religious
service on St. George's Day. The men in our party had to appear at this
service in dress suits early in the morning. The service was accompanied by
the usual Greek orthodox paraphernalia and was interesting to those who
had never before been present on such occasion. What interested me was
the short, stocky general, standing bareheaded on a carpet near the
officiating priests. For one solid hour he stood at "Attention," not a muscle in
his body moving that I could see. I made up my mind then (and I have
never changed it) that he was endowed with stick-at-iveness to a remarkable
degree—a fact bolstered up by his persistency in the Manchurian retreats.
The most interesting interview I had with Kuropatkin was, one morning,
when the three correspondents, including myself, were summoned to
Government House at Askabad and given an official reception. Kuropatkin
sat behind a large desk covered with pamphlets and official papers. We
correspondents were given three chairs in front of the desk. The interpreter
(Kuropatkin spoke neither English nor German) stood at our left.
"And I want you to know," Kuropatkin went on, after informing us somewhat
about the Russian occupation of Trans-Caspia, "that our intentions here are
eminently pacific. We have land enough. Our desire is to improve the
holdings we now possess. You can go all over Russian Central Asia
unarmed." I thought of Geok-tepe. No doubt Kuropatkin believed that that
butchery had cowed the natives for all time.
"Our desire here is economic peace and prosperity."
This was the upshot of his words, translated for us by the interpreter. Was
he telling the truth or not? There was not a correspondent present who
could have answered this question.
My impression was that the man was trying to give us an official version of
the alleged truth, and that he was proud of what he had been able to
accomplish as an administrative officer, after demonstrating his ability as a
human butcher. I have often since thought that, if the Philippines are to be
attended to quickly a la Russe, Kuropatkin could do the job very neatly.
As a mere man shorn of his grand titles, I liked him and didn't like him.
I asked him if he remembered MacGahan, the American correspondent. He
looked at me sharply, always more or less as if he were still listening to that
St. George's Day sermon, and said: "It pleases me to hear that name
mentioned. I knew him well."
I asked the interpreter to ask him if he couldn't think of an anecdote or two
about MacGahan that I could send to my paper. I realized that there was a
sorry task ahead of me writing about far-off Trans-Caspia—truly terra
incognito to most Americans—unless America could be dragged into the
story somehow. But Kuropatkin was not in the anecdotal mood. "When
MacGahan and I were together," he said, "there were too many other things
to think about and remember."
This is the upshot of my intercourse with Kuropatkin. Had there not been
something about the man and his surroundings that took hold of my
imagination this slim report would not have been made here. Throughout my
journey in Trans-Caspia I thought of Genghis Khan and Tamerlane. At Merv
we were told that there, once upon a time, Genghis had slaughtered one
million people. At Samarcand, we were shown Tamerlane's tomb. As a
modern representative of might and force Kuropatkin seemed to be an
improved edition of Genghis and Tamerlane. Whatever else he was, or was
not doing, he was plainly trying to experiment with civilization before
resorting to the sword. His schools, railroads and agricultural experiments
were all indicative of his constructive ability. For this side of his character I
liked him.
I disliked his career in butchering, and I was not pleased with his hard face.
Nevertheless, there was something so companionable and soldier-like in his
parting "Bonne Chance," when we bade him good-by, that, for me, there
was more in him to like than to scold about. As regards the alleged five
million rubles he is supposed to have "grafted" in Manchuria, I can merely
say that he did not look like a thief to me.
CHAPTER XX
IN ST. PETERSBURG
A police raid that I attended in St. Petersburg, although not directly
connected with any tramp experience there, has remained memorable, and,
after all, was due to my interest in tramp lodging houses. I explored the
local vagabonds' resorts pretty carefully during my investigations, visiting
among others the notorious Dom Viazewsky, the worst slum of the kind I
have ever seen anywhere. On a winter's night in 1896 (the conditions have
not changed, I am told), 10,400 men, women and children slept in five two-
story buildings enclosed in a space about the size of a baseball diamond.
Only a hundred paces away is the Anitchkoff Palace. The inmates of the Dom
Viazewsky are the scum of the city's population, diseased, criminal and
defiant.
On one occasion, a woman belonging to the Salvation Army was met in the
dead of night by a police sergeant and some patrolmen, as she was leaving
the most dilapidated of the buildings. She had been doing missionary work.
"My God!" the sergeant exclaimed, seeing her unattended. "You in here
alone?"
"Oh, no, not alone, officer," the intrepid little woman replied. "God is with
me."
"Huh," the officer grunted. "I wouldn't come in here alone with God for a big
sum."
The raid which I attended was made on a smaller lodging house, not far
from the Alexander Nevsky monastery. In a way, it was got up for my
benefit, I fear, and I was later very sorry about it all. The then chief of
detectives was a pleasant old gentleman, called Scheremaityfbsky. I told him
that it would interest me to see how his men "worked," and he introduced
me to a stalwart chap—I forget his name—who kindly offered to show me
how a suspicious place was raided.
We all foregathered first at the precinct station house nearest the place of
the raid, at about nine o'clock in the evening. A Scotch friend accompanied
me. Here were the so-called detectives, or policemen, in citizens' clothes. A
squad of uniformed patrolmen had already been sent on ahead to surround
the lodging house and prevent any departures. Pretty soon we followed after
them in single file, and I could hear passers-by on the sidewalk whisper,
"Polizie! Polizie!" The way they used the word and stopped to stare at us
might have given a stranger the impression that we were on a portentous
mission, which might involve the arrest of the entire city. Arriving at the
lodging house, the gates were closed behind us, and we assembled in a
lower corridor, where all hands received candles. The patrolmen outside
forbade both entrance and escape.
Clumsily, the tallow from the candles dripping on our hands, we climbed the
dingy stairway to the men's quarters. A dismal lamp burned in the center of
the room, throwing a weird light over the awakened lodgers. What a medley
of humanity that vile-smelling room contained! Old men barely able to climb
out of their bunks; rough middle-aged ruffians, cowed for the moment, but
plainly full of vindictiveness and crime; youngsters just beginning the city life
and quaking with fear at the unannounced visitation—never before have I
seen human bodies and rags so miserably entangled.
The method of the raid was simple enough. Each inmate was made to show
his passport. If it was in order, well and good; he could go to sleep again.
But if his papers were irregular, or, still worse, if he hadn't any at all, below
he went to join the others who were guarded by the policemen. The worst
that was found that night I fancy were some hiding peasants, who had run
away from their villages and were loafing around begging in the city. One
poor old man took me for an officer. I was passing around between the
beds, holding my candle high so that I could see the faces of the lodgers.
The old man—he must have been eighty—held out a greasy scrap of paper,
doubtless his passport, and tried to tell me how little he had done in the
world that was wrong. There was an appealing look in his faded, ancient
eyes, like that in those of a mongrel who would fain beg your mercy. I was
glad to learn that his papers were all right.
Later, the women's ward was also inspected. Here was practically the same
bundle of human flesh and rags. Like the men, the women had to identify
themselves or go to the station house. One young peasant girl lost her head,
or perhaps she could not read. She handed the detective her pass
confidently enough, but when he asked her her name she gave a different
one from that on the passport.
"Go below, you little ignoramus," ordered the officer, and below she went,
obviously wondering why all names were not alike—at least when it came to
identification.
The inspection over, we returned to the room below to count the "catch."
Over a score had been drawn into the net. They were lined up outside
between two rows of policemen, the candles were put out, and the inspector
gave the order to march. The weird, gloomy picture they made in the dark,
as they trudged forward in their rags, is one that I do not care to see again.
It seemed to me then, and it seems to me now, that the scene told the sad,
sad truth about Russia.
"A nation on tramp," I murmured, as my friend and I went on alone down
the Nevsky.
An actual arrest is perhaps the most exciting adventure I have to relate
about my tramp experience in Russia. By rights the arrest should never have
taken place, but what do rights count for in Russia? It came about in this
fashion.
General Kleigels, at that time (1897) prefect of St. Petersburg, had given me
a general letter to the police of that city, reading about like this: "The bearer
of this is Josiah Flynt, an American citizen. He is here, in St. Petersburg,
studying local conditions. Under no circumstances is he to be arrested for
vagabondish conduct." The word "vagabondish" was the nearest English
equivalent my friends could find for the Russian word used; it was
underscored by the general himself. I was told by an American resident in
Russia that with such a letter in my possession I could almost commit
murder with impunity, but I succeeded in getting arrested for a much less
grave offense.
The actual tramping in the city was over, and I was back in my own quarters
again, cleaned up and respectable. One night, three of us, an Englishman,
myself and another American, started out to see the city on conventional
lines. My tramp experience had not revealed much to me about the local
night life, and I boldly took advantage of the opportunity offered by the
American's invitation to see the town as he knew it. In the end, there was
not much to see that I had not looked at time and again in other cities, but
before the end came there was a little adventure that proved very amusing.
During our stroll together the Englishman, a diminutive little chap who had
just bought a new pot hat and wanted everybody to know it, got separated
from us. We looked high and low up and down the street where we had
missed him, but he could not be found. We were about to go to the police
station and give an alarm, when, as we were passing a rather dark stairway,
who should come shooting down it but the Briton, his hat all battered in and
his face bleeding.
"Look at my new Lincoln and Bennett, will you?" he snarled, on reaching the
street, "Sixteen bob gone to the devil!"
We asked him what the row had been about. He didn't know. He merely
remembered that he had gone up the stairs and had been politely received
at the door. "I went into the parlor," he said, "called for drinks, and sat
down. After a while I thought it would be fun to open my umbrella and hold
it over my head. I guess the light must have dazzled me. The next thing, I
was shooting down those stairs. They're bally quick here with their bouncer,
ain't they!"
The American was strong in Russian, and also stood well with the police in
his district, and he was determined that the proprietor of the establishment
should give an account of himself. While he and the Englishman went up the
stairs I remained below in the street, according to agreement, and called at
the top of my voice for a gvardovoi (policeman). Two dvorniks (gate-
keepers, but also police underlings) came running up, and most
obsequiously begged the gospodeen to tell them what was the matter.
Forgetting their police power, I pushed one of them aside, declaring that I
wanted a patrolman and not a house porter. General Kleigels, himself, could
not have taken umbrage at my indiscretion any more hot-headedly. The
dvorniks reached for me instantly, but I ran up the steps to get under the
sheltering wing of the American. The dvorniks followed me, and there was a
long, heated discussion, but in the end I had to go to the police station,
where I absolutely refused to say a single word. The officer searched me,
finding in one of my coat pockets the little Englishman's card. He rubbed it
on my nose, saying: "Vasch? Vasch?" (Yours? Yours?) but I held my tongue
and temper. The man never looked into my hip pockets. In one of them I
had a well-filled cardcase, and in the other might have carried a revolver.
He did not seem to know that hip pockets existed. Pretty soon my
companions joined me, and a long parley ensued between my fellow-
countryman and the officer. Finally my valuables were returned to me, and I
was paroled in my friend's custody until I could produce General Kleigels'
letter. I did this that same day, about three o'clock. It was plain to read in
the officer's face that the document gave him pause. It was probably the
first of the kind that he had ever handled, or that General Kleigels had ever
issued. But he had insulted me, and knew it, and he apparently reasoned
that making any great ado over me or my letter would not help matters if I
intended to make him trouble. So, after he had noted down the date and
number of the letter, he handed it back to me and pronounced me free to go
where I pleased. I shook hands with him, for some strange reason, and I
shall never forget the queer way he looked at me and the manner he had of
doubling two fingers in his palm when taking mine. If this was meant as a
secret sign or signal, it was lost on me.
The wind-up of this little affair with the police was more amusing than the
arrest. Not long afterwards, in company with the American Minister and a
Scotch friend, I went on a fishing and camping trip to Northern Finland.
While we were in camp I received word that I was wanted on a criminal
charge in St. Petersburg, but that there was "no need to worry about it." I
proceeded leisurely with our party up to the Arctic Circle, and then back to
St. Petersburg, when I immediately made inquiry of my house porter about
the summons or indictment. The porter laughed. "It was nothing, sir,
nothing," he assured me. "One week came the indictment, and the next
week the announcement of your acquittal. It was a very simple matter."
I was sure that both proceedings could refer to nothing more serious than
the fracas with the dvorniks on the night of my arrest, and I determined to
learn what had happened to my two friends, if anything. The American I
found at his datscha on one of the islands.
"Did you receive an announcement of your indictment on a criminal charge?"
I asked him.
"Yes," he said; "my crime was whistling in a police station."
It seems that the officer in charge, anxious to have his revenge on one of
us, selected the resident American, because he thought it best not to press
any charge against me and he was unable to locate the little Englishman.
The American had whistled unwittingly, and entirely by way of exclamation. I
recalled the incident. On the fateful night, while he was pleading with the
officer for my release, the latter made several astounding statements, and at
one of them my friend could not repress a slight whistle of amazement. I
asked him how he came out with the case.
"Loser," he said. "I put the matter in the hands of a lawyer, and he mussed
things so that I was fined twenty-five rubles. How did you make out?"
I told him of my acquittal. "There's Russia for you," he declared. "You are at
heart the technical villain and go free. I, the poor Samaritan, am fined.
That's just about as much rhyme and reason as they show in this country in
everything they do."
"And the little Englishman," I asked, "the one who really caused the entire
trouble—where is he?"
"The last I heard of him he was out on one of the Pacific Islands, having a
fine time."
In such ways were spent some of my student days in Europe. That I learned
about Europe and its people during these unconventional experiences as I
never could have learned about them had I spent all of my time in libraries
and the lecture room, seems to me undeniably true. Some of my wanderings
were, in all truth, a submission on my part to the all-demanding passion for
wandering. Yet, as they came along in connection with my university studies,
which kept my mind seriously inclined, I think they did me more good than
harm. I learned to know England, Germany and Russia during these trips. It
was also a good thing for me to be let loose every now and then into the
jungle of Europe's vagabond districts and then vent such lingering
Wanderlust as my temperament retained.
Political economy as a more immediate field of exploration was at times
neglected. Professors Schmoller and Wagner were not listened to as
attentively as they deserved to be. The German university idea of serious
work was frequently disregarded. Perhaps it is furthermore fair to say that in
continuing, as at times I did, my vagabondish explorations in Europe, I was
assisting in perpetuating roving habits. I can now solemnly declare here that
the real roaming habits of former days, roaming habits in the sense that I
was willing at any time when Die Ferne called, to put on my hat and chase
after her—received a complete chill during the European vagabond life. That
it will pay one who desires to know Europe in the underground way, to make
tramp trips such as I did, and to get acquainted before they leave home,
with those millions of emigrants who come to us from Europe, I firmly
believe. Neglected though my political economy was on many a journey,
forgotten though were many of the books, I am not sure that I did not read
my Europe, if not my political economy and other bookish things, better than
I could have done it in written form.
Naturally during my tramp trips and experiences in Europe I made use of
them for purposes of newspaper correspondence, magazine articles and
incidentally for the preparation of such a comprehensive book as I thought I
could write on tramp life in general. In this way these wanderings may again
be called useful, because they helped to increase my powers of observation
from a writer's point of view, and to give a serious purpose to such
investigations on my part. I have no reason to regret any tramp trip made in
Europe, but I am glad now that they are over and done with.
Such training in writing as the reporter gets on his newspaper, I got on
returning to my home in Berlin, and having my "copy" most rigidly cut to
pieces by my mother.
Of course this was not newspaper training in the sense that I had to report,
and to a city editor. But it was all the training I ever had in writing that
amounted to anything, until in after years I was interested enough in the
business to observe for myself, in such examples of good writing as came to
my hand, how, as Robert Louis Stevenson indicates in one of his books,
language may be made to fit most tightly around the subject matter in hand.
CHAPTER XXI
I RETURN TO AMERICA
In the early spring of 1898 I made up my mind once and for all that it was
high time for me to leave Europe and get back to my own country if I ever
intended to get to work with young men in my profession, or in any other
activity in which I might be able to hold my own.
Europe had not palled on me—far from it! To have lingered on in Berlin, in
Rome or in Venice would have pleased me at that time, had I possessed the
necessary means to linger, wander and observe. Had I had financial
independence and no sense of responsibility, I might have been in Europe
to-day as a resident.
In 1898 our country went to war with Spain. How the rumors of war affected
other young Americans studying, traveling, or on business in Europe at that
time, I do not know. In me the rumors of war created an uncontrollable
desire to return to my native land. Perhaps I thought I could go to war in
her defense. It is impossible for me now to analyze, as I should like to do,
my determination in 1898 to get away from Europe, university studies and
all that the life abroad had meant to me, just as quickly as possible. My
mother was aghast at this resolution on my part. She said to me: "If you
were going to China, Kamtchatka, Tibet or almost any other place but
America, I could easily think it a very natural thing to do. But America! I feel
as if I should lose all touch with you."
I suppose that my mother was fearful that on returning to America I would
also return to all the unpleasantness, devilishness and lawlessness which I
had pretty successfully run away from when I shipped as a coal-passer in
Hoboken in 1889, on the poor old steamship Elbe. Furthermore, I think it not
unlikely that my mother herself had lived so long in Europe, and had been
able to keep such close track of me there, that she had a notion that we
were always to live in Europe, and that there I must somehow win or lose.
Then, again, there is no doubt that it disappointed my mother very much
that I would not continue in the university and take my degree.
But something impelled me on my course, and in the spring of 1898 I said
good-by to the university, to Berlin, to Germany and to all Europe as places
in which I desired to cast my lot.
As a mere visitor, I have been back in Europe on several occasions since
1898, but I have never regretted my stubborn decision in that year to return
to my country and make it my abiding place.
In retrospect, it occurs to me, first of all, that the general experience in
Europe, on account of its prolongation, lost for me that personal touch with
young men of my own age who were making their way ahead in America,
and which accounts for so much in getting into the swim of things, making
those friends that avail so much in business or in the professions—in a word,
in growing in your own community with your own people. I stayed too long
in Europe for my own good.
In 1898, in spite of the mysterious and uncontrollable desire to get back to
America, I was for months after my arrival in New York the most Europe-
homesick person imaginable. Whom did I find that knew me? Only a few
friends settled there who had been at my mother's home in Berlin, or that I
had met during my travels. I did not know one of them in any business
capacity here, and not one of them had been acquainted with me in any of
my American homes. I had got acquainted with them in Europe, "on the
march," so to speak.
I think it unfortunate that a boy or young man should linger so long in lands
far removed from his own, when, in the end, he usually must try to amount
to something.
It is again that question of camping, which I referred to in an earlier part of
my story, which is preëminently noticeable in all such American colony life
abroad as I have observed. The colonies are for the most part nothing but
camps, the colonists being only too obviously mere birds of passage.
I do not believe it is a good thing for a young man, whose life is afterwards
to be taken up again in his native land, to spend so much time out of it as I
did. I lost touch with my home generation; I spent the most formative years
of my life in countries where, as it proved, I was not to live and make my
way; I got into lackadaisical ways of looking at things, and I fell to thinking
that living in bachelor quarters on five hundred dollars a year would be an
enviable achievement.
Yet Europe, and particularly Germany, also did me a certain good for which I
must always be grateful. I have already hinted at some of the benefits which
I think I appreciated at the time of their bestowal, and have learned never to
forget. I must certainly thank Europe for a quieting effect on my fiery
unwillingness to see inexorable truths as they must be seen sooner or later. I
must also thank Europe for some most delightful friends and acquaintances.
But where are they now? The great majority are scattered no doubt all over
the world, only a few remaining in my own country for me to enjoy. This is
the pathos of the whole business as I have been through it.
CHAPTER XXII
NEW YORK AGAIN
Taking up life anew in New York City, after many years abroad, is not an
easy game. In my case it was particularly disagreeable, because for a while I
had a homesick feeling for Europe, and I suppose for my particular house in
Berlin. I shall never forget the uncomfortable feeling I had while my ship
was docking as to the outcome of myself and my affairs in this new country
—my country, it is true, but to me a country which I knew very little about
from the beginner's point of view. That I was a beginner, psychologically and
financially, is pretty plain from what I have before said.
I had one consolation. It was a letter from L. F. Loree, then general manager
of the Pennsylvania lines west of Pittsburg, asking me to go to Pittsburg and
see him on a matter of business, the nature of which his letter did not
reveal. There had been a previous letter from this gentleman, received in
Stettin, Germany, just as I was sailing for St. Petersburg, suggesting a
meeting in Pittsburg. This was a number of weeks before my final departure
from Germany for the United States. At that particular time I did not give the
letter its due attention. Russia seemed still to hold out promises which I
thought more attractive than those located in other parts of the world.
On arriving in New York City in 1898, with fifty dollars in my pocket and no
more in sight, I naturally bethought myself of the letter received from Mr.
Loree. I notified him of my modest home-coming, and said that I would be
glad to hear more about the business for me that he had in mind. His reply
was to the effect that I should meet him in Pittsburg, and would there learn
about the matter which he was minded to take up with me. I spent three
days in New York City at the home of a friend. During this time I was "put
up" at a certain club by a friend whom I had learned to know through the
writing business. At this club I met various editors, writers, and, I suppose,
publishers. I was so elated with my sudden elevation into club standing in
the writing business in New York City, that I immediately went back from the
club to the home of my host, and told him in glee what a fine beginning I
had made. Neither he nor his wife seemed to care very much for my sudden
rise in the literary world in New York, via the club end of it. I remember that
they looked at each other very significantly on my telling them with
happiness how I had been so happily received by the writers' craft.
That look made it very pleasant for me to consider other pastures, and the
invitation to proceed to Pittsburg was accepted with alacrity. Arriving there, I
had a few of my fifty dollars left. But there was no immediate prospect of
their remaining in my pocket.
It is not always easy, even though invited to meet him and expecting to
meet him, to find the general manager of a railroad. In my case, what
happened? I found my man out on the road, seeing to it that certain repairs
were made, and that he personally should know that they were made
quickly, and that I must wait a while, perhaps two or three hours, perhaps
longer. Pittsburg and its gloom did not make any plainer to me, during this
waiting spell, what I was in Pittsburg for. I remember that I went to a hotel,
and tried to write an article on that poor miserable creature, the Russian
workingman. In the course of a few hours I was notified by telegram that I
was to proceed to where the repairs were being made, and there make the
general manager's acquaintance. I followed out these instructions, and I
learned to know a man to whom I am indebted for my start in life at home
after those wonderland years in Europe and Asia. I remember that I met my
benefactor in a signal tower where he was patiently waiting for confirmation
that his instructions had been carried out. I remember how he looked at me.
No chief of police has ever "sized me up" the way that general manager did.
He looked into my personality as it is not pleasant to have any one's
personality looked into, unless he believes that he is doing the right thing.
This is only a small incident in our acquaintance, but I have never forgotten
it.
Before long the repairs were completed, the required confirmation of
instructions delivered was received, and Mr. Loree and I returned to
Pittsburg in his car. On the car not a word was said about the business that
he had in mind, and I was careful enough not to disturb a man who had
probably attended to ten things to my one during that day.
In Pittsburg, after supper at the club, we went to the theater and there saw
a light play. Naturally, I could not help guessing about the business that the
general manager had in mind for me. The play over, we returned to the club,
and there, for the first time, I learned what the gentleman wanted.
As I remember his words now, he said to me: "The tramp trouble in the
United States has interested me as a railroad man. I take it that it has
interested you temperamentally and, perhaps, as a student of economics.
"It occurred to me, on taking hold of this railroad property as a general
manager, that I would see whether I could not help to eliminate the tramp
trouble for the railroad as well as for the public. It was not a question in my
mind about the possibility of the tramp being as bad a man as some have
painted him, nor was it the question of doing the honest but unfortunate
and penniless train-rider an injury. The thing I had in mind to do, and have
tried to do, was to clear the property intrusted to my hands of that riffraff
population which has been infesting American railroads for so many years.
"I feel like this. Taken any way you like it, a railroad in a State is one of its
biggest citizens. My position as general manager did not call upon me to
exercise the theoretical notion of a railroad's position as a citizen in a State.
Nevertheless, I said to myself: 'If I clean up my property as regards this
riffraff population I am possibly contributing to the fulfillment of my
citizenship.'"
At these words I looked at my possible employer pretty carefully. I have
never had any reason to believe that as a citizen he has not struggled to do
what, in his mind, seemed to be the right thing. He then and there made an
impression upon me which I shall never forget. Mind you, I had just come
over to this country. It was my business to find something that would make
money for me as soon as possible. Mind you, I had gone to a man who knew
and managed thirty thousand men.
He said to me: "What I wish you would do is to go over the property under
my management, and make such a report as you see fit about the tramp
conditions."
I said to him: "What do you think that will be worth?"
He said: "Well, what do you think it will be worth?"
I needed the money, there was not much more in sight at that time, whether
I went on tramp or not anyhow, and I replied: "Well, I suppose that ten
dollars a day would be an even price."
The general manager replied: "I think that's fair. I suppose you know how to
proceed?"
"I think that I can get back in the old line without much trouble," I returned.
The general manager said: "Go ahead, and find out whatever you can.
Whether the police force that I have instituted has been successful or not in
stopping the tramp evil, I do not know. I say that I do not know because I
cannot possibly be personally on every spot, covering five States, including
thirty thousand men. It is pretty hard to keep track of all that you order to
be done. I am speaking to you purely from the point of view of a railroad
manager. It's pretty hard to run a railroad as you would like to have it run.
This tramp business, this riffraff, this slum population that I find on my lines
is, of course, a detail in the work that has been set before me.
"In my endeavor to keep my lines as clean as possible, not only as a citizen,
but also as a railroader, I have tried to build up a railroad police. The States
through which my lines run protect me only incidentally. I find that when
your friends, the tramps, are arrested by town or village officials they are
easily turned loose. I wanted to know how the situation could be changed,
and I proceeded to look into the matter. The result was that I made up my
mind that the railroad company must protect itself. I found that certain men,
called detectives, were, at times, endeavoring to keep tramps off trains on
our lines. I found, furthermore, that these men, or detectives, were not
attending to their duty as I believe it should be attended to.
"Consequently I got to wondering how this matter could be better attended
to. I looked over the expense accounts for police purposes, and found that
our people were paying what seemed to me an exorbitant sum for very poor
service. It seemed to me that police matters on a railroad, on account of the
negligence on the part of villages and towns, should be organized and given
a standing, which, on account of our lackadaisical procedure against crime in
this country, was justified.
"You will find on our property a certain number of qualified policemen.
Perhaps I should say 'patrolmen.' We do not use the word detective on this
property. They are divided up according to divisions, and the moral
deportment of the different communities in which they are placed. My idea
has been to try to police our property just as a city is policed.
"What I should like to have you do is to go over our property and see
whether our police force has been successful in ridding our lines, and, to
some extent, the communities which they touch, from tramp immigration.
How do you feel about the matter?"
Here was a problem which led right back into all that land of Wanderlust
which I supposed that I had given up in so far as it applied to tramp life.
However, as so many well-known people say: "Beggars cannot be choosers,"
I undertook the job of finding out for the general manager exactly what the
tramps had to say about his lines as protected by his police. Eighteen years
before this interview, the general manager's lines, to my own knowledge,
were so littered up with tramps, and tramp camps that the Fort Wayne road
in particular then was known as an "easy" road to beat between Chicago and
Pittsburg. It was as bad as the Baltimore and Ohio Railroad, which in those
days was called "The Dope."
These roads were ridden promiscuously by all kinds of men, women and
children who did not pay fare. When they got into a box car they thought
much nonsense. The things that were done and said among all these people
at that time would make too scandalizing reading now. If there are slums in
our cities, there are no greater slums anywhere in the world, barring no
crime, passion, or idiosyncracy, than were found on the "Dope" and the Fort
Wayne roads in my tramp days.
I looked over the general manager's property. Dressed as a tramp, acting as
a tramp, living and sleeping as a tramp, I surrounded his lines until I knew
what the tramp world had to say about his railroad police idea. I found
wherever I went, in Cleveland, Chicago, Cincinnati, Wheeling, or Pittsburg,
that tramps said: "There are easier roads to beat than the Fort Wayne."
It was hard work to go back into tramp life. I had some hard knocks, as
regards storms and other misadventures in various places. Yet, with it all, it
brought back to me a number of remembrances of earlier tramp days.
At the end of one month on the "Road" I went to the general manager and
told him that I had no desire to ride his trains—that there were so many
other trains and roads that were easier. I believed that, in order to complete
my investigations, if he cared to have me proceed further, I should have a
pass, good on every movable thing that he had on his property. We
discussed this matter in some detail. Eventually, the general manager
consented to my proposition, and I was given a pass, good over all his lines,
and I had with me the moral support of his position.
I tackled the tramp problem from a new point of view. It was my privilege to
ride on practically every passenger train, every freight train, and on all
engines that it should be my fate to meet. The general manager also gave
me a letter instructing his employees to let me pass. I now know that it
puzzled the general manager's police force to comprehend my compromising
position on the road. The police force said: "Who is this young fellow out
here looking us up?"
I was called to order one night, in Ohio, by a captain of the newly instituted
police force, for riding on a caboose of a freight train. I was getting off the
caboose to find out about something which was a matter of detail at the
time, and had got back to the steps of the caboose, when the captain
stepped up to me and said: "What are you doing on this train?" I looked at
him. He looked at me. We then and there decided that there was no
particular disagreement between us. But I have to say that during the
second month of my investigations for the general manager, his police force
could not make out why I was on the property with all my credentials, and
my confusing diminutive form and face. One of my best friends to-day, who
was then at the head of the police, was interested in my proceedings.
As an illustration of how men keep track of each other, he had his men keep
track of me. At the same time, I think he must have realized that our
superior officer was behind such an errand as I was on. He had the good
sense to say to himself: "Well, if that is the Boss's work, I'd better leave it
alone." But he kept his men looking out for me, which is only human nature.
One of the experiences that I had during this second month in the interests
of railroading, so far as its traffic applies to tramps, occurred in Ohio. During
my extraordinary privileges as a railroading tramp, and with all my
credentials from the general manager's office, I picked up a freight train
going west of Mansfield, Ohio, upon which I nevertheless found myself in
difficulties. I saw three tramping negroes on this train. I saw them get on
the train—largely a coal train so that one could see from the caboose
window exactly what was going on—and went after them, car after car full
of coal, until I reached the biggest of the three. The train was going at the
rate of about twenty miles an hour. I snatched the hat of the biggest one
that I could see and said, with some reminiscences in mind, I must confess:
"You have your nerve with you, riding on this road. Hit the gravel."
The negro looked up at me, as if all the majesty of the law had been
suddenly invested in my humble person, and said, with a truly pathetic
tramp touch: "Cap, the train is going a little too hard." He received back his
hat, and he and his two companions were asked by me, in no uncertain
terms, to leave the train at a certain siding.
I made up my mind that those three negroes should get no train leaving the
siding—a resting place for tramps, and for trains that needed coal and steam
to go farther on. I went to the signal tower and telegraphed east and west
for an officer to get to the signal tower in question and arrest the
trespassers as soon as possible. This may seem a hard thing for a man to
do, who had been through what I had. But I was responsible to the general
manager of that property. I was also responsible to my own idea of integrity,
and I believed in my inmost soul that it was the thing to do.
The negroes wanted to fight me. I was carrying a toothbrush at the time.
While at the coaling station the negroes lingered around and made every
effort to catch every freight train that was going out their way. I rode every
one of these going in their direction to within about one hundred yards of
their waiting place. Finally, the last "run," as they well knew, had gone. As I
dropped off the last freight train that they were not swift enough to catch, I
walked toward them, and was greeted with these words: "Do you think you
run this road? If you do, you'll get a bullet hole through you so soon that
you won't know what struck you."
I thought of my toothbrush as the only weapon I had. I thought also of the
willingness on the part of those negroes to revenge themselves, and I
thought still more closely about the distance between where I stood and the
coaling station. It so happened that my bluff went. I said to the negroes: "If
there is any shooting to be done here I'll begin it." The negroes left me
alone, and I left them alone. I could not, however, get over the idea that
they had infringed on my territory as investigator, police officer, or anything
else that you want to call it. The result of the experience was that the police
officer that I had telegraphed for toward the east appeared at the coaling
station as soon as he could, and that we rode on together to the next
village. There I said to him: "I think we will catch those negroes not very far
away from here." He picked up the town marshal and away we went down
the track to find those negroes. We found them.
Dusk was just coming on, and they were sitting alongside the track. The
policeman from the east drew his revolver, went up to them, and said, much
to their surprise: "I place you under arrest." The negroes wilted, and all of
us went to the station house of the nearest village. They were given an
immediate hearing. They said that they had not been seen on any train,
other than a passenger train on which they had paid their fares, during all
the years of their existence. The justice said: "Do you suppose that that man
is going to come here and tell me that he saw you on a certain freight train
when he didn't see you on that freight train?"
One of the negroes replied: "I never saw that man before in my life." This
was the man whose hat I had taken when I told him to get off the train. The
justice gave all three a thirty-day sentence to the Canton Workhouse. The
next morning, the negroes were prisoners of the local authorities. By these
local authorities they were handcuffed, put on a train, and started for their
destination. Foolishly, I not only followed them in Canton, but I went up with
them, in the street car, to the workhouse. During that ride I heard all the
hard things that can possibly be said about any one.
This experience and my participation in it may not seem so very creditable to
one who had himself been a tramp. But what did I learn about those
negroes? They had been employees of a circus, had got drunk and into a
row, and had left their positions as circus men. So far as I have been able to
make out, they had no right to have a free ride anywhere.
This is merely one of the incidents that fell to my lot during the second
month. Of course there were many others, which interested me at the time,
to think over, but which would not interest the reader.
The main thing I learned to believe in and expect in my general manager
was a great efficiency. All through my tramp experiences at his request, I
found, even in tramp life, that the great thing is getting there and doing
something. My report to him about the general ability of the police force,
which he and his subordinates had got together for the purpose of
completely ridding the property of the tramp nuisance, was that I thought he
had at least got the Fort Wayne road so cleaned up, in that respect, that no
"respectable" tramp would ride on it. In making this report I said to the
general manager: "They are stealing coal on the Lake Shore Railroad. There
is a man who told me that on the Lake Shore Railroad every twentieth train,
before it gets forty miles out of Buffalo, gets dug into." On that same
expedition for the general manager I ran up against two tramp camps at the
end of one of the "Short Lines" at Ashtabula. My interest at that time was
not to disturb either camp at all. I went down to the Lake Shore Railroad,
toward their coal chutes, and there I found two camps. The fires of these
were being bountifully supplied by coal taken from the adjoining railroad
company. My position was peculiar. Tramps, and criminals for that matter, do
not like to have any one approach what they believe to be their property. I
went to one of the camps, and sat down on a railroad tie. Pretty soon a
person of unquestionable importance in his own tramp line, said to me:
"Have you a match?"
"I think I have. I'll see."
"If you find one, go over and build your own fire."
I did so, and was left more or less in peace
CHAPTER XXIII
RAILROAD EXPERIENCES
At that time there was a collection of men, called the "Lake Shore Push."
These men thought that they had the Lake Shore Railroad in their hands,
from the criminal end of it, or, perhaps, I should say, the hold-up end of it.
Their history is a matter hard to explain. They had been known on or about
the Lake Shore Railroad, to my knowledge, for twenty years easily.
They are worth while considering in a paragraph or two as showing how
criminal "mobs" are made up.
The Lake Shore Railroad for some reason or other has been infested with
box-car robbers, hold-up men, for about the number of years suggested. For
some reason, the Lake Shore gang found it convenient to organize itself in
so far as organization is possible in criminal life. Criminals of different types
got together, and said: "We will run this road as we think it should be run
according to our ways of looking at things." The management of the road
had nothing to say that was of any use.
So the Lake Shore gang proceeded, and robbed cars, even threw a steer off
a car when it wanted to hold a barbecue, held up the polite Ohio politician
beating his way to the extent of forty cents, had all those plants supposed to
be between Buffalo and Chicago, and generally made themselves a criminal
nuisance.
The Lake Shore gang consisted of the following types: the desperate
laboring man (?) who is willing to grapple with your throat on account of a
dollar or two—I mean the hold-up man that you hear so much about in the
Middle West; the discouraged criminal who knew that he was discouraged,
but thought he might possibly, under spurious cover, get a "stake" on
professionally criminal lines; the hard-up man who was led along by the
other conspirators in the game; the boy of eighteen, who had made some
miserable mistake in his home, had to get away from that home, and had
fallen into the hands of scheming men; and the woman of the street who
had her reasons for knowing anything about the Lake Shore gang. The Lake
Shore gang, it can be said, grew out of the idea that when you can be
imposed upon, you will stand for it. What they are doing now I do not know.
It may be that they are amusing themselves as in days of old. All I want to
say here is that this was the company I had good chances of falling in with
when striking the general manager's terminals on the lakes. The Lake Shore
Railroad and the Nickel Plate, as it was called, took up the full responsibility
of all tramp nonsense after certain department heads had done their best to
relieve both of these roads of pronounced deficiencies and crimes.
As I have said, I found that, at Ashtabula, the tramps were burning up the
Lake Shore Company's coal, the Nickel Plate Company's coal—put the two
together and call them the Vanderbilt lines if you like—and that the Lake
Shore gang were robbing people right and left on every freight train that
went over the Vanderbilt lines. I found also that the Vanderbilt lines did not
pay the slightest respect to the protection of their patrons, as regards
pickpockets and other gentry of that character, on their passenger trains,
otherwise than by employing a man who feverishly ran up and down their
territory—let us say between Toledo and Cleveland—took his lunches where
he could buy them for from ten to twenty-five cents, and tried to carry out
the whole game for the Vanderbilt interests between the points mentioned.
This man was supposed to be the police force of that district. The reason he
took so many quick lunches is because he had too much to do. In some
ways, I believe that he tried to serve the Vanderbilt interests. But no man
can cover such a district, if he be all alone—as it is alleged that he was—and
attend to all of the details that will come up in police life on the Vanderbilt
lines or on any other line.
This man I did not meet. I heard about him, from time to time, taking
hungry lunches on the Lake Shore trains, passenger and freight.
This man, so far as the public is concerned, passenger or freight, did no
more to protect the public than does a mosquito in New Jersey when it tries
mercenary intentions upon an innocent suburbanite. In my opinion, the Lake
Shore Railroad, in its employ of this one man to cover so much territory, did
not honestly stand up as a citizen in our United States.
My employer, the general manager, had in mind something else.
He is the man, who, when the Johnstown flood occurred, built the railroad
bridge over the turbulent river in twenty-four hours. In saying that he built
it, I mean that he knew how to get men to help him build it.
The same determination that he had in building that bridge, the same
character, came out in his determination that his railroad line, so far as he
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like