Monday 15 March 2010

Creating an array of objects in C#

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 = "Must See";
cdLibrary[0].Artist = "Anonymous";
cdLibrary[0].Rating = 5;
}
}
}

Collections

An array is just one of many options for storing sets of data by using C#. The option that you select depends on several factors, such as how you intend to manipulate or access the items. For example, a list is generally faster than an array if you must insert items at the beginning or in the middle of the collection. Other types of collection classes include map, tree, and stack; each one has its own advantages. For more information, see System.Collections, and System.Collections.Generic.

The following example shows how to use the List<(Of <(T>)>) class. Notice that unlike the Array class, items can be inserted into the middle of the list. This example restricts the items in the list so that they must be strings.


public class TestCollections
{
public static void TestList()
{
System.Collections.Generic.List sandwich = new System.Collections.Generic.List();

sandwich.Add("A");
sandwich.Add("B");

sandwich.Insert(1, "C");

foreach (string ingredient in sandwich)
{
System.Console.WriteLine(ingredient);
}
}
}
// Output:
// A
// B
// C


No comments:

Post a Comment