
336
LESSON 28 Making generic classes
Lesson Requirements
Start a new project and give it an
ArrayMethods class.
Create a generic
Randomize method with one generic type parameter T. The method should
take as a parameter an array of
T and return an array of T.
Make the main program test the method.
Hints
Use the following code for the method’s body. Try to figure out the method’s declaration
yourself before you read the step-by-step instructions that follow.
// Make a Random object to use to pick random items.
Random rand = new Random();
// Make a copy of the array so we don’t mess up the original.
T[] randomizedItems = (T[])items.Clone();
// For each spot in the array, pick
// a random item to swap into that spot.
for (int i = 0; i < items.Length - 1; i++)
{
// Pick a random item j between i and the last item.
int j = rand.Next(i, items.Length);
// Swap item j into position i.
T temp = randomizedItems[i];
randomizedItems[i] = randomizedItems[j];
randomizedItems[j] = temp;
}
// Return the randomized array.
return randomizedItems;
Step-by-Step
Start a new project and give it an
ArrayMethods class.
1. This is reasonably straightforward. You don’t need to make the ArrayMethods class
generic.
Create a generic
Randomize method with one generic type parameter T. The method should
take as a parameter an array of
T and return an array of T.
1. The following code shows how you can implement ...