logo
Учебник_ПОА

Arrays of Objects

Creating an array of objects, rather than an array of simple data types such as integers, is a two-part process. First you declare the array, and then you must create the objects that are stored in the array. This example creates a class that defines an audio CD. It then creates an array that stores 20 audio CDs.

namespace CDCollection

{

// Define a CD type.

class CD

{

private string album;

private string artist;

private int rating;

public string Album

{

get {return album;}

set {album = value;}

}

public string Artist

{

get {return artist;}

set {artist = value;}

}

public int Rating

{

get {return rating;}

set {rating = value;}

}

}

class Program

{

static void Main(string[] args)

{

// Create the array to store the CDs.

CD[] cdLibrary = new CD[20];

// Populate the CD library with CD objects.

for (int i=0; i<20; i++)

{

cdLibrary[i] = new CD();

}

// Assign details to the first album.

cdLibrary[0].Album = "See";

cdLibrary[0].Artist = "The Sharp Band";

cdLibrary[0].Rating = 10;

}

}}