.NET Framework Arrays Introduce the System.Array class as the base class of all array types that contains methods for creating, manipulating, searching, and sorting arrays!. The followi
Trang 1Contents
Overview 1
Strings 2
Terminology – Collections 20
.NET Framework Collections 39
Lab 7: Working with Strings, Enumerators,
Review 63
Module 7: Strings, Arrays, and Collections
Trang 2domain 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
2001-2002 Microsoft Corporation All rights reserved
Microsoft, ActiveX, BizTalk, IntelliMirror, Jscript, MSDN, MS-DOS, MSN, PowerPoint, Visual Basic, Visual C++, Visual C#, Visual Studio, Win32, Windows, Windows Media, and Window NT are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A and/or other countries
The names of actual companies and products mentioned herein may be the trademarks of their respective owners
Trang 3Instructor Notes
After completing this module, students will be able to:
! Parse, format, manipulate, and compare strings
! Use the classes in the System.Array and System.Collections namespaces
! Improve the type safety and performance of collections by using specialized collections and class-specific code
Materials and Preparation
This section provides the materials and preparation tasks that you need to teach this module
Required Materials
To teach this module, you need the Microsoft® PowerPoint® file 2349B_07.ppt
Preparation Tasks
To prepare for this module, you should:
! Read all of the materials for this module
! Practice the demonstrations
! Complete the lab
Presentation:
120 Minutes
Lab:
60 Minutes
Trang 4Demonstrations
This section provides demonstration procedures that will not fit in the margin notes or are not appropriate for the student notes
Sorting and Enumerating an Array
In this demonstration, you will show students how to sort and enumerate an array.
The code for this demonstration is contained in one project and is located in
<install folder>\Democode\Mod07\Demo07.1 In addition, the code for the
individual demonstration is provided in the student notes
ArrayList
In this demonstration, you will show students how ArrayList implements the
IList interface by using an array whose size is dynamically increased as
required
The code for this demonstration is contained in one project and is located in
<install folder>\Democode\Mod07\Demo07.2 In addition, the code for the
individual demonstration is provided in the student notes
Hashtable
In this demonstration, you will show students how to create a hash table that is used for searches
The code for this demonstration is contained in one project and is located in
<install folder>\Democode\Mod07\Demo07.3 In addition, the code for the
individual demonstration is provided in the student notes
In all of the preceding demonstrations, use the debugger to step through the code while you point out features
Trang 5Module Strategy
Use the following strategy to present this module:
! Strings Discuss how to work with strings in the Microsoft NET Framework, including common operations, such as parsing, formatting, manipulating, and comparing strings
! Terminology – Collections Define the term collection as it is used in this module and identify where collections are found in the NET Framework Be sure that students understand that the term collection is used in its broader sense: to describe a group of items
! NET Framework Arrays
Introduce the System.Array class as the base class of all array types that
contains methods for creating, manipulating, searching, and sorting arrays Discuss features of arrays that are specific to C# Explain the role of the
IEnumerable and IEnumerator interfaces in System.Array and System.Collections classes
Use the Sorting and Enumerating an Array demonstration to show how to sort and enumerate an array
! NET Framework Collections
Briefly introduce some commonly used classes in the System.Collections
namespace
Discuss the IList interface with regards to classes that represent an ordered
collection of objects that can be individually indexed Use the ArrayList demonstration to reinforce this concept
Discuss the IDictionary interface and the classes that it implements Use the Hashtable demonstration to show how to use the IDictionary interface
Provide guidelines to help students distinguish between collections and arrays, and explain when collections are used
Discuss runtime casting for type safety and the effects of runtime casting, and boxing and unboxing on performance Discuss techniques for handling boxing and unboxing to optimize performance
Trang 7Overview
! Strings
! Terminology – Collections
! .NET Framework Arrays
! .NET Framework Collections
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
In this module, you will learn about some of the key classes in the Microsoft®
.NET Framework class library Specifically, you will learn how to work with strings, arrays, collections, and enumerators
After completing this module, you will be able to:
! Parse, format, manipulate, and compare strings
! Use the classes in the System.Array and System.Collections namespaces
! Improve the type safety and performance of collections by using specialized collections and class-specific code
In this module, you will learn
about some of the key
classes in the NET
Framework class library
Trang 8! Trim and Pad
! Split and Join
! StringBuilder
! C# Specifics
! Regular Expressions
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
In the C# language, string is an alias for System.String in the NET Framework The System.String type represents a string of Unicode characters
Working with strings is an everyday task in software development, and includes operations, such as parsing, formatting, manipulating, and comparing strings
The String object is immutable Therefore, every time you use one of the methods in the System.String class, you create a new string object When you
want to perform repeated modifications to a string, the overhead that is
associated with creating a new String object can be costly As an alternative, you can use the System.Text.StringBuilder class to modify a string without
creating a new object
In this section, you will learn how to work with strings in the NET Framework
Topic Objective
To introduce the topics in
the section
Lead-in
In this section, you will learn
how to work with strings in
the NET Framework
Trang 9Parse
! Parse Method Converts a Numeric String to a Numeric
! To Ignore Commas, Use the NumberStyles.AllowThousands Flag
// The output to the console is "123456"
string MyString = "123,456";
int MyInt = int.Parse(MyString, System.Globalization.NumberStyles.AllowThousands);Console.WriteLine(MyInt);
// The output to the console is "123456"
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
The Parse method converts a string that represents a NET Framework numeric
base type to an actual NET Framework numeric base type
The Parse method takes a combination of up to three parameters, as follows:
! The string to be converted
! One or more values from the System.Globalization.NumberStyles
enumeration
! A NumberFormatInfo class Because the Parse method assumes that all string input represents a base-10 value, non-base-10 values are not parsable The Parse method also does not parse strings that represent the values NaN (Not A Number), PositiveInfinity,
or NegativeInfinity of the Single and Double classes because they are not real
numbers
The following code example converts a string to an int value, increments that
value, and displays the result:
To explain how the Parse
method is used to convert
numeric strings to a NET
Framework numeric base
type
Lead-in
The Parse method converts
a string that represents a
.NET Framework numeric
base type to an actual NET
Framework numeric base
type
Trang 10Handling Nonnumeric Characters
The NumberStyles enumeration is useful if you have a string that contains
nonnumeric characters that you want to convert into a NET Framework numeric base type You must use this enumeration to parse a string with a currency symbol, decimal point, exponent, parentheses, and so on
For example, a string that contains a comma cannot be converted to an int value by using the Parse method unless you pass the
System.Globalization.NumberStyles enumeration
Incorrect Way to Parse a String with Nonnumeric Characters
The following code example is invalid and raises an exception It illustrates the incorrect way to parse a string that contains nonnumeric characters
exception in the preceding example
The following code example uses the same string as the preceding example but does not raise an exception
Trang 11***************************** ILLEGAL FOR NON - TRAINER USE ******************************
The NET Framework provides several format strings, or specifiers, that you can use to format the appearance of strings that derive from other objects There are several advantages to converting base data types to strings before displaying them to users Strings are easily displayed and can be appended to the messages and dialog boxes of your application You can also use format specifiers to display the same numeric value in scientific format, monetary format, hexadecimal format, and so on
When to Use Format Strings
You can use format specifiers in situations where your application stores information in a format that is designed for use by the application, and not by the user For example, a business application may keep track of the current date
and time in a DateTime object to log when transactions are completed The
DateTime object stores information in which the user is not necessarily
interested, such as the number of milliseconds that have elapsed since the creation of the object
You can also use format specifiers to display only information that is of interest
to the user, such as the date and hour of the transaction Additionally, you can dynamically modify strings that are created by using format specifiers to represent monetary, date, and time conventions for the current culture For example, your application can display the date and time in the notation that is specific to the user’s current culture
Topic Objective
To explain how to use
format strings, or specifiers,
to format the appearance of
your application
Lead-in
The NET Framework
provides several format
strings that you can use to
format the appearance of
strings that derive from
other objects
Trang 12Methods Used with Format Strings
Format strings are used with any method that creates a string representation of a
.NET Framework data type, such as Int32, Int64, Single, Double,
Enumeration, DateTime, and so on Format strings are also used with Console.Writeline, String.Format, and several methods in the System.IO
namespace
Additionally, every base data type contains a ToString method that returns a
string representation of the data type’s value and accepts a string format specifier You can control the layout and design of strings that are created by any of these methods by using one of several format strings defined by the NET Framework
Using the ToString Method The ToString method is useful if you want to convert one of the standard NET
Framework data types to a string that represents that type in some other format
For example, if you have an integer value of 100 that you want to represent to the user as a currency value, you can easily use the ToString method and the
currency format string ("C") to produce a string of "$100.00" The original value that is contained in the data type is not converted, but a new string is returned that represents the resulting value This new string cannot be used for calculation until it is converted back to a NET base data type The original value, however, can be calculated at any time
Computers that do not have U.S English specified as the current culture will display whatever currency notation is used by the current culture
In the following code example, the ToString method displays the value of 100
as a currency-formatted string in a console window:
argument and can produce the same value as the preceding example
Console.Writeline accepts string format specifiers in the form, where the
characters inside the curly brackets specify the formatting to apply to the variable
The following code example uses the Console.WriteLine method to format the
value of MyInt to a currency value
int MyInt = 100;
Console.WriteLine("{0:C}", MyInt);
In the preceding example, the 0 character specifies the variable or value on which to apply formatting In this example, it is the first and only variable The characters that follow the colon are interpreted as string format specifiers
Note
Trang 13string MyString = MyInt.ToString("C" );
// In the U.S English culture: "$12,345.00"
int MyInt = 12345;
string MyString = MyInt.ToString("C" );
// In the U.S English culture: "$12,345.00"
DateTime MyDate = new DateTime(2000, 1, 10, 0, 0, 0);
string MyString = MyDate.ToString( "d" );
// In the U.S English culture: "1/10/2000"
DateTime MyDate = new DateTime(2000, 1, 10, 0, 0, 0);
string MyString = MyDate.ToString( "d" );
// In the U.S English culture: "1/10/2000"
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
The standard numeric, picture numeric, date and time, and enumeration format strings are described in detail in the NET Framework Software Development Kit (SDK) This topic provides examples of these format strings
The following examples show the use of the format string that returns the value
of MyInt in the currency format:
int MyInt = 12345;
string MyString = MyInt.ToString( "C" );
// In the U.S English culture, MyString has the value:
Example Format Pattern (en-US)
and short time)
Dd MMMM yyyy HH:mm
date and long time)
Dd MMMM yyyy HH:mm:ss
Topic Objective
To provide examples of
format strings that return
common numeric string
types
Lead-in
Let’s look at some examples
of format strings that return
the value of MyString in the
currency and date time
formats
Trang 14The following example shows the use of the format string that returns the value
of MyDate in the short date pattern format:
DateTime MyDate = new DateTime(2000, 1, 10, 0, 0, 0);
string MyString = MyDate.ToString( "d" );
// In the U.S English culture, MyString has the value: // "1/10/2000"
Trang 15Changing Case
! You Can Easily Change the Case of a String
# String.ToUpper – converts to upper case
# String.ToLower – converts to lower case
string MyString = "hello world!";
// outputs: HELLO WORLD!
Console.WriteLine(MyString.ToUpper());
string MyString = "hello world!";
// outputs: HELLO WORLD!
Console.WriteLine(MyString.ToUpper());
string MyString = "HELLO WORLD!";
// outputs: hello world!
Console.WriteLine(MyString.ToLower());
string MyString = "HELLO WORLD!";
// outputs: hello world!
Console.WriteLine(MyString.ToLower());
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
You can easily change the case of a string by using the two methods that are described in the following table
String.ToUpper Converts all characters in a string to uppercase
String.ToLower Converts all characters in a string to lowercase
String.ToUpper and String.ToLower provide an override that accepts a
The preceding example displays HELLO WORLD! to the console
The String.ToLower method is similar to the String.ToUpper method, but it
converts all of the characters in a string to lowercase
The following code example converts the string "HELLO WORLD!" to lowercase string MyString = "HELLO WORLD!";
You can easily change the
case of a string by using the
String.ToUpper and
String.ToLower methods
Trang 16Compare
! The NET Framework Has Methods to Compare Strings
# For example, the Compare method compares the
current string object to another string or object, returning:
- Negative if first string is less than second string
- 0 if the two strings are equal
- Positive if first string is greater than second string
string MyString = "Hello World!";
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
The NET Framework provides several methods to compare the values of strings The following table describes some of the value-comparison methods
Method Name Use String.Compare Compares the values of two strings Returns an integer value
String.StartsWith Determines if a string begins with the string passed Returns a
boolean value
String.IndexOf Returns the index of the first occurrence of a String, or one or
more characters, within this instance
For more information about value comparison methods and for a complete list
of these methods, see “Comparing Strings” in the NET Framework SDK documentation
For example, the String.Compare method provides a thorough way to compare
the current string object to another string or object You can use this function to compare two strings or substrings of two strings
Additionally, overloads are provided that regard or disregard case and cultural variance
Topic Objective
To introduce some of the
value-comparison methods
that are used to compare
the values of strings
Lead-in
The NET Framework
provides several
value-comparison methods to
compare the values of
strings
Trang 17The following table shows the three integer values that are returned by the
Compare(string strA, string strB) method
The following code example uses the Compare method to determine whether
two strings are the same
string MyString = "Hello World!";
Console.WriteLine(String.Compare(MyString, "Hello World!")); The preceding example displays 0 to the console
Trang 18Trim and Pad
! Trim Methods Remove Spaces
! Pad Methods Expand a Specific Number of Characters
string MyString = " Big ";
Console.WriteLine("Hello{0}World!", MyString ); string TrimString = MyString.Trim();
Console.WriteLine("Hello{0}World!", TrimString );
// outputs the following lines to the console:
//Hello Big World!
//HelloBigWorld!
string MyString = " Big ";
Console.WriteLine("Hello{0}World!", MyString ); string TrimString = MyString.Trim();
Console.WriteLine("Hello{0}World!", TrimString );
// outputs the following lines to the console:
//Hello Big World!
//HelloBigWorld!
string MyString = "Hello World!";
Console.WriteLine(MyString.PadLeft(20, '-'));
// outputs the following line to the console:
// -Hello World! to the console
string MyString = "Hello World!";
Console.WriteLine(MyString.PadLeft(20, '-'));
// outputs the following line to the console:
// -Hello World! to the console
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
When you want to remove or extend the spaces around strings, the
System.String class provides methods for trimming and padding strings
The following table describes two of the available trim methods
Method Name Use String.Trim Removes white spaces from the beginning and end of a string
String.Remove Removes a specified number of characters from a specified index
position in a string
For example, you can easily remove white spaces from both ends of a string by
using the String.Trim method, as shown in the following code example
string MyString = " Big ";
Console.WriteLine("Hello{0}World!", MyString );
string TrimString = MyString.Trim();
Console.WriteLine("Hello{0}World!", TrimString );
This code outputs the following lines to the console:
Hello Big World!
HelloBigWorld!
For a complete list of trim methods in the System.String class, see “Trimming
and Removing Characters” in the NET Framework SDK documentation
Topic Objective
To explain how to use
methods of the
System.String class to trim
and pad strings
Lead-in
You can remove or extend
the spaces around strings
by using methods of the
System.String class
Trang 19Padding
System.String also provides methods that you can use to create a new version
of an existing string that is expanded by a specific number of characters
The following table describes the available pad methods
Method Name Use String.PadLeft Right aligns and pads a string, so its rightmost character is a
specified distance from the beginning of the string
String.PadRight Left aligns and pads a string, so its rightmost character is a
specified distance from the beginning of the string
For example, the String.PadLeft method creates a new string that moves an
existing string to the right, so its last character is a specified number of spaces from the first index of the string White spaces are inserted if you do not use an override that allows you to specify your own custom padding character
The following code example uses the PadLeft method to create a new string
with a total length of 20 spaces
string MyString = "Hello World!";
Console.WriteLine(MyString.PadLeft(20, '-'));
This example displays the following text to the console
-Hello World!
Trang 20Split and Join
! Split Method Is Used to Break Up a String Into an Array of Substrings
characters parameter
assumed to be the separator
! Join Method Is Used to Concatenate Strings
string array
string Line = "Hello World";
string[] Words = Line.Split(null);
// Words[0] = "Hello" and Words[1] = "World"
string Line = "Hello World";
string[] Words = Line.Split(null);
// Words[0] = "Hello" and Words[1] = "World"
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
The System.String class provides the Split method to break up strings and the
Join method to concatenate strings
The Split Method
You use the Split method to break up a string instance into an array of
substrings at the positions that are specified by separator characters If separator
characters are omitted, that is to say, if the parameter is null, the whitespace
characters are assumed to be the separator If the separator is a zero-length string, a single-element array that contains the entire expression string is returned
The following example shows how to break up a string into a string array of words:
string Line = "Hello World";
string[] Words = Line.Split(null);
// Words[0] = "Hello" and Words[1] = "World"
The Join Method
You use the Join method to concatenate a specified separator string between each element of a specified String array, which yields a single concatenated string If the separator is omitted, that is to say null, the space character (" ")
is used If the separator is a zero-length string (""), all of the items in the list are concatenated with no delimiters
Topic Objective
To explain how to use the
Split and Join methods to
break up and concatenate
strings
Lead-in
The System.String class
provides the Split method to
break up strings and the
Join method to concatenate
strings
For Your Information
You should cover the
String.Split method
because it is used in the lab
Trang 21StringBuilder
! The String Object is Immutable
! System.Text.StringBuilder – Allows You to Modify a String Without Creating a New Object
! You Can Specify the Maximum Number of Characters
! Methods Include:
# Append, AppendFormat, Insert, Remove, and Replace
StringBuilder MyStringBuilder = new StringBuilder("Hello");
// MyStringBuilder can hold a maximum of 25 characters StringBuilder MyStringBuilder =
new StringBuilder("Hello World!", 25);
// MyStringBuilder can hold a maximum of 25 characters StringBuilder MyStringBuilder =
new StringBuilder("Hello World!", 25);
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
The String object is immutable Therefore, every time you use one of the methods in the System.String class, you create a new string object When you
want to perform repeated modifications to a string, the overhead that is
associated with creating a new String object can be costly As an alternative, you can use the System.Text.StringBuilder class to modify a string without
creating a new object
Creating a StringBuilder Object
You can create a new instance of the StringBuilder object by initializing your
variable with one of the overloaded constructor methods, as shown in the following code example:
StringBuilder MyStringBuilder = new StringBuilder("Hello");
Although the StringBuilder object is a dynamic object that allows you to
expand the number of characters in the string that it encapsulates, you can specify a value for the maximum number of characters that it can hold This
value is called the capacity of the object and must not be confused with the
length of the string that the current StringBuilder object holds Any attempt to expand the StringBuilder class beyond the maximum range causes an
ArgumentOutOfRangeException to be thrown
The following code example specifies that the MyStringBuilder object can be
expanded to a maximum of 25 spaces
StringBuilder MyStringBuilder = new StringBuilder("Hello World!", 25);
Topic Objective
To explain how to use the
StringBuilder method to
modify a string without
creating a new object
class to modify a string
without creating a new
object
Trang 22StringBuilder Methods
The following table describes the methods that you can use to modify the
contents of the StringBuilder object
StringBuilder.Append Appends information to the end of the current
StringBuilder object
StringBuilder.AppendFormat Replaces zero or more format specifications with
the appropriately formatted value of an object
StringBuilder.Insert Inserts a string or object into the specified index of
the current StringBuilder object
StringBuilder.Remove Removes a specified number of indexes from the
current StringBuilder object
StringBuilder.Replace Replaces a specified index or character with the
passed character
Trang 23C# Specifics
! C# string Type Is a String of Unicode Characters
not references
// rather than "c:\\Docs\\Source\\a.txt"
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
The string type represents a string of Unicode characters; string is an alias for
System.String in the NET Framework
Although string is a reference type, the equality (==) operator and the inequality (!=) operator are defined to compare the values of string objects, not the references Comparing the values of string objects makes testing for string
equality more intuitive, as in the following example:
string a = "hello";
string b = "hello";
Console.WriteLine( a == b ); // output: True same value
The + operator concatenates strings, as in the following example:
string a = "good " + "morning";
The [ ] operator accesses individual characters of a string, as in the following
example:
char x = "test"[2]; // x = 's';
String literals are of type string and can be written in two forms: quoted and
@-quoted Quoted string literals are enclosed in quotation marks ("), as in the following example:
"good morning" // a string literal Quoted string literals can also contain any character literal, including escape sequences, as in the following example:
string a = "\\\u0066\n"; // backslash, letter f, new line
Topic Objective
To explain what the string
type is in the NET
Framework and to describe
the functions of the +, [ ],
and != operators, and
alias for System.String in
the NET Framework
Trang 24@-quoted string literals start with @ and are enclosed in quotation marks, as in the following example:
@"good morning" // a string literal The advantage of using @-quoted string literals is that escape sequences are not processed This makes it easy to write a fully qualified file name, as in the following example:
@"c:\Docs\Source\a.txt"
// rather than "c:\\Docs\\Source\\a.txt"
To include a quoted phrase in an @-quoted string, use two pairs of double quotation marks, as in the following example:
@"""Ahoy!"" cried the captain." // "Ahoy!" cried the captain The following code example uses the C# features that are discussed in this topic:
using System;
class test {
public static void Main( String[] args ) {
True
Trang 25Regular Expressions
! Regular Expressions – Powerful Text Processing
! Pattern-Matching Notation Allows You to:
# Find specific character patterns
# Extract, edit, replace, or delete text substrings
# Add the extracted strings to a collection to generate
a report
! Designed to be Compatible With Perl 5
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
Regular expressions provide a powerful, flexible, and efficient method to process text The extensive pattern-matching notation of regular expressions allows you to quickly parse large amounts of text to find specific character patterns; to extract, edit, replace, or delete text substrings; and to add the extracted strings to a collection in order to generate a report
For many applications that deal with strings, such as HTML processing, log file parsing, and HTTP header parsing, regular expressions are an essential tool The NET Framework regular expressions incorporate the most popular features
of other regular expression implementations, such as those used in Perl and awk Designed to be compatible with Perl 5 regular expressions, NET Framework regular expressions include features that are not yet available in other implementations, such as right-to-left matching and dynamic compilation The NET Framework regular expression classes are part of the NET
Framework class library and can be used with any language or tool that targets the common language runtime, including ASP.NET and Microsoft
Visual Studio® NET
A detailed explanation of how to use the regular expression classes is beyond the scope of this course For more information about using regular expression classes, see the NET Framework SDK documentation
Topic Objective
To briefly describe how
regular expressions can be
used in the NET
Framework
Lead-in
Regular expressions allow
you to quickly parse large
amounts of text in order to
find specific character
patterns; to extract, edit,
replace, or delete text
substrings; and to add the
expressions Do not spend
much time on this slide, but
encourage students to refer
to the NET Framework
SDK, especially for details
about using the regular
expression classes
Trang 26***************************** ILLEGAL FOR NON - TRAINER USE ******************************
In this module, the term collection is used in its broader sense to refer to a group of items In the NET Framework, examples of collections are found in
the namespaces System.Array, and System.Collections
Topic Objective
To define the term collection
as it is used in this module
and to identify where
collections are found in the
.NET Framework
Lead-in
In this module, the term
collection is used in its
broader sense: to describe a
group of items
Do not spend much time on
this slide The objective of
this slide is to define the
term collection clearly,
before discussing the
collections that are found in
the NET Framework
Trang 27" NET Framework Arrays
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
The System.Array class is the base class of all array types and contains methods for creating, manipulating, searching, and sorting arrays The Array class is not part of the Collections namespace However, it is still a collection because it is based on the IList interface
In an array style of collection, an item in the collection is referred to by the term
element Specific elements are identified by their array index The low bound or
lower bound of an Array is the index of its first element
To understand the functionality of the various collection classes, you must understand their key interfaces In this section, you will learn about the
interfaces that are used by the methods of System.Array
Topic Objective
To introduce the topics in
the section
Lead-in
The System.Array class is
the base class of all array
types and contains methods
for creating, manipulating,
searching, and sorting
arrays
Trang 28System.Array
! System.Array Is the Base Class of All Array Types
! Arrays Implement the Following Interfaces
# ICloneable, IList, ICollection, and IEnumerable
! System.Array Has Methods For
# Creating, manipulating, searching, and sorting
! Null, Empty String, and Empty (0 item) Arrays Should Be Treated the Same
# Therefore, return an Empty array, instead of a null reference
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
The System.Array class is the base class of all array types and contains
methods for creating, manipulating, searching, and sorting arrays Arrays are always allocated on the garbage-collected heap Arrays can be single dimensional or multidimensional You can also create arrays of arrays, called
jagged arrays
For optimum performance, it is highly recommended that each rank of an array
be zero-based Additionally, each rank of an array must be zero-based when passing arrays between programming languages
Defining an Array Type
You define an array type by specifying the element type of the array, the rank,
or number of dimensions, of the array, and the upper and lower bounds of each dimension of the array All of these details are included in any signature of an array type
The runtime automatically creates exact array types as they are required No separate definition of the array type is needed Arrays of a particular type can only hold elements of that type If you need to manipulate a set of unlike objects or value types, consider using one of the collection types that are
defined in the System.Collections namespace
Topic Objective
To explain how array types
are used and defined
Lead-in
The System.Array class is
the base class of all array
types and contains methods
for creating, manipulating,
searching, and sorting
arrays
Trang 29Methods and Properties of System.Array
Some of the methods and properties for the System.Array class are described
in this topic Many of these methods are used to implement the class’s interfaces
System.Array implements the interfaces that are described in the following
table
Interface Use ICloneable Supports cloning, which creates a new instance of a class with the
same value as an existing instance
IList Represents a collection of objects that can be individually
The interfaces that are listed in the preceding table are supported not only by
arrays but also by many of the System.Collections classes Subsequent topics
in this module discuss specific interfaces and the classes that implement them The following tables describe some of the public members that are available
through the System.Array class
Static Method Use BinarySearch Overloaded Searches a one-dimensional sorted Array for a
value, using a binary search algorithm
CreateInstance Overloaded Initializes a new instance of the Array class
Sort Overloaded Sorts the elements in one-dimensional Array
objects
Property Use IsFixedSize Gets a value that indicates whether the Array has a fixed size
IsReadOnly Gets a value that indicates whether the Array is read-only
Length Gets the total number of elements in all of the dimensions of the
Array
Rank Gets the rank (number of dimensions) of the Array
The IsFixedSize and IsReadOnly properties are always false unless they
are overridden by a derived class
Note
Trang 30The following table describes some of the public instance methods that are
available through the System.Array class
Instance Method Use Clone Creates a shallow copy of the Array
GetEnumerator Returns an IEnumerator for the Array
GetLength Gets the number of elements in the specified dimension of the
Array
GetLowerBound Gets the lower bound of the specified dimension in the Array
GetUpperBound Gets the upper bound of the specified dimension in the Array
GetValue Overloaded Gets the values of the Array elements at the
specified indexes
SetValue Overloaded Sets the specified Array elements to the specified
value
For complete lists of public members of the System.Array class, see “Array
Members” in the NET Framework SDK documentation
Empty Arrays
Nulls should only be returned by reference properties that refer to another
object or component String and Array properties should never return null,
because a programmer typically does not expect null in this context For example, a programmer typically would assume that the following code works: public void DoSomething(…) {
string[] sa = SomeOtherFunc();
// The following line assumes sa is never null
if (sa.Length > 0) { // do something else }
} Generally, null, empty string, and empty (0 item) arrays should be treated in the
same way Therefore, return an Empty array, instead of a null reference
Trang 31C# Specifics
! C# Array Indexes Start at Zero
! Declaring an Array – Size Is Not Part of Its Type
! Creating an Array
! Initializing an Array
! Using System.Array Members
int[] numbers; // declare numbers as
// an int array of any size
int[] numbers; // declare numbers as
// an int array of any sizeint[] numbers = new int[5]; // declare and create
int[] numbers = {1, 2, 3, 4, 5};
int LengthOfNumbers = numbers.Length;
int[] numbers = {1, 2, 3, 4, 5};
int LengthOfNumbers = numbers.Length;
int[] numbers = new int[5] {1, 2, 3, 4, 5};
***************************** ILLEGAL FOR NON - TRAINER USE ******************************
C# arrays are zero-indexed That means the array indexes start at zero Arrays
in C# and arrays in most other popular languages work similarly, but there are a few differences that you should be aware of
When declaring an array, the brackets ([]) must come after the type, and not after the identifier Placing the brackets after the identifier is not legal syntax in C#, as shown in the following example:
int[] table; // not int table[];
In addition, and unlike the C language, the size of the array is not part of its
type This allows you to declare and assign to an array any array of int objects,
regardless of the array’s length, as in the following examples
int[] numbers; // declare numbers as an int array of any size numbers = new int[10]; // numbers is a 10-element array numbers = new int[20]; // now it's a 20-element array
Topic Objective
To explain features that are
unique to C# arrays
Lead-in
C# arrays are similar to
arrays in most other popular
languages, but you should
be aware of the differences
that are presented in this
topic
Trang 32The following code examples show the syntax to create an array for each of the arrays already discussed:
int[] numbers = new int[5]; // Single-dimensional array string[,] names = new string[5,4]; // Multi-dimensional array byte[][] scores = new byte[5][]; // Array-of-arrays
for (int x = 0; x < scores.Length; x++) {
scores[x] = new byte[4];
}
Trang 33The following example shows a complete C# program that declares and instantiates arrays as discussed in this topic
using System;
class DeclareArraysSample {
public static void Main() {
// Single-dimensional array int[] numbers = new int[5];
// Multidimensional array string[,] names = new string[5,4];
// Array-of-arrays (jagged array) byte[][] scores = new byte[5][];
// Create the jagged array for (int i = 0; i < scores.Length; i++) {
scores[i] = new byte[i+3];
} // Print length of each row for (int i = 0; i < scores.Length; i++) {
Console.WriteLine("Length of row {0} is {1}",
} } } The preceding program displays the following output:
Length of row 0 is 3 Length of row 1 is 4 Length of row 2 is 5 Length of row 3 is 6 Length of row 4 is 7
Trang 34Single-Dimensional Array
The following examples show different ways to initialize single-dimensional arrays:
int[] numbers = new int[5] {1, 2, 3, 4, 5};
string[] names = new string[3] {"Matt", "Joanne", "Robert"}; You can omit the size of the array, as in the following examples:
int[] numbers = new int[] {1, 2, 3, 4, 5};
string[] names = new string[] {"Matt", "Joanne", "Robert"};
If an initializer is provided, you can also omit the new statement, as in the
You can omit the size of the array, as in the following examples:
int[,] numbers = new int[,] { {1, 2}, {3, 4}, {5, 6} }; string[,] siblings = new string[,] { {"Mike","Amy"}, {"Mary","Ray"} };
If an initializer is provided, you can also omit the new statement, as in the
following examples:
int[,] numbers = { {1, 2}, {3, 4}, {5, 6} };
string[,] siblings = { {"Mike", "Amy"}, {"Mary", "Albert"} };
Trang 35Jagged Array (Array-of-Arrays)
The following examples show different ways to initialize jagged arrays You can initialize jagged arrays by using the following style:
int[][] numbers = new int[2][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };
You can omit the size of the first array, as in the following example:
int[][] numbers = new int[][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };
Accessing Array Members
Accessing array members in C# is straightforward and similar to how you access array members in C and C++ For example, the following code creates
an array called numbers and then assigns 5 to the fifth element of the array: int[] numbers = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
numbers[4] = 5;
The following code example declares a multidimensional array and assigns 5 to the member located at [1, 1]:
int[,] numbers = { {1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10} }; numbers[1, 1] = 5;
The following code example shows how to access a member of a jagged array: int[][] numbers = new int[][]
{ new int[] {1, 2}, new int[] {3, 4}
int LengthOfNumbers = numbers.Length;
The System.Array class provides many other useful methods and properties,
such as methods for sorting, searching, and copying arrays