
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
302
|
Chapter 5: Collections
from the array. The InsertIntoArray method will insert an item into the array with-
out overwriting any data that already exists in the array. The
RemoveFromArray will
remove an element from the array:
using System;
public class ArrayUtilities
{
public void InsertIntoArray(Array target,
object value, int index)
{
if (index < target.GetLowerBound(0) ||
index > target.GetUpperBound(0))
{
throw (new ArgumentOutOfRangeException("index", index,
"Array index out of bounds."));
}
else
{
Array.Copy(target, index, target, index + 1,
target.Length - index - 1);
}
target.SetValue(value, index);
}
public void RemoveFromArray(Array target, int index)
{
if (index < target.GetLowerBound(0) ||
index > target.GetUpperBound(0))
{
throw (new ArgumentOutOfRangeException("index", index,
"Array index out of bounds."));
}
else if (index < target.GetUpperBound(0))
{
Array.Copy(target, index + 1, target, index,
target.Length - index - 1);
}
target.SetValue(null, target.GetUpperBound(0));
}
}
Discussion
The InsertIntoArray and RemoveFromArray methods make use of the Array.Copy static
method to perform their operations. Initially, both methods test to see whether an
item is being added or removed within the bounds of the array
target. If the item
passes this test, the
Array.Copy method ...