0% found this document useful (0 votes)
9 views

Programming In C With Microsoft Visual Studio 2010 Student Manual download

The document provides a comprehensive guide on programming in C# using Microsoft Visual Studio 2010, covering various modules from introducing C# to advanced topics like LINQ and operator overloading. It includes lessons, labs, and best practices for encapsulating data, handling exceptions, and managing resources. Additionally, it offers links to related resources and products for further learning in C programming and Visual Studio.

Uploaded by

labaroliurdc
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
0% found this document useful (0 votes)
9 views

Programming In C With Microsoft Visual Studio 2010 Student Manual download

The document provides a comprehensive guide on programming in C# using Microsoft Visual Studio 2010, covering various modules from introducing C# to advanced topics like LINQ and operator overloading. It includes lessons, labs, and best practices for encapsulating data, handling exceptions, and managing resources. Additionally, it offers links to related resources and products for further learning in C programming and Visual Studio.

Uploaded by

labaroliurdc
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

Programming In C With Microsoft Visual Studio

2010 Student Manual download

https://ebookbell.com/product/programming-in-c-with-microsoft-
visual-studio-2010-student-manual-2581034

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Ms 10266a Programming In C With Visual Studio 2010 Vol 1 Student


Manual

https://ebookbell.com/product/ms-10266a-programming-in-c-with-visual-
studio-2010-vol-1-student-manual-2581036

Ms Course 10266a Programming In C With Microsoft Visual Studio 2010


Trainer Edition Volume 1 Microsoft

https://ebookbell.com/product/ms-course-10266a-programming-in-c-with-
microsoft-visual-studio-2010-trainer-edition-
volume-1-microsoft-2113632

Ms Course 10266a Programming In C With Microsoft Visual Studio 2010


Trainer Edition Volume 2 Microsoft

https://ebookbell.com/product/ms-course-10266a-programming-in-c-with-
microsoft-visual-studio-2010-trainer-edition-
volume-2-microsoft-2113634

Programming In C With Visual Stdio 2010 Lab Manual

https://ebookbell.com/product/programming-in-c-with-visual-
stdio-2010-lab-manual-1547090
Parallel Programming In C With Mpi And Openmp Michael Jay Quinn

https://ebookbell.com/product/parallel-programming-in-c-with-mpi-and-
openmp-michael-jay-quinn-2438258

Functional Programming In C With Categories 221 Dimitris Papadimitriou

https://ebookbell.com/product/functional-programming-in-c-with-
categories-221-dimitris-papadimitriou-46704096

An Introduction To Objectoriented Programming In C With Applications


In Computer Graphics 2nd Edition Graham M Seed Beng

https://ebookbell.com/product/an-introduction-to-objectoriented-
programming-in-c-with-applications-in-computer-graphics-2nd-edition-
graham-m-seed-beng-4198618

Handson Network Programming With C Learn Socket Programming In C And


Write Secure And Optimized Network Code 1st Edition Lewis Van Winkle

https://ebookbell.com/product/handson-network-programming-with-c-
learn-socket-programming-in-c-and-write-secure-and-optimized-network-
code-1st-edition-lewis-van-winkle-55536756

Handson Network Programming With C Learn Socket Programming In C And


Write Secure And Optimized Network Code Lewis Van Winkle

https://ebookbell.com/product/handson-network-programming-with-c-
learn-socket-programming-in-c-and-write-secure-and-optimized-network-
code-lewis-van-winkle-11074026
OFFICIAL MICROSOFT LEARNING PRODUCT

10266A
Programming in C# with
Microsoft® Visual Studio® 2010

Be sure to access the extended learning content on your Course


Companion CD enclosed on the back cover of the book.
ii Programming in C# with Microsoft® Visual Studio® 2010

Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, place or event is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part
of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted
in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for
any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.

The names of manufacturers, products, or URLs are provided for informational purposes only and
Microsoft makes no representations and warranties, either expressed, implied, or statutory,
regarding these manufacturers or the use of the products with any Microsoft technologies. The
inclusion of a manufacturer or product does not imply endorsement of Microsoft of the
manufacturer or product. Links may be provided to third party sites. Such sites are not under the
control of Microsoft and Microsoft is not responsible for the contents of any linked site or any link
contained in a linked site, or any changes or updates to such sites. Microsoft is not responsible for
webcasting or any other form of transmission received from any linked site. Microsoft is providing
these links to you only as a convenience, and the inclusion of any link does not imply endorsement
of Microsoft of the site or the products contained therein.
© 2010 Microsoft Corporation. All rights reserved.

Microsoft, and Windows are either registered trademarks or trademarks of Microsoft Corporation in
the United States and/or other countries.
All other trademarks are property of their respective owners.

Product Number: 10266A

Part Number: 01918

Released: 09/2010
Programming in C# with Microsoft® Visual Studio® 2010 v

Contents
Module 1: Introducing C# and the .NET Framework
Lesson 1: Introduction to the .NET Framework 4 1-4
Lesson 2: Creating Projects Within Visual Studio 2010 1-16
Lesson 3: Writing a C# Application 1-33
Lesson 4: Building a Graphical Application 1-44
Lesson 5: Documenting an Application 1-58
Lesson 6: Debugging Applications by Using Visual Studio 2010 1-66
Lab: Introducing C# and the .NET Framework 1-78

Module 2: Using C# Programming Constructs


Lesson 1: Declaring Variables and Assigning Values 2-4
Lesson 2: Using Expressions and Operators 2-23
Lesson 3: Creating and Using Arrays 2-36
Lesson 4: Using Decision Statements 2-49
Lesson 5: Using Iteration Statements 2-63
Lab: Using C# Programming Constructs 2-78

Module 3: Declaring and Calling Methods


Lesson 1: Defining and Invoking Methods 3-3
Lesson 2: Specifying Optional Parameters and Output Parameters 3-29
Lab: Declaring and Calling Methods 3-39

Module 4: Handling Exceptions


Lesson 1: Handling Exceptions 4-3
Lesson 2: Raising Exceptions 4-23
Lab: Handling Exceptions 4-34
vi Programming in C# with Microsoft® Visual Studio® 2010

Module 5: Reading and Writing Files


Lesson 1: Accessing the File System 5-3
Lesson 2: Reading and Writing Files by Using Streams 5-27
Lab: Reading and Writing Files 5-45

Module 6: Creating New Types


Lesson 1: Creating and Using Enumerations 6-3
Lesson 2: Creating and Using Classes 6-12
Lesson 3: Creating and Using Structures 6-33
Lesson 4: Comparing References to Values 6-41
Lab: Creating New Types 6-55

Module 7: Encapsulating Data and Methods


Lesson 1: Controlling Visibility of Type Members 7-4
Lesson 2: Sharing Methods and Data 7-15
Lab: Encapsulating Data and Methods 7-29

Module 8: Inheriting from Classes and Implementing Interfaces


Lesson 1: Using Inheritance to Define New Reference Types 8-3
Lesson 2: Defining and Implementing Interfaces 8-27
Lesson 3: Defining Abstract Classes 8-45
Lab: Inheriting from Classes and Implementing Interfaces 8-56

Module 9: Managing the Lifetime of Objects and Controlling Resources


Lesson 1: Introduction to Garbage Collection 9-4
Lesson 2: Managing Resources 9-21
Lab: Managing the Lifetime of Objects and Controlling Resources 9-35

Module 10: Encapsulating Data and Defining Overloaded Operators


Lesson 1: Creating and Using Properties 10-4
Lab A: Creating and Using Properties 10-26
Lesson 2: Creating and Using Indexers 10-38
Lab B: Creating and Using Indexers 10-50
Programming in C# with Microsoft® Visual Studio® 2010 vii

Lesson 3: Overloading Operators 10-60


Lab C: Overloading Operators 10-79

Module 11: Decoupling Methods and Handling Events


Lesson 1: Declaring and Using Delegates 11-4
Lesson 2: Using Lambda Expressions 11-14
Lesson 3: Handling Events 11-22
Lab: Decoupling Methods and Handling Events 11-38

Module 12: Using Collections and Building Generic Types


Lesson 1: Using Collections 12-4
Lab A: Using Collections 12-22
Lesson 2: Creating and Using Generic Types 12-28
Lesson 3: Defining Generic Interfaces and Understanding Variance 12-42
Lesson 4: Using Generic Methods and Delegates 12-56
Lab B: Building Generic Types 12-69

Module 13: Building and Enumerating Custom Collection Classes


Lesson 1: Implementing a Custom Collection Class 13-3
Lesson 2: Adding an Enumerator to a Custom Collection Class 13-21
Lab: Building and Enumerating Custom Collection Classes 13-37

Module 14: Using LINQ to Query Data


Lesson 1: Using the LINQ Extension Methods and Query Operators 14-3
Lesson 2: Building Dynamic LINQ Queries and Expressions 14-28
Lab: Using LINQ to Query Data 14-47

Module 15: Integrating Visual C# Code with Dynamic Languages and COM
Components
Lesson 1: Integrating Visual C# Code with Ruby and Python 15-4
Lesson 2: Accessing COM Components from Visual C# 15-19
Lab: Integrating Visual C# Code with Dynamic Languages and COM
Components 15-36
viii Programming in C# with Microsoft® Visual Studio® 2010

Appendix: Lab Answer Keys


Module 1 Lab: Introducing C# and the .NET Framework L1-1
Module 2 Lab: Using C# Programming Constructs L2-1
Module 3 Lab: Declaring and Calling Methods L3-1
Module 4 Lab: Handling Exceptions L4-1
Module 5 Lab: Reading and Writing Files L5-1
Module 6 Lab: Creating New Types L6-1
Module 7 Lab: Encapsulating Data and Methods L7-1
Module 8 Lab: Inheriting from Classes and Implementing Interfaces L8-1
Module 9 Lab: Managing the Lifetime of Objects and Controlling
Resources L9-1
Module 10 Lab A: Creating and Using Properties L10A-1
Module 10 Lab B: Creating and Using Indexers L10B-1
Module 10 Lab C: Overloading Operators L10C-1
Module 11 Lab: Decoupling Methods and Handling Events L11-1
Module 12 Lab A: Using Collections L12A-1
Module 12 Lab B: Building Generic Types L12B-1
Module 13 Lab: Building and Enumerating Custom Collection Classes L13-1
Module 14 Lab: Using LINQ to Query Data L14-1
Module 15 Lab: Integrating Visual C# Code with Dynamic Languages
and COM Components L15-1
Encapsulating Data and Defining Overloaded Operators 10-1

Module 10
Encapsulating Data and Defining Overloaded
Operators
Contents:
Lesson 1: Creating and Using Properties 10-4
Lab A: Creating and Using Properties 10-26
Lesson 2: Creating and Using Indexers 10-38
Lab B: Creating and Using Indexers 10-50
Lesson 3: Overloading Operators 10-60
Lab C: Overloading Operators 10-79
10-2 Programming in C# with Microsoft® Visual Studio® 2010

Module Overview

Nearly every application you develop will require you to develop at least one type
to represent some entity. Types typically expose methods and data. A simple
approach to exposing data is to make the fields used by your class public; however,
this is often bad practice—or at least is not the most secure, efficient, or natural
technique.
For example, providing an array-like syntax may be a better approach when
accessing data in a class that stores a collection of data. Similarly, if a class exposes
a member that should have only read-only access, exposing a field publicly
provides both read and write access. This module will introduce you to properties
and indexers. These are elements of Microsoft® Visual C#® that enable you to
encapsulate data and expose data appropriately and efficiently.
Another syntax you will commonly use is that associated with operators. For
example, it is intuitive to write 2 + 3 and expect that the result will be 5. Similarly,
you will probably expect "Hello"+ "World" to return the concatenated string
"HelloWorld". Many operators have well-defined behavior for the built-in Visual C#
types, but you can also define operators for your own types. This module describes
how to implement operators for your types by using overloading.
Encapsulating Data and Defining Overloaded Operators 10-3

Objectives
After completing this module, you will be able to:
• Explain how properties work and use them to encapsulate data.
• Describe how to use indexers to provide access to data through an array-like
syntax.
• Describe how to use operator overloading to define operators for your own
types.
10-4 Programming in C# with Microsoft® Visual Studio® 2010

Lesson 1
Creating and Using Properties

You can use properties to provide controlled access to the data in a type. This
lesson introduces you to properties and shows you how to define them in your
types. It also explains why you should use this approach to encapsulate data.

Objectives
After completing this lesson, you will be able to:
• Describe the purpose of properties.
• Implement properties.
• Explain automatic properties.
• Instantiate an object by using properties.
• Define properties in an interface.
• Describe the best practices relating to properties.
Encapsulating Data and Defining Overloaded Operators 10-5

What Is a Property?

Key Points
A property is a cross between a field and a method. You use field-like syntax to
access a property. However, the behavior of a property is more like a method.
A property can contain two elements:
• A get accessor, which an application can use to read the property value.
• A set accessor, which an application can use to change the property value.

Properties are a common way of encapsulating data exposed by your class.


Normally a property is mapped to a private field in your type. The field stores the
data, and the get and set accessors of the property provide a mechanism for
accessing that field. You are not obliged to provide both a get and a set accessor, so
properties have the advantage that you can control whether to make a property
read-only, write-only, or make the property readable and writeable which you
cannot do by exposing a field.
Another advantage of using a property is the ability to validate data. If you expose a
field in your type, any other type can read or write to that field. As long as the data
10-6 Programming in C# with Microsoft® Visual Studio® 2010

is of the right type, any value can be assigned to that field. This is not always
logical; sometimes you may need to restrict the range of acceptable values for a
field in your type. With a property, you can add logic to the set accessor to check
that a value falls in the expected range before updating the private field.
Although properties normally map to private fields, there is no requirement for
them to do so. The get accessor of a property can return a calculated value, a
constant value, or perform any other operation applicable to your application.
Properties will often include additional logic; for example, if you update a file name
by using a property, the property may check whether the file is currently in use
and, if necessary, rename the file or open a new file according to the requirements
of the application.

Question: How does the behavior of a method differ from a property?

Additional Reading
For more information about properties, see the Properties (C# Programming
Guide) page at http://go.microsoft.com/fwlink/?LinkId=192948.
Encapsulating Data and Defining Overloaded Operators 10-7

Defining a Property

Key Points
A property has a type and a name, in much the same way as a field. However, the
logic for a property is defined by the get and set accessors.
The get accessor, like a method, can include any code; however, it must return an
object of the type specified by the property or throw an exception. The set accessor
does not have to perform any function—although normally, you update a private
field to perform some operation based on the value passed to the property. You do
not specify a parameter for the set accessor; a set accessor always takes one
parameter of the type exposed by the property. You can access the object passed as
a parameter to a set accessor by using the value keyword.
The following code example shows how to define a simple property that provides
access to a private field. The get keyword introduces a code block that defines the
code that runs when an application reads the property. The set keyword defines
the code block for the logic that runs when an application assigns a value to the
property.
10-8 Programming in C# with Microsoft® Visual Studio® 2010

private string myString;

public string MyString


{
get
{
return this.myString;
}
set
{
this.myString = value;
}
}

To define a read-only property, you simply omit the set accessor. Similarly, to
define a write-only property, do not implement a get accessor.

Defining Property Accessibility


When you define a property, you specify the access modifier for that property. The
access modifier that you specify for a property is inherited by the get and set
accessors. You can override the access modifier for either the get or set accessor;
however, you cannot make an accessor more accessible than the containing
property. For example, you cannot make the get accessor public if the property is
private.
The following code example shows how to modify the accessibility level at the
accessor level.

public string MyString


{
get
{
return this.myString;
}
private set
{
myString = value;
}
}

Using a Property in a Consuming Class


You use a property in a consuming class by using the dot notation in the same way
as you access a public field. The following code example shows how to access the
MyString property from the previous code example. Internally, the Visual C#
Encapsulating Data and Defining Overloaded Operators 10-9

compiler converts all attempts to read the property into calls to the get accessor
and changes all attempts to write the property into calls to the set accessor.

MyObject theClass = new MyObject;

// Setting the string – calls the set accessor


theClass.MyString = "Property set.";

// Getting the string – calls the get accessor


Console.WriteLine(theClass.MyString);

Note: You can define static properties, but they can only access static data.

Question: How can you enable write access to a property to other types in the
same assembly, but read access to a property from a class in any assembly?

Additional Reading
For more information about using properties, see the Using Properties (C#
Programming Guide) page at http://go.microsoft.com/fwlink/?LinkId=192949.
10-10 Programming in C# with Microsoft® Visual Studio® 2010

Automatic Properties

Key Points

When you develop a new type, you may include a data field that you want to
expose to applications. If no additional processing or validation is required on that
field, it may be tempting to simply expose the field publicly instead of adding a
property to provide access to that field.
In this case, exposing a field may not seem like a problem. However, remember
that you cannot add code to prevent invalid values in a field but you can in a
property. Whether you need to add validation or other logic to a property when
you originally develop a type does not mean that will always be the case. The
requirements of your type may change over the lifetime of the application.
From a developer's perspective, using a property is exactly the same as using a
field; however, this is not true to the compiler. The compiler converts code that
accesses a property into a method call to the get accessor, and it similarly converts
writing to a property to a method call to the set accessor. This has implications for
existing applications if you must convert a field to a property at a later date; any
application that used the type with the value exposed as a field must be recompiled
Encapsulating Data and Defining Overloaded Operators 10-11

with the data exposed through a property. If this type is in an assembly used by a
number of applications, you may need to rebuild and redeploy a lot of
installations.
You can avoid this extra work by simply exposing the data through a property
when you originally develop the type. Any future changes to the type can then be
made without the need to recompile applications that consume your type.
Where you must expose a field, and are tempted to simply make the field public
rather than writing a property to get and set the field, you can use automatic
properties.
Automatic properties provide a simple inline syntax that converts a field to a
property. To use automatic properties, you simply add curly braces that contain
both set and get accessors, each followed by a semicolon, as the following code
example shows.

public string Name { get; set; }

When you use an automatic property, the compiler creates a private field and
automatically generates code to read and write this field, as the following code
example shows.

private string _name;

public string Name


{
get
{
return this._name;
}
set
{
this._name = value;
}
}

Note: Automatic properties always define both a get and set accessor. Automatic
properties are intended for use where otherwise you would simply expose a public field.
If you require more specific control over the data, you must write the property manually.
It does not make any difference to consuming classes if you change from an automatic
property to a manual property in a later build of your code; they are completely
interchangeable, unlike properties and fields.
10-12 Programming in C# with Microsoft® Visual Studio® 2010

Question: What is the benefit of using an automatic property compared to


exposing a public field?
Encapsulating Data and Defining Overloaded Operators 10-13

Instantiating an Object by Using Properties

Key Points
You have previously seen how to use a constructor to instantiate an object and
initialize its fields. You can declare several constructors, with different signatures,
to enable other developers to set various combinations of fields in your type to
appropriate values; however, this approach is problematic if you have more than a
small number of fields or several properties of the same type.
The following code example shows a simple class with several constructors.

class Employee
{
private string name;
private string department;

// Initialize both fields


public Employee(string empName, string empDepartment)
{
this.name = Name;
this.department = Department;
}
10-14 Programming in C# with Microsoft® Visual Studio® 2010

// Initialize name only


public Employee(string empName)
{
this.name = empName;
}

// Initialize department only


public Employee(string empDepartment)
{
this.department = empDepartment
}
...
}

The intention of the constructors is to enable an application to specify a value for


the employee name, department name, or both when it creates a new Employee
object. However, this code will not compile because the compiler cannot
distinguish between the two constructors that take a single string parameter. If you
attempt to instantiate an Employee object by using the code shown in the
following code example, the compiler does not know which constructor to use.

// Is "Fred" the name of an employee or a department?


Employee myEmployee = new Employee("Fred");

You can resolve this problem by using properties to initialize the object when you
instantiate it. This syntax is known as an object initalizer. With an object initializer,
you create a new object by using a constructor, but you specify the values to assign
to properties after the constructor has completed by using property name/value
assignment pairs separated by commas and enclosed in curly braces.
The following code example shows how to define a class that supports object
initializers and how to create an object by using them.

class Employee
{
// Default constructor.
public Employee()
{
...
}

// Constructor that sets the grade of an employee.


public Employee(int grade)
{
...
}
Encapsulating Data and Defining Overloaded Operators 10-15

// Expose Name and Department as automatic properties.


public string Name { get; set; }
public string Department { get; set; }
...
}

// Instantiating an object and setting a single property.


Employee louisa = new Employee() { Department = "Technical" };

// Instantiating an object and setting a single property.


// You do not have to add the brackets to use the default constructor.
Employee john = new Employee { Name = "John" };

// Instantiating an object and setting a multiple properties.


// Separate properties with a comma.
Employee mike = new Employee
{
Name = "Mike",
Department = "Technical"
};

In the first example, (louisa), the default constructor is used to create the
Employee object. After the object is created and the constructor has finished, the
value "Technical" is assigned to the Department property. Note that if you use the
default constructor, you can omit the brackets (), as the second example (john)
and the third example (mike) illustrate.
If the Employee class has a nondefault constructor, you can invoke that together
with an object initializer, as the following code example shows. This code example
uses the constructor that sets the grade of an employee.

Employee antony =
new Employee(2) { Name = "Antony", Department = "Management" };

When you use an object initializer, the constructor logic runs first, and then the
properties are set to the values specified in the object initializer. This means that if
you set a property in a constructor, and then set the same property in the object
initializer, the value from the object initializer will overwrite the value set by the
constructor.

Hint: You should only define constructors that set any required properties to default
values. Classes that consume your type can then override those properties in an object
initializer.
10-16 Programming in C# with Microsoft® Visual Studio® 2010

Question: Why is it important to instantiate required properties to default values


in the constructor?
Encapsulating Data and Defining Overloaded Operators 10-17

Defining Properties in an Interface

Key Points
An interface defines a contract that specifies the methods that a class should
implement. An interface can also define properties. However, the implementation
details of these properties (such as the fields they reference, if any) are the
responsibility of the class.
To add a property to an interface, you use the same syntax as an automatic
property, except you cannot specify an access modifier. The following code
example shows properties added to an interface.

interface IPerson
{
string Name { get; set; }
int Age { get; }
DateTime DateOfBirth { set; }
}

Classes that implement an interface that includes properties can implement the
properties implicitly or explicitly.
10-18 Programming in C# with Microsoft® Visual Studio® 2010

The following code example shows the IPerson interface implemented implicitly.

class Person : IPerson


{
public string Name
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}

public int Age


{
get { throw new NotImplementedException(); }
}

public DateTime DateOfBirth


{
set { throw new NotImplementedException(); }
}
}

The following code example shows the IPerson interface implemented explicitly.

class Person : IPerson


{
string IPerson.Name
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}

int IPerson.Age
{
get { throw new NotImplementedException(); }
}

DateTime IPerson.DateOfBirth
Encapsulating Data and Defining Overloaded Operators 10-19

{
set { throw new NotImplementedException(); }
}
}

Question: When should you add a property to an interface?

Additional Reading
For more information about defining properties in an interface, see the Interface
Properties (C# Programming Guide) page at
http://go.microsoft.com/fwlink/?LinkId=192950.
10-20 Programming in C# with Microsoft® Visual Studio® 2010

Best Practices When Defining and Using Properties

Key Points
Properties provide an excellent framework for exposing data from types you
develop; however, if you do not use properties appropriately, you risk introducing
bugs or simply exposing properties that enable consuming classes to perform
undesirable behavior. You can mitigate the risks by following some best practices.

Using Properties Appropriately


It would be easy to say you should always expose a property for every field in types
that you develop; however, this is not necessarily good practice. You should
carefully consider whether exposing a property is appropriate to the types of
operations an application can perform on a data item.
For example, if you are developing a type to represent a bank account, a field in the
class can represent the balance of the account. It may be tempting to provide a
property that enables an application to read and write the account balance, but this
does not reflect the real-world operations that a bank typically implements; a bank
enables you to deposit some money to increase your balance and to take money
out (subject to any necessary overdraft constraints) rather than letting you directly
Encapsulating Data and Defining Overloaded Operators 10-21

set the balance of your account. Consequently, it is more appropriate to provide


Deposit and Withdraw methods.
When you design types in your application, you should remember to design those
types to expose the functionality required for the specific application. You should
not expose every field as a property unless there is a good reason for exposing the
field.

Do Not Implement Get Accessors With Side Effects


A get accessor should simply retrieve a value and return that value to the
consuming application. When you implement a get accessor, retrieving the value
should not impact the value or any other data stored by the type. The only
exception to this rule is when you write applications that must adhere to security
restrictions. In this case, you can add logic to the get accessor to log access or to
further restrict access according to business requirements.

Use Naming Conventions


The convention when wrapping a field is to use a name that varies from the field
only in the case of the initial letter. For example, a field called myData is typically
encapsulated in a property called MyData. However, it is very easy to write code
that calls itself recursively, such as in the following code example.

int myData;

public int MyData


{
get
{
return MyData;
}
...
}

The code will compile; however, there is a bug in this code. It will cause an infinite
loop because the MyData property calls itself recursively. Bugs such as this can be
difficult to spot. If you allow an application with a bug such as this to run for long
enough, you will eventually get an OutOfMemoryException exception.

Question: When would you add logic to a get accessor that performs functionality
other than to return the data?
10-22 Programming in C# with Microsoft® Visual Studio® 2010

Additional Reading
For more information about choosing between properties and methods, see the
Choosing Between Properties and Methods page at
http://go.microsoft.com/fwlink/?LinkId=192951.
Encapsulating Data and Defining Overloaded Operators 10-23

Demonstration: Using Properties

Key Points
• Convert a field to an automatic property.
• Create a new property to provide controlled access to data in a field.
• Test the properties by using a test harness.

Demonstration Steps
1. Log on to the 10266A-GEN-DEV virtual machine as Student with the
password Pa$$word.
2. Start Microsoft Visual Studio® 2010.
3. Open the UsingPropertiesDemo solution in the
E:\Demofiles\Mod10\Demo1\Starter\UsingPropertiesDemo folder.
4. Open the Employee.cs file, and then review the Employee class. Notice the
publicly exposed fields and the constructor that sets the Name field based on
the parameter, and the Salary and Department fields to default values.
10-24 Programming in C# with Microsoft® Visual Studio® 2010

5. Convert the Name field to a property by using automatic properties:


• Modify the following line of code.

public string Name;

Change it to the following line of code.

public string Name { get; set; }

6. Convert the Department field to a property by using automatic properties:


• Modify the following line of code.

public string Department;

Change it to the following line of code.

public string Department { get; set; }

7. Convert the public Salary field to a private field and rename it salary:
• Modify the following line of code.

public int Salary;

Change it to the following line of code.

private int salary;

8. Uncomment the commented Salary property, and then explain how it ensures
that an employee can never have a negative salary.
9. Open the Program.cs file, and then review the Employee class.
10. Uncomment all of the code up to and including the first occurrence of the
following code.

Console.ReadLine();

Notice how the julie object is created by using the constructor, and explain
that the properties are subsequently set by using the dot notation.
Notice how the james object is created by using named properties. Emphasize
that these named properties are set after the constructor is run, so they take
precedence over the default values set by the constructor.
Encapsulating Data and Defining Overloaded Operators 10-25

11. Uncomment the remaining code in the file.


Notice that the code attempts to set James’ salary to a negative value. Remind
students that the property prevented negative values.
12. Run the application without debugging.
13. When the application pauses, highlight that the application has worked as
expected, and the two employees’ details are displayed correctly, and then
press ENTER.
14. When the application pauses, highlight that the application has worked as
expected, and James’ salary has been set to 0 instead of a negative value, and
then press ENTER.
15. Close Visual Studio.

Question: If you set a property in a constructor, and you use named properties to
set the same property when you instantiate the object, which takes precedence: the
value from the constructor or the named property?
10-26 Programming in C# with Microsoft® Visual Studio® 2010

Lab A: Creating and Using Properties

Objectives
After completing this lab, you will be able to:
• Define properties in an interface.
• Implement properties in a class.
• Use properties exposed by a class.

Introduction
In this lab, you will define properties in an interface and then implement these
properties in a class. You will also use a test application to verify that the properties
behave as expected.
Encapsulating Data and Defining Overloaded Operators 10-27

Lab Setup
For this lab, you will use the available virtual machine environment. Before you
begin the lab, you must:
• Start the 10266A-GEN-DEV virtual machine, and then log on by using the
following credentials:
• User name: Student
• Password: Pa$$w0rd
10-28 Programming in C# with Microsoft® Visual Studio® 2010

Lab Scenario

You have been asked to enhance the functionality of the software that drives a
number of the scientific devices produced by Fabrikam, Inc.
The software for the measuring devices developed in the previous labs must be
improved and simplified by using properties to provide controlled access to the
private data members of the MeasureDataDevice abstract class. In this way, other
developers can write software to manipulate the data exposed by these devices in a
variety of ways. Consequently, these developers will no longer be restricted by the
limited set of access methods that this class currently provides.
In this lab, you will modify the IMeasuringDevice interface and add the following
properties:
• UnitsToUse: A read-only property based on the Units enumeration that
exposes the unitsToUse field.
• DataCaptured: A read-only integer array property that exposes the
dataCaptured field.
• MostRecentMeasure: A read-only integer property that exposes the
mostRecentMeasure field.
Encapsulating Data and Defining Overloaded Operators 10-29

• LoggingFileName: A read/write string property that exposes the


loggingFileName field.

You will leave the existing methods in the IMeasuringDevice interface intact,
because the updated software has to support older applications that still use these
methods.
You will modify the MeasureDataDevice abstract class from the previous lab and
implement the properties. The property set accessor for the LoggingFileName
property will close the existing logging file (if it is open) and then open a new file
with the specified name. The remaining properties will simply return the value of
the underlying field. You will test the new functionality by using the
MeasureMassDevice class.

Exercise 1: Defining Properties in an Interface


Scenario
In this exercise, you will define an interface called
IMeasuringDeviceWithProperties with the following public properties:
• UnitsToUse. This read-only property will return the units used by the
emulated device.
• DataCaptured. This read-only property will return a copy of all of the recent
data that the measuring device has captured.
• MostRecentMeasure. This read-only property will return the most recent
measurement taken by the device.
• LoggingFileName. This read/write property will return and update the name
of the logging file used by the device.

The IMeasuringDeviceWithProperties interface will inherit from the


IMeasuringDevice interface; classes that implement the new interface will always
be required to implement the IMeasuringDevice interface.
The main tasks for this exercise are as follows:
1. Open the starter project.
2. Add properties to the IMeasuringDeviceWithProperties interface.
10-30 Programming in C# with Microsoft® Visual Studio® 2010

f Task 1: Open the starter project


1. Log on to the 10266A-GEN-DEV virtual machine as Student with the
password Pa$$w0rd.
2. Open Visual Studio 2010.
3. Import the code snippets from the E:\Labfiles\Lab 10\Snippets folder.
4. Open the Module10 solution in the E:\Labfiles\Lab 10\Lab A\Ex1\Starter
folder.

f Task 2: Add properties to the IMeasuringDeviceWithProperties


interface
1. In Visual Studio, review the task list.
2. Open the IMeasuringDeviceWithProperties.cs file.
3. Remove the comment TODO: Add properties to the interface..
4. Add a read-only property to the interface of type Units called UnitsToUse.
5. Add a read-only property to the interface of type int[] called DataCaptured.
6. Add a read-only property to the interface of type int called
MostRecentMeasure.
7. Add a read/write property to the interface of type string called
LoggingFileName.
8. Build the solution and correct any errors.

Exercise 2: Implementing Properties in a Class


Scenario
In this exercise, you will modify the existing MeasureDataDevice class (which
currently implements the IMeasuringDevice interface) to implement the
IMeasuringDeviceWithProperties interface. When you implement the
LoggingFileName property, you will implement logic in the set accessor that
checks whether the log file is open, and if it is open, closes the file and opens a new
log file with the updated name.
The main tasks for this exercise are as follows:
1. Open the starter project.
Encapsulating Data and Defining Overloaded Operators 10-31

2. Update the MeasureDataDevice class to implement the


IMeasuringDeviceWithProperties interface.

f Task 1: Open the starter project

Note: Perform this task only if you have not been able to complete Exercise 1. If you
have defined the IMeasuringDeviceWithProperties interface successfully, proceed
directly to Task 2: Update the MeasureDataDevice class to implement the
IMeasuringDeviceWithProperties interface.

• Open the Module10 solution in the E:\Labfiles\Lab 10\Lab A\Ex2\Starter


folder. This solution contains a completed version of the
IMeasuringDeviceWithProperties interface.

f Task 2: Update the MeasureDataDevice class to implement the


IMeasuringDeviceWithProperties interface
1. In Visual Studio, review the task list.
2. Open the MeasureDataDevice.cs file.
3. Remove the comment TODO: Implement the
IMeasuringDeviceWithProperties interface..
4. Modify the class declaration to implement the
IMeasuringDeviceWithProperties interface instead of the
ILoggingMeasuringDevice interface.
The IMeasuringDeviceWithProperties interface inherits from the
ILoggingMeasuringDevice interface, so modifying the declaration will not
break compatibility with existing applications; the class can still be cast as an
instance of the ILoggingMeasuringDevice interface.
5. Remove the comment TODO: Add properties specified by the
IMeasuringDeviceWithProperties interface..
You will use the Implement Interface Wizard in the next step to add the
properties.
6. Use the Implement Interface Wizard to generate method stubs for each of the
methods in the IMeasuringDeviceWithProperties interface.
10-32 Programming in C# with Microsoft® Visual Studio® 2010

7. Locate the UnitsToUse property get accessor, and then remove the default
body that throws a NotImplementedException exception. Add code to the get
accessor of the UnitsToUse property to return the unitsToUse field.
8. Locate the DataCaptured property get accessor, and then remove the default
that throws a NotImplementedException exception. Add code to the get
accessor of the DataCaptured property to return the dataCaptured field.
9. Locate the MostRecentMeasure property get accessor, and then remove the
default body that throws a NotImplementedException exception. Add code to
the get accessor of the MostRecentMeasure property to return the
mostRecentMeasure field.
10 Locate the LoggingFileName property get accessor, and then remove the
default body that throws a NotImplementedException exception. Add code to
the get accessor of the LoggingFileName property to return the
loggingFileName field.
11. Modify the set accessor of the LoggingFileName property as shown in the
following code example.

Note: A code snippet is available, called Mod10LoggingFileNamePropertySetAccessor,


that you can use to add this code.

if (loggingFileWriter == null)
{
// If the file has not been opened, simply update the file name.
loggingFileName = value;
}
else
{
// If the file has been opened, close the current file first,
// and then update the file name and open the new file.
loggingFileWriter.WriteLine("Log File Changed");
loggingFileWriter.WriteLine("New Log File: {0}", value);
loggingFileWriter.Close();

// Now update the logging file and open the new file.
loggingFileName = value;

// Check whether the logging file exists—if not, create it.


if (!File.Exists(loggingFileName))
{
loggingFileWriter = File.CreateText(loggingFileName);
Encapsulating Data and Defining Overloaded Operators 10-33

loggingFileWriter.WriteLine
("Log file status checked - Created");
loggingFileWriter.WriteLine("Collecting Started");
}
else
{
loggingFileWriter = new StreamWriter(loggingFileName);
loggingFileWriter.WriteLine
("Log file status checked - Opened");
loggingFileWriter.WriteLine("Collecting Started");
}
loggingFileWriter.WriteLine("Log File Changed Successfully");
}

The set accessor for the LoggingFileName property checks whether the log
file is currently open. If the log file has not been opened, the set accessor
simply updates the local field. However, if the log file has been opened, the
accessor closes the current log file and opens a new log file with the new file
name in addition to updating the local field.
12. Build the solution and correct any errors.

Exercise 3: Using Properties Exposed by a Class


Scenario
In this exercise, you will use a test harness application to test the functionality of
the MeasureDataDevice class you developed in the previous exercise.
The main tasks for this exercise are as follows:
1. Add the test harness to the solution.
2. Update the test harness.
3. Test the properties by using the test harness.

f Task 1: Add the test harness to the solution


The test harness application for this lab is a simple Windows® Presentation
Foundation (WPF) application that is designed to test the functionality of the
MeasureDataDevice class that you have just modified. It does not include any
exception handling to ensure that it does not hide any exceptions thrown by the
class that you have developed.
10-34 Programming in C# with Microsoft® Visual Studio® 2010

1. Add the test harness to the solution. The test harness is a project called
Exercise3TestHarness, located in the E:\Labfiles\Lab 10\Lab A\Ex3
\Starter\Exercise3TestHarness folder.
2. Set the Exercise3TestHarness project as the startup project for the solution.

f Task 2: Update the test harness


1. In Visual Studio, review the task list.
2. Review the user interface for the test application.
The test harness application includes functionality to enable you to test the
properties you developed in the previous exercise. The Start Collecting button
creates a new instance of the MeasureMassDevice object and starts collecting
measurements from the emulated device. The application includes text boxes
that display the output from the application. It also includes an Update button
to enable you to update the file name of the log file. Finally, the test harness
includes a button to stop the collection of measurements from the emulated
device and dispose of the object.
3. Open the MainWindow.xaml.cs file.

Note: In the following steps, you will store values in the Text property of TextBox
controls in the WPF window. This is a string property. In some of the steps, you may
need to call the ToString method to convert the property to a string.

4. Remove the comment TODO: Add code to set the unitsBox to the current
units.
5. Locate the following line of code.

unitsBox.Text = "";

6. Update the code you located in the previous step to set the Text property of
the unitsBox object to the UnitsToUse property of the device object.
7. Remove the comment TODO: Add code to set the mostRecentMeasureBox
to the value from the device..
8. Locate the following line of code.

mostRecentMeasureBox.Text = "";
Encapsulating Data and Defining Overloaded Operators 10-35

9. Update the code you located in the previous step to set the Text property of
the mostRecentMeasureBox object to the MostRecentMeasure property of
the device object.
10. Remove the comment TODO: Update to use the LoggingFileName property.
11. Locate the following line of code.

loggingFileNameBox.Text =
device.GetLoggingFile().Replace(labFolder, "");

12. Update the code you located in the previous step to set the Text property of
the loggingFileNameBox object to the LoggingFileName property of the
device object. Your code should call the Replace method of the string class in
the same way as the code you are updating.
13. Remove the comment TODO: Update to use the DataCaptured property.
14. Locate the following line of code.

rawDataValues.ItemsSource = device.GetRawData();

15. Update the code you located in the previous step to set the ItemsSource
property of the rawDataValues object to the DataCaptured property of the
device object.
16. In the updateButton_Click method, remove the comment TODO: Add code
to update the log file name property of the device and add code to set the
LoggingFileName property of the device object to the concatenation of the
labFolder field and the Text property of the loggingFileNameBox box.
17. Build the solution and correct any errors.

f Task 3: Test the properties by using the test harness


1. Start the Exercise3TestHarness application.
2. Click Start Collecting. This action causes the application to pause for 10
seconds while some measurements data is generated and then display this
data. This pause is necessary because the application waits for measurement
data from the emulated device.
3. Using Windows Explorer, move to the E:\Labfiles\Lab 10\Lab A folder, and
then verify that the default logging file, LogFile.txt, has been created.
10-36 Programming in C# with Microsoft® Visual Studio® 2010

4. Return to the Exercise3TestHarness window. Wait at least a further 10


seconds to ensure that the emulated device has generated some additional
values before you perform the following steps.
5. Change the log file to LogFile2.txt, and then click Update.
The Update button calls the code you added to set the LoggingFileName
property of the device; because the device is running, and therefore logging
values to the log file, the code will close the current log file and open a new
one with the name you specified.
6. Wait at least 10 seconds to ensure that the emulated device has generated
some additional values before you perform the following steps.
7. Using Windows Explorer, move to the E:\Labfiles\Lab 10\Lab A folder, and
then verify that the new logging file, LogFile2.txt, has been created.
8. Return to the Exercise3TestHarness window, and then click Stop Collecting /
Dispose Object.
9. Close the Exercise3TestHarness window.
10. Close Visual Studio.
11. Using Notepad, open the LogFile.txt file in the E:\Labfiles\Lab 10\Lab A
folder.
12. Review the contents of the LogFile.txt file.
The file includes the values originally displayed in the test harness in addition
to some not displayed. The file then indicates that the log file has changed and
gives the name of the new log file.
13. Open the LogFile2.txt file in the E:\Labfiles\Lab 10\Lab A folder.
14. Review the contents of the LogFile2.txt file.
The file indicates that the log file has changed successfully. The file then
includes any measurements taken after the log file changed and finally
indicates that collecting stopped and the object was disposed of.
15. Close Notepad.
Encapsulating Data and Defining Overloaded Operators 10-37

Lab Review

Review Questions
1. What is the syntax for declaring a property in an interface?
2. What is the significant difference between automatic properties and
nonautomatic properties?
3. What happens if you attempt to write to a property that exposes only a get
accessor?
10-38 Programming in C# with Microsoft® Visual Studio® 2010

Lesson 2
Creating and Using Indexers

A property typically provides access to a single item in a type. However, some types
are inherently multivalued, such as an array or a collection. Similarly, an item may
contain subelements that you want to provide easy access to. For example, you can
think of a string as a set of characters, and you may need to provide access to the
individual characters in a string field through a property.
The most natural syntax for accessing elements in a set is to use array-like notation,
and you can provide this access by defining indexer properties.
This lesson introduces you to indexers and describes how you can use indexers to
encapsulate data in your applications.

Objectives
After completing this lesson, you will be able to:
• Describe the purpose of an indexer.
• Implement an indexer.
Encapsulating Data and Defining Overloaded Operators 10-39

• Access data in your applications by using a type that exposes an indexer.


• Describe the differences between an indexer and an array.
• Define an indexer in an interface.
10-40 Programming in C# with Microsoft® Visual Studio® 2010

What Is an Indexer?

Key Points
An indexer provides a mechanism for encapsulating a set of values, in the same
way that a property encapsulates a single value. You use an indexer to access a
single value in a set of values, but you use get and set accessors to control how the
value is retrieved or set based on a subscript passed as a parameter to the indexer.
The get and set accessors use a property-like syntax.
Accessing an indexer uses the same syntax as accessing an array. However, with
indexers, you have more flexibility. For example, with an indexer, you can use a
noninteger type as the subscript instead of an integer normally used to access an
array.
The following code example shows the use of a simple indexer for a type called
CustomerAddressBook. This type provides an indexer that enables an application
to retrieve the address of a customer by specifying the ID of that customer. The
customer ID is held as a string.
Encapsulating Data and Defining Overloaded Operators 10-41

CustomerAddressBook addressBook = ...;


// Use an indexer to find the address of a customer.
Address customerAddress = addressBook["a2332"];

A type can define overloaded indexers that take different types of parameters. For
example, the CustomerAddressBook type could also provide an indexer that
retrieves a customer address based on an integer reference number, as the
following code example shows.

// Find the address of the customer with the specified reference.


Address customerAddress = addressBook[99];

In addition to defining indexers that take different parameters, indexers can also
return different types; they do not have to return an instance of the type that
defines the indexer.

Question: When may you want to add an indexer to a type?

Additional Reading
For more information about the comparison between properties and indexers, see
the Comparison Between Properties and Indexers (C# Programming Guide) page
at http://go.microsoft.com/fwlink/?LinkId=192952.
10-42 Programming in C# with Microsoft® Visual Studio® 2010

Creating an Indexer

Key Points
Writing an indexer is a cross between writing a property and using an array.
You use syntax reminiscent of properties to specify the type and get and set
accessors, but the name of the indexer is always this. You specify the types and
names of parameters by using array-like notation in square brackets.
Like a property, an indexer can also be read-only (it only has a get accessor) or
write-only (it only has a set accessor).
You can access the indexer parameters by name in the accessors, and in the set
accessor, you can use the value keyword to access the value passed to the indexer.
Parameters passed to an indexer are only intended to be used to locate the data
item to set or get. In the get accessor, you return the item found at this location,
and in the set accessor, you store the data specified by the value parameter at this
location.
The following code example shows a simple indexer that enables an application to
find the address of a customer given the customer ID, or update the address. The
address is stored in a database, accessed through the database variable.
Encapsulating Data and Defining Overloaded Operators 10-43

class AddressBook
{
public Address this[string CustomerID]
{
get
{
return database.FindCustomer(CustomerID);
}
set
{
database.UpdateCustomer(CustomerID, value);
}
}
...
}

Important: Ensure that you incorporate some type of error-handling strategy to handle
the chance of client code passing in an invalid index value.

Note: You cannot define static indexers.

Question: What information should you use as parameters for an indexer?

Additional Reading
For more information about using indexers, see the Using Indexers (C#
Programming Guide) page at http://go.microsoft.com/fwlink/?LinkId=192953.
10-44 Programming in C# with Microsoft® Visual Studio® 2010

Comparing Indexers and Arrays

Key Points
To use an indexer, you use a similar syntax to that of an array; however, there are
several important differences between an indexer and an array.

Indexer Subscripts
When you use an array, you access members of that array by using a numeric
subscript. For example, you can access the fifth element in an array and use syntax
similar to myArray[4] (assuming a zero-based index). With arrays, you can only use
numeric subscripts. An indexer gives you greater flexibility because you can use
nonnumeric subscripts.

Overloading an Indexer
You cannot overload an array; the implementation is defined by the runtime, and
all classes that inherit from your class cannot change the behavior of that array.
However, you have complete control over the behavior of an indexer, and classes
that inherit from your class can override the indexer and provide their own
implementation.
Other documents randomly have
different content
§ 98. The outbreak of war causes at once the rupture of
diplomatic intercourse between the belligerents, if such rupture has
not already taken place. The respective diplomatic envoys are
recalled and ask for their passports, or receive them without any
previous request, but they enjoy their privileges of inviolability and
exterritoriality for the period of time requisite for leaving the country.
Consular activity likewise comes to an end through the outbreak of
war.[180]
[180] See above, vol. I. §§ 413 and 436.

Cancellation of Treaties.
§ 99. The doctrine was formerly held, and a few writers[181]
maintain it even now, that the outbreak of war ipso facto cancels all
treaties previously concluded between the belligerents, such treaties
only excepted as have been concluded especially for the case of war.
The vast majority of modern writers on International Law have
abandoned this standpoint,[182] and the opinion is pretty general that
war by no means annuls every treaty. But unanimity as to what
treaties are or are not cancelled by war does not exist. Neither does
a uniform practice of the States exist, cases having occurred in
which States have expressly declared[183] that they considered all
treaties annulled through war. Thus the whole question remains as
yet unsettled. Nevertheless a majority of writers agree on the
following points:—
(1) The outbreak of war cancels all political treaties between the
belligerents which have not been concluded for the purpose of
setting up a permanent condition of things, for instance, treaties of
alliance.
(2) On the other hand, it is obvious that such treaties as have
been especially concluded for the case of war are not annulled, such
as treaties in regard to the neutralisation of certain parts of the
territories of the belligerents.
(3) Such political and other treaties as have been concluded for
the purpose of setting up a permanent[184] condition of things are
not ipso facto annulled by the outbreak of war, but nothing prevents
the victorious party from imposing upon the other party in the treaty
of peace any alterations in, or even the dissolution of, such treaties.
(4) Such non-political treaties as do not intend to set up a
permanent condition of things, as treaties of commerce for example,
are not ipso facto annulled, but the parties may annul them or
suspend them according to discretion.
(5) So-called law-making[185] treaties, as the Declaration of Paris
for example, are not cancelled by the outbreak of war. The same is
valid in regard to all treaties to which a multitude of States are
parties, as the International Postal Union for example, but the
belligerents may suspend them, as far as they themselves are
concerned, in case the necessities of war compel them to do so.[186]
[181] See, for instance, Phillimore, III. § 530, and Twiss, I. § 252, in contradistinction to
Hall, § 125.
[182] See Jaconnet, op. cit. pp. 113-128.
[183] As, for instance, Spain in 1898, at the outbreak of the war with the United States of
America, see Moore, V. pp. 375-380.
[184] Thus American and English Courts—see the cases of the Society for the Propagation
of the Gospel v. Town of Newhaven (1823), 8 Wheaton 464, and Sutton v. Sutton (1830),
1 Russel & Mylne, 663—have declared that article IX. of the treaty of Nov. 19, 1794,
between Great Britain and the United States was not annulled by the outbreak of war in
1812. See Moore, V. § 779 and Westlake, II. p. 30; see also the foreign cases discussed
by Jaconnet, op. cit. pp. 168-179.
[185] See above, vol. I. §§ 18, 492, 555-568b.
[186]The Institute of International Law is studying the whole question of the effect of
war on treaties; see Politis, l.c., and especially Annuaire, XXIV. (1911), pp. 201-213, and
220-221.

Precarious position of Belligerents' subjects on Enemy Territory.


§ 100. The outbreak of war affects likewise such subjects of the
belligerents as are at the time within the enemy's territory. In former
times they could at once be detained as prisoners of war, and many
States, therefore, concluded in time of peace special treaties for the
time of war expressly stipulating a specified period during which
their subjects should be allowed to leave each other's territory
unmolested.[187] Through the influence of such treaties, which
became pretty general during the eighteenth century, it became an
international practice that, as a rule, enemy subjects must be
allowed to withdraw within a reasonable period, and no instance of
the former rule has occurred during the nineteenth[188] century.
Although some[189] writers even nowadays maintain that according to
strict law the old rule is still in force, it may safely[190] be maintained
that there is now a customary rule of International Law, according to
which all such subjects of the enemy as have not according to the
Municipal Law of their country to join the armed forces of the enemy
must be allowed a reasonable period for withdrawal. On the other
hand, such enemy subjects as are active or reserve officers, or
reservists, and the like, may be prevented from leaving the country
and detained as prisoners of war, for the principle of self-
preservation must justify belligerents in refusing to furnish each
other with resources which increase their means of offence and
defence.[191] However that may be, a belligerent need not allow[192]
enemy subjects to remain on his territory, although this is frequently
done. Thus, during the Crimean War Russian subjects in Great
Britain and France were allowed to remain there, as were likewise
Russians in Japan and Japanese in Russia during the Russo-
Japanese War, and Turks in Italy during the Turco-Italian War. On the
other hand, France expelled all Germans during the Franco-German
war in 1870; the former South African Republics expelled most
British subjects when war broke out in 1899; Russia, although during
the Russo-Japanese War she allowed Japanese subjects to remain in
other parts of her territory, expelled them from her provinces in the
Far East; and in May 1912, eight months after the outbreak of the
Turko-Italian War, Turkey decreed the expulsion of all Italians,
certain classes excepted. In case a belligerent allows the residence
of enemy subjects on his territory, he can, of course, give the
permission under certain conditions only, such as an oath to abstain
from all hostile acts or a promise not to leave a certain region, and
the like. And it must be especially observed that an enemy subject
who is allowed to stay in the country after the outbreak of war must
not, in case the forces of his home State militarily occupy the part of
the country inhabited by him, join these forces or assist them in any
way. If, nevertheless, he does so, he is liable to be punished for
treason[193] by the local Sovereign after the withdrawal of the enemy
forces.
[187] See a list of such treaties in Hall, § 126, p. 107, note 1.
[188] With regard to the 10,000 Englishmen who were arrested in France by Napoleon at
the outbreak of war with England in 1803 and kept as prisoners of war for many years, it
must be borne in mind that Napoleon did not claim a right to make such civilians
prisoners of war as were at the outbreak of war on French soil. He justified his act as
one of reprisals, considering it a violation of the Law of Nations on the part of England to
begin hostilities by capturing two French merchantmen in the Bay of Audierne without a
formal declaration of war. See Alison, History of Europe, V. p. 277, and Bonfils, No. 1052.
[189] See Twiss, II. § 50; Rivier, II. p. 320; Liszt, § 39, V.; Holland, Letters upon War and
Neutrality (1909), p. 39.
[190] See Land Warfare, § 12.
[191] See Land Warfare, § 13.
[192]See above, vol. I. § 324.
[193]See above, vol. I. § 317, p. 394, where the case of De Jager v. Attorney General is
discussed.

Persona standi in judicio on Enemy Territory.


§ 100a. Formerly the rule prevailed everywhere that an enemy
subject has no persona standi in judicio and is, therefore, ipso facto
by the outbreak of war, prevented from either taking or defending
proceedings in the Courts. This rule dates from the time when war
was considered such a condition between belligerents as justified the
committing of hostilities on the part of all subjects of the one
belligerent against all subjects of the other, and, further, the killing of
all enemy subjects irrespective of sex and age, and, at any rate, the
confiscation of all private enemy property. War in those times used
to put enemy subjects entirely ex lege, and it was only a logical
consequence from this principle that enemy subjects could not
sustain persona standi in judicio. Since the rule that enemy subjects
are entirely ex lege has everywhere vanished, the rule that they may
not take or defend proceedings in the Courts has in many countries,
such as Austria-Hungary, Germany, Holland, and Italy, likewise
vanished. But in Great Britain and the United States of America[194]
enemy subjects are still prevented from taking and defending legal
proceedings,[195] although there are six exceptions to the general
rule. Firstly, enemy subjects who do not bear enemy character
because they are resident in neutral country or have a licence to
trade or are allowed[196] to remain in the country of a belligerent, are
therefore permitted to sue and be sued in British and American
Courts. Secondly, if during time of peace a defendant obtains an
opportunity to plead, and if subsequently war breaks out with the
country of the plaintiff, the defendant may not plead that the
plaintiff is prevented from suing.[197] Thirdly, if a contract was
entered into and executed before the war, and if an absent enemy
subject has property within the boundaries of a belligerent, he may
be sued.[198] Fourthly, a prisoner of war[199] may sue during war on a
contract for wages. Fifthly, if the parties, being desirous to obtain a
decision on the merits of the case, waive the objection, enemy
subjects may sue and be sued.[200] Lastly, a petition on the part of a
creditor who is an enemy subject, to prove a debt under a
commission of bankruptcy must be admitted[201] although the
dividend will not be paid till after the conclusion of peace.
[194] In strict law also in France.
[195] The leading case is the Hoop (1799), 1 C. Rob. 196.
[196] Wells v. Williams (1698), 1 Lord Raymond, 282.
[197] Shepeler v. Durand (1854), 14 P.C. 582.
[198] Dorsey v. Kyle (1869), 3 Maryland, 512. It would seem that the American Courts
are inclined to drop the rule that an enemy subject cannot be sued; see De Jarnett v. De
Giversville (1874), 56 Missouri, 440.
[199] Maria v. Hall (1800), 2 B. & P. 236.
[200] Driefontein Consolidated Gold Mines Co. v. Janson (1910), 2 Q.B. 419; App. Cas.
(1902), 484.
[201] Ex parte Boussmaker (1806), 13 Vesey Jun. 71.

It is asserted that, in consequence of article 23 (h) of the Hague


Regulations concerning land warfare enacting the injunction "to
declare extinguished, suspended, or unenforceable in a Court of Law
the rights and rights of action of the nationals of the adverse party,"
Great Britain and the United States are compelled to abolish their
rule that enemy subjects may not sue. But the interpretation of
article 23 (h) is controversial, Great Britain and the United States of
America—in contradistinction to Germany and France—maintaining
that the article has nothing to do with their Municipal Law but
concerns the conduct of armies in occupied enemy territory.[202]
[202] It is impossible here to discuss the details of this controversy which the third Peace
Conference must settle. See above, vol. I. § 554, No. 10; Politis in R.G. XVIII. (1911),
pp. 249-259, and the literature there quoted; Kohler in Z.V. V. (1911), pp. 384-393;
Holland in The Law Quarterly Review, XXVIII. (1912), pp. 94-98; Charteris in The
Juridical Review, XXIII. (1911), pp. 307-323; Oppenheim, Die Zukunft des Völkerrechts
(1911), pp. 30-32.
However this may be, it must be especially observed that,
according to British and American law, claims arising out of contracts
concluded before the war do not become extinguished through the
outbreak of war, but are only suspended during war, and the Statute
of Limitations does not, according to American[203] practice at any
rate, run during war.
[203]Hanger v. Abbot (1867), 6 Wallace, 532. The point is not settled in English law, for
the obiter dictum in De Wahl v. Browne (1856), 25 L.J. (N.S.) Ex. 343, "It may be that
the effect would ultimately be to bar the action by reason of the Statute of Limitations is
no answer...", is not decisive, although Anson, Principles of the English Law of Contract
(11th ed. 1906), p. 122, and other writers accept it as decisive.

Intercourse, especially Trading, between Subjects of Belligerents.


§ 101. Following Bynkershoek,[204] all British and American writers
and cases, and also some French[205] and German[206] writers assert
the existence of a rule of International Law that all intercourse, and
especially trading, is ipso facto by the outbreak of war prohibited
between the subjects of the belligerents, unless it is permitted under
the customs of war, as, for instance, ransom bills, or is allowed
under special licences, and that all contracts concluded between the
subjects of the belligerents before the outbreak of war become
extinct or suspended. On the other hand, most German, French, and
Italian writers deny the existence of such a rule, but assert the
existence of another according to which belligerents are empowered
to prohibit by special orders all trade between their own and enemy
subjects.
[204] Quaestiones juris publici, I. c. 3: "quamvis autem nulla specialis sit commerciorum
prohibitio ipsa tamen jure belli commercia sunt vetita."
[205] For instance, Pillet, p. 74, and Mérignhac, p. 57.
[206] For instance, Geffcken in his note 4 to Heffter, p. 265.

These assertions are remnants of the time when the distinction[207]


between International and Municipal Law was not, or not clearly,
drawn. International Law, being a law for the conduct of States only
and exclusively, has nothing to do directly with the conduct of
private individuals, and both assertions are, therefore, nowadays
untenable. Their place must be taken by the statement that, States
being sovereign and the outbreak of war bringing the peaceful
relations between belligerents to an end, it is within the competence
of every State to enact by its Municipal Law such rules as it pleases
concerning intercourse, and especially trading, between its own and
enemy subjects. And if we look at the Municipal Laws of the several
countries, we find that they have to be divided into two groups. To
the one group belong those States—such as Austria-Hungary,
Germany, Holland, and Italy—whose Governments are empowered
by their Municipal Laws to prohibit by special order all trading with
enemy subjects at the outbreak of war. In these countries trade with
enemy subjects is permitted to continue after the outbreak of war
unless special prohibitive orders are issued. To the other group
belong those States—such as Great Britain, the United States of
America, and, unless desuetudo[208] has made an alteration, France—
whose Municipal Laws declare trade and intercourse with enemy
subjects ipso facto by the outbreak of war prohibited, but empowers
the Governments to allow by special licences all or certain kinds of
such trade.
[207] See above, vol. I. § 20.
[208] See Meyer, op. cit. p. 91.

As regards the law of Great Britain[209] and the United States of


America, it has been, since the end of the eighteenth century, an
absolutely settled[210] rule of the Common Law that, certain cases
excepted, all trading with alien enemies is ipso facto by the outbreak
of war illegal unless it is allowed by special licences of the Crown.
From the general principle asserted in the leading cases,[211] the
Courts have drawn the following more important consequences:—
(1) All contracts, entered into during a war,[212] with alien enemies
without a special licence are illegal, invalid, and can never be
enforced, unless the contract was one entered into in case of
necessity,[213] or in order to supply[214] an invading English army or
the English fleet, or by prisoners[215] of war concerning personal
services and requirements. (2) Trading with the enemy does not
become legal by the fact that goods coming from the enemy country
to Great Britain, or going from Great Britain to the enemy country,
are sent to their destination through a neutral country.[216] (3) As
regards contracts entered into before[217] the outbreak of war, a
distinction must be drawn:—(a) Executory contracts are avoided,
both parties being released from performance. (b) Contracts
executed before the outbreak of war and not requiring to be acted
upon during the war are suspended until after the conclusion of
peace. (c) Executed contracts which require acting upon during the
war are dissolved. (4) Partnerships[218] with alien enemies are
dissolved. (5) No interest runs on debts[219] or mortgages.[220]
(6) A contract of affreightment[221] must not be fulfilled; therefore
English ships must not load or unload goods in an enemy port. (7)
Contracts of insurance of enemy vessels and goods are so to be
construed as to contain a proviso that the assurance shall not cover
any loss occurring during a war between the country of the assurer
and the country of the assured.[222] (8) A life insurance policy,[223]
entered into before the outbreak of war conditioning the payment of
yearly premiums on pain of forfeiture of the policy, is forfeited ipso
facto by the outbreak of war because the payment of the premium is
now prohibited. After the conclusion of peace, however, the insured
may claim the equitable value of the policy arising, at the time of the
outbreak of war, from the premiums actually paid.
[209] See besides the English and American text-books quoted above at the
commencement of § 97, Pennant, Chadwick, and Gregory in The Law Quarterly Review,
XVIII. (1902), pp. 289-296, XX. (1904), pp. 167-185, XXV. (1909), pp. 297-316;
Bentwich, The Law of Private Property in War (1907), pp. 46-61; Phillipson, The Effect of
War on Contracts (1909); Latifi, Effects of War on Property (1909), pp. 50-58.
[210] Whereas the Admiralty Court did at all times, the Common Law Courts did not
during the eighteenth century hold trading with enemy subjects to be illegal, at any rate
not in so far as insurance of enemy vessels and goods against capture on the part of
English cruisers was concerned; see Henkle v. London Exchange Assurance Co. (1749), 1
Vesey Sen. 320; Planche v. Fletcher (1779), 1 Dougl. 251; Lavabre v. Wilson (1779), 1
Dougl. 284; Gist v. Mason (1786), 1 T.R. 84.
[211]Besides the Admiralty case of the Hoop (1799), 1 C. Rob. 196, the following are the
leading cases:—Potts v. Bell (1800), 8 D. & E. 548; Furtado v. Rodgers (1802), 3 P. & B.
191; Esposito v. Bowden (1857), 7 E. & B. 763; the Mashona (1900), 10 Cape Times Law
Reports, 170.
[212] Willison v. Paterson (1817), 7 Taunt, 439.
[213] Antoine v. Morshead (1815), 6 Taunt, 237.
[214] The Madonna delle Gracie (1802), 4 C. Rob. 195.
[215] Maria v. Hall (1800), 2 B. & P. 236.
[216] The Jonge Pieter (1801), 4 C. Rob. 79. But if the goods have been bought by the
subject of a neutral State bona fide by himself and are afterwards shipped through
neutral country to the enemy, it is not a case of trading with the enemy; see the Samuel
(1802), 4 C. Rob. 284, note.
[217] Melville v. De Wold (1855), 4 E. & B. 844; Esposito v. Bowden (1857), 7 E. & B.
763; Ex parte Boussmaker (1806), 13 Ves. Jun. 71; Alcinous v. Nygreu (1854), 4 E. & B.
217; the Charlotta (1814), 1 Dodson, 390.
[218] Griswold v. Boddington (1819), 16 Johnson, 438; Esposito v. Bowden (1857), 7 E. &
B. 763.
[219] Du Belloix v. Lord Waterpark (1822), 1 Dowl. & R. 16; Mayer v. Reed (1867), 37
Gallison, 482.
[220] Hoare v. Allan (1789), 2 Dallas, 102.
[221] Esposito v. Bowden (1857), 7 E. & B. 763. See also the Teutonia (1870), L. R. 4
Privy Council, 171.
[222] Brandon v. Curling (1803), 4 East, 410; but see also Potts v. Bell (1800), 8 D. & E.
548; Furtado v. Rodgers (1802), 3 P. & B. 191; Kellner v. Le Mesurier (1803), 4 East,
396; Gamba v. Le Mesurier (1803), 4 East, 407.
[223] New York Life Insurance Co. v. Stathem, v. Symes, and v. Buck (1876), 93 United
States, 24; New York Life Insurance Co. v. Davis (1877), 95 United States, 425.
It must be specially observed that, if the continental interpretation
of article 23 (h) of the Hague Regulations—see above, § 100a—were
not contradicted by Great Britain and the United States of America,
both countries would be compelled to alter their Municipal Laws in
so far as these declare such contracts as have been entered into
with alien enemies before the outbreak of war dissolved, void, or
suspended. Article 23 (h) distinctly enacts that it is forbidden to
declare extinguished or suspended the rights of the nationals of the
adverse party. Since, however, as stated above in § 100a, Great
Britain and the United States of America uphold a different
interpretation, this article does not concern their Municipal Laws
respecting trading with alien enemies.

Position of Belligerents' Property in the Enemy State.


§ 102. In former times all private and public enemy property,
immoveable or moveable, on each other's territory could be
confiscated by the belligerents at the outbreak of war, as could also
enemy debts; and the treaties[224] concluded between many States
with regard to the withdrawal of each other's subjects at the
outbreak of war stipulated likewise the unrestrained withdrawal of
the private property of their subjects. Through the influence of such
treaties as well as of Municipal Laws and Decrees enacting the same,
an international usage and practice grew up that belligerents should
neither confiscate private enemy property nor annul enemy debts on
their territory. The last case of confiscation of private property is that
of 1793 at the outbreak of war between France and Great Britain. No
case of confiscation occurred during the nineteenth century, and
although several writers maintain that according to strict law the old
rule, in contradistinction to the usage which they do not deny, is still
valid, it may safely be maintained that it is obsolete, and that there
is now a customary rule of International Law in existence prohibiting
the confiscation of private enemy property and the annulment of
enemy debts on the territory of a belligerent. This rule, however,
does not prevent a belligerent from seizing public enemy property on
his territory, such as funds, ammunition, provisions, rolling stock of
enemy state-railways, and other valuables; from preventing the
withdrawal of private enemy property which may be made use of by
the enemy[225] for military operations, such as arms and munitions;
from seizing and making use of rolling stock belonging to private
enemy railway companies, other means of transport of persons or
goods which are private enemy property, and, further, all appliances
for the transmission of news, although they are private enemy
property, provided all these articles are restored and indemnities are
paid for them after the conclusion of peace;[226] and from
suspending, as a measure of self preservation, the payment of large
enemy debts till after the conclusion of peace in order to prevent the
increase of resources of the enemy.
[224]See above, § 100; Moore, VII. § 1196; Scott, Conferences, pp. 559-563.
[225]The indulgence granted to enemy merchantmen in Russian and Japanese ports at
the outbreak of the war in 1904, to leave those ports unmolested within a certain period
of time, was conditional upon there being no contraband in the cargoes. See Lawrence,
War, p. 52.
[226] As the seizure of all these articles is, according to article 53 of the Hague
Regulations, permissible in occupied enemy country, provided they are restored and
indemnities paid after the conclusion of peace, seizure must likewise—under the same
conditions—be permissible in case these articles are on the territory of a belligerent. As
regards rolling stock belonging to private enemy railway companies, see Nowacki, Die
Eisenbahnen im Kriege (1906), § 15.

Effect of the Outbreak of War on Merchantmen.


§ 102a. In former times International Law empowered States at
the outbreak of war to lay an embargo upon all enemy
merchantmen in their harbours in order to confiscate them. And
enemy merchantmen on the sea could at the outbreak of war be
captured and confiscated although they did not even know of the
outbreak of war. As regards enemy merchantmen in the harbours of
the belligerents, it became, from the outbreak of the Crimean War in
1854, a usage, if not a custom, that no embargo[227] could be laid on
them for the purpose of confiscating them, and that a reasonable
time must be granted them to depart unmolested; but no rule was in
existence until the Second Peace Conference of 1907 which
prescribed immunity from confiscation for such enemy merchantmen
at sea as did not know of the outbreak of war. This Conference took
the matter into consideration, and produced a Convention (VI.)
relative to the status of enemy merchantmen at the outbreak of
hostilities[228] which is signed by all the Powers represented at the
Conference, except the United States of America,[229] China, and
Nicaragua; but Nicaragua acceded later. In coming to an agreement
on the subject, two facts had to be taken into consideration. There
is, firstly, the fact that in all maritime countries numerous
merchantmen are now built from special designs in order that they
may quickly, at the outbreak of or during war, be converted into
cruisers; it would therefore be folly on the part of a belligerent to
grant any lenient treatment to such vessels. There is, secondly, the
fact, that a belligerent fleet cannot nowadays remain effective for
long without being accompanied by a train of colliers, transport
vessels, and repairing vessels; it is, therefore, of the greatest
importance for a belligerent to have as many merchantmen as
possible at his disposal for the purpose of making use of them for
such assistance to the fleet. For this reason, Convention VI.
represents a compromise, and it distinguishes between vessels in
the harbours of the belligerents and vessels on the sea. Its
provisions are the following:—
[227] See above, § 40.
[228] See Lémonon, pp. 647-661; Higgins, pp. 300-307; Nippold, II. pp. 146-153; Scott,
Conferences, pp. 556-568; Dupuis, Guerre, Nos. 74-81; Scott in A.J. II. (1908), pp. 260-
269.
[229] The United States of America refused to sign the Convention because she considers
its stipulations retrogressive as they are less liberal than the practice which has prevailed
since 1854. But circumstances have changed since that time, and the two facts explained
in the text would seem to have compelled the maritime Powers to adopt rules somewhat
less liberal. This was the more necessary since no agreement could be arrived at
concerning the question of the locality in which belligerents should be allowed to convert
merchantmen into cruisers.
(1) Article 1 of the Convention enacts that, in case an enemy
merchantman is at the beginning of the war in the port of a
belligerent, it is desirable that she should be allowed freely to
depart, either immediately or after a sufficient term of grace, and,
after being furnished with a passport, to proceed either direct to her
port of destination or to such other port as may be determined. It is
obvious that, since only the desirability of free departure of such
vessels is stipulated, a belligerent is not compelled to grant free
departure; nevertheless there must be grave reasons for not acting
in accordance with what is considered desirable by article 1. And it
must be specially observed that a belligerent may make a distinction
in the treatment of several enemy vessels in his harbours, and may
grant free departure to one or more of them, and refuse it to others,
according to his discretion.
(2) The former usage that enemy merchantmen in the harbours of
the belligerents at the outbreak of war may not be confiscated, has
been made a binding rule by article 2 which enacts that such vessels
as were not allowed to leave, or were by force majeure prevented
from leaving during the term of grace, may not be confiscated, but
may only be detained under the obligation that they shall be
restored, without indemnity, after the conclusion of peace, or they
may be requisitioned on condition of indemnities to be paid to the
owners.
(3) Enemy merchantmen which have left their last port of
departure before the outbreak of war and which, while ignorant of
the outbreak of war, are met at sea by cruisers of the belligerents,
may, according to article 3, be captured, but they may not be
confiscated, for they must be restored after the war is ended,
although no indemnities need be paid. Indemnities are only to be
paid in case the vessels have been requisitioned or destroyed, for a
belligerent is empowered to requisition or destroy such vessels
provided he takes care to preserve the ship papers and makes
arrangements for the safety of the persons on board.
It is obvious that, in case such vessels are not ignorant of the
outbreak of war—having, for instance, received the news by wireless
telegraphy—they may not any longer claim the privileges stipulated
by article 3. And this article stipulates expressly that after having
touched a port of their own or of a neutral country, such vessels are
no longer privileged.
(4) Enemy goods on board such enemy merchantmen as are in
the harbour of a belligerent at the outbreak of war or at sea and are
in ignorance of the outbreak of war are, according to article 4,
privileged to the same extent as the vessels concerned.
(5) Enemy merchantmen whose construction indicates that they
are intended to be converted into cruisers may be seized and
confiscated in the harbours of the belligerents, as well as at sea,
although ignorant of the outbreak of war, for article 5 stipulates
expressly that Convention VI. does not affect such vessels.

CHAPTER III
WARFARE ON LAND
I
ON LAND WARFARE IN GENERAL

Vattel, III. §§ 136-138—Hall, §§ 184-185—Phillimore, III. § 94—Taylor, § 469—


Wheaton, § 342—Bluntschli, §§ 534-535—Heffter, § 125—Lueder in Holtzendorff,
IV. pp. 388-389—Gareis, § 84—Bonfils, Nos. 1066-1067—Pradier-Fodéré, VI. Nos.
2734-2741—Longuet, § 41—Mérignhac, p. 146—Pillet, pp. 85-89—Kriegsbrauch, p.
9—Land Warfare, § 39—Holland, War, Nos. 1-15.

Aims and Means of Land Warfare.


§ 103. The purpose of war, namely, the overpowering of the
enemy, is served in land warfare through two aims[230]—firstly, defeat
of the enemy armed forces on land, and, secondly, occupation and
administration of the enemy territory. The chief means by which
belligerents try to realise those aims, and which are always
conclusively decisive, are the different sorts of force applied against
enemy persons. But besides such violence against enemy persons
there are other means which are not at all unimportant, although
they play a secondary part only. Such means are: appropriation,
utilisation, and destruction of enemy property; siege; bombardment;
assault; espionage; utilisation of treason; ruses. All these means of
warfare on land must be discussed in this chapter, as must also
occupation of enemy territory.
[230] Aims of land warfare must not be confounded with ends of war; see above, § 66.

Lawful and Unlawful Practices of Land Warfare.


§ 104. But—to use the words of article 22 of the Hague
Regulations—"the belligerents have not an unlimited right as to the
means they adopt for injuring the enemy." For not all possible
practices of injuring the enemy in offence and defence are lawful,
certain practices being prohibited under all circumstances and
conditions, and other practices being allowed only under certain
circumstances and conditions, or only with certain restrictions. The
principles of chivalry and of humanity have been at work[231] for
many hundreds of years to create these restrictions, and their work
is not yet at an end. However, apart from these restrictions, all kinds
and degrees of force and many other practices may be made use of
in war.
[231] See above, § 67.

Objects of the Means of Warfare.


§ 105. In a sense all means of warfare are directed against one
object only—namely, the enemy State, which is to be overpowered
by all legitimate means. Apart from this, the means of land warfare
are directed against several objects.[232] Such objects are chiefly the
members of the armed forces of the enemy, but likewise, although in
a lesser degree, other enemy persons; further, private and public
property, fortresses, and roads. Indeed, apart from certain
restrictions, everything may eventually be the object of a means of
warfare, provided the means are legitimate in themselves and are
capable of fostering the realisation of the purpose of war.
[232] See Oppenheim, Die Objekte des Verbrechens (1894), pp. 64-146, where the
relation of human actions with their objects is fully discussed.

Land Warfare in contradistinction to Sea Warfare.


§ 106. Land warfare must be distinguished from sea warfare
chiefly for two reasons. Firstly, their circumstances and conditions
differ widely from each other, and, therefore, their means and
practices also differ. Secondly, the law-making Conventions which
deal with warfare rarely deal with land and sea warfare at the same
time, but mostly treat them separately, for whereas some
Conventions deal exclusively with warfare on sea, the Hague
Regulations (Convention IV.) deal exclusively with warfare on land.

II
VIOLENCE AGAINST ENEMY PERSONS

Grotius, III. c. 4—Vattel, III. §§ 139-159—Hall, §§ 128, 129, 185—Westlake, II. pp.
72-76—Lawrence, §§ 161, 163, 166-169—Maine, pp. 123-148—Manning, pp. 196-
205—Phillimore, III. §§ 94-95—Halleck, II. pp. 14-18—Moore, VII. §§ 1111, 1119,
1122, 1124—Taylor, §§ 477-480—Walker, § 50—Wheaton, §§ 343-345—Bluntschli,
§§ 557-563—Heffter, § 126—Lueder in Holtzendorff, IV. pp. 390-394—Gareis, § 85
—Klüber, § 244—Liszt, § 40, III.—G. F. Martens, II. § 272—Ullmann, § 176—
Bonfils, Nos. 1068-1071, 1099, 1141—Despagnet, Nos. 525-527—Pradier-Fodéré,
VI. Nos. 2742-2758—Rivier, II. pp. 260-265—Nys, III. pp. 206-209—Calvo, IV.
2098-2105—Fiore, III. Nos. 1317-1320, 1342-1348, and Code, Nos. 1476-1483—
Martens, II. § 110—Longuet, §§ 42-49—Mérignhac, pp. 146-165—Pillet, pp. 85-95
—Holland, War, pp. 70-76—Zorn, pp. 127-161—Bordwell, pp. 278-283—Meurer, II.
§§ 30-31—Spaight, pp. 73-156—Kriegsbrauch, pp. 9-11—Land Warfare, §§ 39-53.

On Violence in general against Enemy Persons.


§ 107. As war is a contention between States for the purpose of
overpowering each other, violence consisting of different sorts of
force applied against enemy persons is the chief and decisive means
of warfare. These different sorts of force are used against
combatants as well as non-combatants, but with discrimination and
differentiation. The purpose of the application of violence against
combatants is their disablement so that they can no longer take part
in the fighting. And this purpose may be realised through either
killing or wounding them, or making them prisoners. As regards non-
combatant members of armed forces, private enemy persons
showing no hostile conduct, and officials in important positions, only
minor means of force may as a rule be applied, since they do not
take part in the armed contention of the belligerents.
Killing and Wounding of Combatants.
§ 108. Every combatant may be killed or wounded, whether a
private soldier or an officer, or even the monarch or a member of his
family. Some publicists[233] assert that it is a usage of warfare not to
aim at a sovereign or a member of his family. Be that as it may,
there is in strict law[234] no rule preventing the killing and wounding
of such illustrious persons. But combatants may only be killed or
wounded if they are able and willing to fight or to resist capture.
Therefore, such combatants as are disabled by sickness or wounds
may not be killed. Further, such combatants as lay down arms and
surrender or do not resist being made prisoners may neither be
killed nor wounded, but must be given quarter. These rules are
universally recognised, and are now expressly enacted by article 23
(c) of the Hague Regulations, although the fury of battle frequently
makes individual fighters[235] forget and neglect them.
[233] See Klüber, § 245; G. F. Martens, II. § 278; Heffter, § 126.
[234] Says Vattel, III. § 159: "Mais ce n'est point une loi de la guerre d'épargner en toute
rencontre la personne du roi ennemi; et on n'y est obligé que quand on a la facilité de le
faire prisonnier." The example of Charles XII. of Sweden (quoted by Vattel), who was
intentionally fired at by the defenders of the fortress of Thorn, besieged by him, and who
said that the defenders were within their right, ought to settle the point.
[235] See Baty, International Law in South Africa (1900), pp. 84-85.

Refusal of Quarter.
§ 109. However, the rule that quarter must be given has its
exceptions. Although it has of late been a customary rule of
International Law, and although the Hague Regulations now
expressly stipulate by article 23 (d) that belligerents are prohibited
from declaring that no quarter will be given, quarter may
nevertheless be refused[236] by way of reprisal for violations of the
rules of warfare committed by the other side; and, further, in case of
imperative necessity, when the granting of quarter would so
encumber a force with prisoners that its own security would thereby
be vitally imperilled.[237] But it must be emphasised that the mere
fact that numerous prisoners cannot safely be guarded and fed by
the captors[238] does not furnish an exceptional case to the rule,
provided that no vital danger to the captors is therein involved. And
it must likewise be emphasised that the former rule is now obsolete
according to which quarter could be refused to the garrison of a
fortress carried by assault, to the defenders of an unfortified place
against an attack of artillery, and to the weak garrison who
obstinately and uselessly persevered in defending a fortified place
against overwhelming enemy forces.
[236]See Pradier-Fodéré, VII. Nos. 2800-2801, who opposes this principle but discusses
the subject in a very detailed way.
[237] See Payrat, Le Prisonnier de Guerre (1910), pp. 191-220, and Land Warfare, § 80.
[238] Accordingly, the Boers frequently during the South African War set free British
soldiers whom they had captured.

Lawful and Unlawful Means of killing and wounding Combatants.


§ 110. Apart from such means as are expressly prohibited by
treaties or custom, all means of killing and wounding that exist or
may be invented are lawful. And it matters not whether the means
used are directed against single individuals, as swords and rifles, or
against large bodies of individuals, as, for instance, shrapnel,
Gatlings, and mines. On the other hand, all means are unlawful that
render death inevitable or that needlessly aggravate the sufferings of
wounded combatants. A customary rule of International Law, now
expressly enacted by article 23 (e) of the Hague Regulations,
prohibits, therefore, the employment of poison and of such arms,
projectiles, and material as cause unnecessary injury. Accordingly:
wells, pumps, rivers, and the like from which the enemy draws
drinking water must not be poisoned; poisoned weapons must not
be made use of; rifles must not be loaded with bits of glass,
irregularly shaped iron, nails, and the like; cannons must not be
loaded with chain shot, crossbar shot, red-hot balls, and the like.
Another customary rule, now likewise enacted by article 23 (b) of
the Hague Regulations, prohibits any treacherous way of killing and
wounding combatants. Accordingly: no assassin must be hired and
no assassination of combatants be committed; a price may not be
put on the head of an enemy individual; proscription and outlawing
are prohibited; no treacherous request for quarter must be made; no
treacherous simulation of sickness or wounds is permitted.
Explosive Bullets.
§ 111. In 1868 a conference met at St. Petersburg for the
examination of a proposition made by Russia with regard to the use
of explosive projectiles in war. The representatives of seventeen
Powers—namely, Great Britain, Russia, Austria-Hungary, Bavaria,
Belgium, Denmark, France, Greece, Holland, Italy, Persia, Portugal,
Prussia and the North German Confederation, Sweden-Norway,
Switzerland, Turkey and Württemberg (Brazil acceded later) signed
on December 11, 1868, the so-called Declaration of St. Petersburg,
[239]
which stipulates that the signatory Powers, and those who
should accede later, renounce in case of war between themselves
the employment, by their military and naval troops, of any projectile
of a weight below 400 grammes (14 ounces) which is either
explosive or charged with fulminating or inflammable substances.
This engagement is obligatory only upon the contracting Powers,
and it ceases to be obligatory in case a non-contracting Power takes
part in a war between any of the contracting Powers.
[239] See above, vol. I. § 562, and Martens, N.R.G. XVIII. p. 474.

Expanding (Dum-Dum) Bullets.


§ 112. As Great Britain had introduced bullets manufactured at the
Indian arsenal of Dum-Dum, near Calcutta, the hard jacket of which
did not quite cover the core and which therefore easily expanded
and flattened in the human body, the First Hague Peace Conference
adopted a declaration signed on July 29, 1899, by fifteen Powers—
namely, Belgium, Denmark, Spain, Mexico, France, Greece,
Montenegro, Holland, Persia, Roumania, Russia, Siam, Sweden-
Norway, Turkey, and Bulgaria—stipulating that the contracting
Powers should abstain, in case of war between two or more of them,
from the use of bullets which expand or flatten easily in the human
body, such as bullets with hard envelopes which do not entirely
cover the core or are pierced with incisions. Austria-Hungary, China,
Germany, Italy, Nicaragua, Portugal, Japan, Luxemburg, Servia,
Switzerland, and Great Britain acceded later.
Projectiles diffusing Asphyxiating or Deleterious Gases.
§ 113. The First Hague Peace Conference also adopted a
Declaration, signed on July 29, 1899, by sixteen States—namely,
Belgium, Denmark, Spain, Mexico, France, Greece, Montenegro,
Holland, Persia, Portugal, Roumania, Russia, Siam, Sweden-Norway,
Turkey and Bulgaria—stipulating that the signatory Powers should in
a war between two or more of them abstain from the use of
projectiles the sole object of which is the diffusion of asphyxiating or
deleterious gases. Austria-Hungary, China, Germany, Italy, Japan,
Luxemburg, Nicaragua, Servia, Switzerland, and Great Britain
acceded later.

Violence directed from Air-Vessels.


§ 114. The First Hague Peace Conference adopted likewise a
Declaration, signed on July 29, 1899, prohibiting for a term of five
years the launching of projectiles or explosives from balloons or
other kinds of aerial vessels. The Second Peace Conference, on
October 18, 1907, renewed this Declaration up to the close of the
Third Peace Conference, but out of twenty-seven States which
signed the Declaration only seven—namely, Great Britain, the United
States of America, China, Holland, Bolivia, Salvador, Haiti (Nicaragua
acceded later)—ratified it, and Germany, France, Italy, Japan, Russia
—not to mention smaller Powers—did not even sign it. There is,
therefore, no doubt that the Third Peace Conference will not renew
the Declaration. Although it is very much to be regretted, the fact
must be taken into consideration that in future violence directed
from air-vessels will play a great part in war. For this reason, the
question as to the conditions under which such violence is
admissible, is of importance,[240] but it is as yet impossible to give a
satisfactory answer. The Institute of International Law, at its meeting
at Madrid in 1911, adopted the principle[241] that aerial warfare must
not comprise greater danger to the person and the property of the
peaceful population than land or sea warfare. However this may be,
there can be no doubt that the general principles laid down in the
Declaration of St. Petersburg of 1868, in the two Declarations,
adopted by the First Peace Conference, concerning expanding bullets
and projectiles diffusing asphyxiating or deleterious gases, in the
Hague rules concerning land warfare, and the like, must find
application as regards violence directed from air vessels.
[240] See, besides the literature quoted above, vol. I. p. 237, note 1, Mérignhac, pp. 198-
209; Bonfils, Nos. 14404-144021; Despagnet, No. 721 bis; Meyer, Die Luftschiffahrt in
kriegsrechtlicher Beleuchtung (1909); Philet, La guerre aérienne (1910); Nys, Fauchille,
and Bar in Annuaire, XIX. (1902), pp. 58-114, XXIV. (1911), pp. 23-126; Fauchille in R.G.
VIII. (1901), pp. 414-485.
[241] See Annuaire, XXIV. (1911), p. 346.

Violence against non-combatant Members of Armed Forces.


§ 115. It will be remembered from above, § 79, that numerous
individuals belong to armed forces without being combatants. Now,
since and in so far as these non-combatant members of armed
forces do not take part in the fighting, they may not directly be
attacked and killed or wounded. However, they are exposed to all
injuries indirectly resulting from the operations of warfare. And, with
the exception of the personnel[242] engaged in the interest of the
wounded, such as doctors, chaplains, persons employed in military
hospitals, official ambulance men, who, according to articles 9 and
10 of the Geneva Convention, are specially privileged, such non-
combatant members of armed forces may certainly be made
prisoners, since the assistance they give to the fighting forces may
be of great importance.
[242] See below, § 121.

Violence against Private Enemy Persons.


§ 116. Whereas in former[243] times private enemy persons of
either sex could be killed or otherwise badly treated according to
discretion, and whereas in especial the inhabitants of fortified places
taken by assault used to be abandoned to the mercy of the
assailants, in the eighteenth century it became a universally
recognised customary rule of the Law of Nations that private enemy
individuals should not be killed or attacked. In so far as they do not
take part in the fighting, they may not be directly attacked and killed
or wounded. They are, however, like non-combatant members of the
armed forces, exposed to all injuries indirectly resulting from the
operations of warfare. Thus, for instance, when a town is
bombarded and thousands of inhabitants are thereby killed, or when
a train carrying private individuals as well as soldiers is wrecked by a
mine, no violation of the rule prohibiting attack on private enemy
persons has taken place.
[243] See Grotius, III. c. 4, §§ VI. and IX.
As regards captivity, the rule is that private enemy persons may
not be made prisoners of war. But this rule has exceptions
conditioned by the carrying out of certain military operations, the
safety of the armed forces, and the order and tranquillity of occupied
enemy territory. Thus, for instance, influential enemy citizens who
try to incite their fellow-citizens to take up arms may be arrested
and deported into captivity. And even the whole population of a
province may be imprisoned in case a levy en masse is threatening.
[244]
[244]Civilians who render assistance to the enemy as drivers, or as labourers to
construct fortifications or siege works, or in a similar way, if captured while they are so
engaged, may not be detained as prisoners of war, whether they render these services
voluntarily or are requisitioned or hired. See Land Warfare, § 58 note (a).
Apart from captivity, restrictions of all sorts may be imposed upon,
and means of force may be applied against, private enemy persons
for many purposes. Such purposes are:—the keeping of order and
tranquillity on occupied enemy territory; the prevention of any
hostile conduct, especially conspiracies; the prevention of
intercourse with and assistance to the enemy forces; the securing of
the fulfilment of commands and requests of the military authorities,
such as those for the provision of drivers, hostages, farriers; the
securing of compliance with requisitions and contributions, of the
execution of public works necessary for military operations, such as
the building of fortifications, roads, bridges, soldiers' quarters, and
the like. What kind of violent means may be applied for these
purposes is in the discretion of the respective military authorities,
who on their part will act according to expediency and the rules of
martial law established by the belligerents. But there is no doubt
that, if necessary, capital punishment and imprisonment[245] are
lawful means for these purposes. The essence of the position of
private individuals in modern warfare with regard to violence against
them finds expression in article 46 of the Hague Regulations, which
lays down the rule that "family honours and rights, individual lives
and private property, as well as religious convictions and liberty,
must be respected."
[245] That in case of general devastation the peaceful population may be detained in so-
called concentration camps, there is no doubt; see below, § 154. And there is likewise no
doubt that hostages may be taken from the peaceful population; see below, § 170, p.
213, and § 259, p. 319, note 2.

Violence against the Head of the Enemy State and against Officials in Important
Positions.
§ 117. The head of the enemy State and officials in important
posts, in case they do not belong to the armed forces, occupy, so far
as their liability to direct attack, death, or wounds is concerned, a
position similar to that of private enemy persons. But they are so
important to the enemy State, and they may be so useful to the
enemy and so dangerous to the invading forces, that they may
certainly be made prisoners of war. If a belligerent succeeds in
obtaining possession of the head of the enemy State or its Cabinet
Ministers, he will certainly remove them into captivity. And he may
do the same with diplomatic agents and other officials of
importance, because by weakening the enemy Government he may
thereby influence the enemy to agree to terms of peace.

III
TREATMENT OF WOUNDED, AND DEAD BODIES

Hall, § 130—Lawrence, § 165—Maine, pp. 156-159—Manning, p. 205—Phillimore, III.


§ 95—Halleck, II. pp. 36-39—Moore, VII. § 1134—Taylor, §§ 527-528—Bluntschli,
§§ 586-592—Lueder in Holtzendorff, IV. pp. 289-319, 398-421—Liszt, § 40, V.—
Ullmann, § 178 and in R.G. IV. (1897), pp. 437-447—Bonfils, Nos. 1108-11187—
Despagnet, Nos. 551-553—Pradier-Fodéré, VI. No. 2794, VII. Nos. 2849-2881—
Rivier, II. pp. 268-273—Nys, III. pp. 526-536—Calvo, IV. §§ 2161-2165—Fiore, III.
Nos. 1363-1372, and Code, Nos. 1589-1604—Martens, II. § 114—Longuet, §§ 85-
90—Mérignhac, pp. 114-142—Pillet, pp. 165-192—Kriegsbrauch, p. 26—Land
Warfare, §§ 174-220—Zorn, p. 122—Bordwell, pp. 249-277—Spaight, pp. 419-460
—Higgins, pp. 35-38—Holland, Studies, pp. 61-65—Holland, War, Nos. 41-69—
Güret, Zur Geschichte der internationalen und freiwilligen Krankenpflege (1873)—
Lueder, Die Genfer Convention (1876)—Moynier, La croix rouge, son passé et son
avenir (1882); La revision de la Convention de Genève (1898); La fondation de la
croix rouge (1903)—Buzzati, De l'emploi abusif ... de la croix rouge (1890)—
Triepel, Die neuesten Fortschritte auf dem Gebiet des Kriegsrechts (1894), pp. 1-41
—Müller, Entstehungsgeschichte des rothen Kreuzes und der Genfer Konvention
(1897)—Münzel, Untersuchungen über die Genfer Konvention (1901)—Roszkoroski
in R.I. 2nd Ser. IV. (1902), pp. 199, 299, 442—Gillot, La revision de la Convention
de Genève, etc. (1902)—Meurer, Die Genfer Konvention und ihre Reform (1906)—
Delpech in R.G. XIII. (1906), pp. 629-724—Macpherson in Z.V. V. (1911), pp. 253-
277.

Origin of Geneva Convention.


§ 118. Although since the seventeenth century several
[246]

hundreds of special treaties have been concluded between different


States regarding the tending of each other's wounded and the
exemption of army surgeons from captivity, no general rule of the
Law of Nations on these points was in existence until the second half
of the nineteenth century other than one prohibiting the killing,
mutilation, or ill-treatment of the wounded. A change for the better
was initiated by Jean Henry Dunant, a Swiss citizen from Geneva,
who was an eye-witness of the battle of Solferino in 1859, where
many thousands of wounded died who could, under more favourable
circumstances, have been saved. When he published, in 1861 and
1863, his pamphlet, Un Souvenir de Solférino, the Geneva Société
d'utilité publique, under the presidency of Gustave Moynier, created
an agitation in favour of better arrangements for the tending of the
wounded on the battlefield, and convoked an international congress
at Geneva in 1863, where thirty-six representatives of nearly all the
European States met and discussed the matter. In 1864 the
Bundesrath, the Government of the Federal State of Switzerland,
took the matter in hand officially, and invited all European and
several American States to send official representatives to a
Congress at Geneva for the purpose of discussing and concluding an
international treaty regarding the wounded. This Congress met in
1864, and sixteen States were represented. Its result was the
international "Convention[247] for the Amelioration of the Condition of
Soldiers wounded in Armies in the Field," commonly called "Geneva
Convention," signed on August 22, 1864. By-and-by States other
than the original signatories joined the Convention, and finally the
whole body of the civilised States of the world, with the exception of
Costa Rica, Monaco, and Lichtenstein, became parties. That the rules
of the Convention were in no wise perfect, and needed to be
supplemented regarding many points, soon became apparent. A
second International Congress met at the invitation of Switzerland in
1868 at Geneva, where additional articles[248] to the original
Convention were discussed and signed. These additional articles
have, however, never been ratified. The First Hague Peace
Conference in 1899 unanimously formulated the wish that
Switzerland should shortly take steps for the assemblage of another
international congress in order to revise the Geneva Convention.
This Congress assembled in June 1906, thirty-five States having sent
representatives, and on July 6, 1906, a new Geneva Convention[249]
was signed by Great Britain, Germany, Argentina, Austria-Hungary,
Belgium, Bulgaria, Chili, China, Congo Free State, Korea, Denmark,
Spain, the United States of America, Brazil, Mexico, France, Greece,
Guatemala, Honduras, Italy, Japan, Luxemburg, Montenegro,
Norway, Holland, Peru, Persia, Portugal, Roumania, Russia, Servia,
Siam, Sweden, Switzerland, and Uruguay. Most of these States have
already ratified, and Colombia, Costa-Rica, Cuba, Nicaragua,
Salvador, Turkey, and Venezuela, which were not represented at the
Congress, acceded later. There is no doubt that in time all the
civilised Powers will become parties.
[246] See Macpherson, loc. cit. p. 254.
[247] See Martens, N.R.G. XVIII. p. 607, and above, vol. I. § 560.
[248] See Martens, N.R.G. XVIII. p. 61.
[249] See Martens, N.R.G. 3rd. Ser. II. (1910), p. 620, and Treaty Series, 1907, No. 15.
The new Convention consists of thirty-three articles instead of the
ten articles of the old Convention, and provides rules for the
treatment of the wounded and the dead; further rules concerning
military hospitals and mobile medical units; the personnel engaged
in the interest of the wounded including army chaplains; the material
belonging to mobile medical units, military hospitals, and voluntary
aid societies; the convoys of evacuation; the distinctive emblem; the
carrying out of the Convention; and the prevention of abuses and
infractions.
In the final protocol the Conference expresses the desire that, in
order to arrive at a unanimous interpretation of the Convention, the
parties should, so far as the cases and the circumstances permit,
submit to Hague Court Arbitration any differences which in time of
peace might arise between them concerning the interpretation of the
Convention, but Great Britain and Japan refused to become parties
to this.

The Wounded and the Sick.


§ 119. According to articles 1-5 of the Geneva Convention,[250] the
sick and wounded persons belonging, or officially attached, to
armies must be respected and taken care of, without distinction of
nationality, by the belligerent in whose power they may be. Should,
however, a belligerent necessarily be compelled to abandon such
sick and wounded persons to the enemy, he must, so far as military
exigencies permit, leave behind with them a portion of his medical
personnel to take care of them, and the necessary material. The sick
and wounded who have fallen into the hands of the enemy are
prisoners of war, but belligerents may exchange or release them, or
even hand them over to a neutral State which has to intern them
until after the conclusion of peace. After each engagement the
commander in possession of the field must have search made for the
wounded and must take measures to protect them against pillage
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