Programming In C With Microsoft Visual Studio 2010 Student Manual download
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
https://ebookbell.com/product/ms-10266a-programming-in-c-with-visual-
studio-2010-vol-1-student-manual-2581036
https://ebookbell.com/product/ms-course-10266a-programming-in-c-with-
microsoft-visual-studio-2010-trainer-edition-
volume-1-microsoft-2113632
https://ebookbell.com/product/ms-course-10266a-programming-in-c-with-
microsoft-visual-studio-2010-trainer-edition-
volume-2-microsoft-2113634
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
https://ebookbell.com/product/functional-programming-in-c-with-
categories-221-dimitris-papadimitriou-46704096
https://ebookbell.com/product/an-introduction-to-objectoriented-
programming-in-c-with-applications-in-computer-graphics-2nd-edition-
graham-m-seed-beng-4198618
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
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
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.
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 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
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.
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.
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
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.
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.
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.
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.
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
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;
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()
{
...
}
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
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.
The following code example shows the IPerson interface implemented explicitly.
int IPerson.Age
{
get { throw new NotImplementedException(); }
}
DateTime IPerson.DateOfBirth
Encapsulating Data and Defining Overloaded Operators 10-19
{
set { throw new NotImplementedException(); }
}
}
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
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.
int 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
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
7. Convert the public Salary field to a private field and rename it salary:
• Modify the following line of code.
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
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
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
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.
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.
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.
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;
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.
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.
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.
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
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
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.
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.
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.
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
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.
CHAPTER III
WARFARE ON LAND
I
ON LAND WARFARE IN GENERAL
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.
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.
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
ebookbell.com