illustrates the use of an array of objects
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
Example10_10.cs illustrates the use of
an array of objects
*/
using System;
// declare the Star class
class Star
{
// declare two fields
public string name;
public int brightness;
// declare a constructor
public Star(
string name,
int brightness
)
{
this.name = name;
this.brightness = brightness;
}
}
public class Example10_10
{
public static void Main()
{
// create the galaxy array of Star objects
Star[,,] galaxy = new Star[10, 5, 3];
// create two Star objects in the galaxy array
galaxy[1, 3, 2] = new Star("Sun", 3);
galaxy[4, 1, 2] = new Star("Alpha Centuri", 9);
// display the Rank and Length properties of the galaxy array
Console.WriteLine("galaxy.Rank (number of dimensions) = " + galaxy.Rank);
Console.WriteLine("galaxy.Length (number of elements) = " + galaxy.Length);
// display the galaxy array elements
for (int x = 0; x < galaxy.GetLength(0); x++)
{
for (int y = 0; y < galaxy.GetLength(1); y++)
{
for (int z = 0; z < galaxy.GetLength(2); z++)
{
if (galaxy[x, y, z] != null)
{
Console.WriteLine("galaxy[" + x + ", " + y + ", " + z +"].name = " +
galaxy[x, y, z].name);
Console.WriteLine("galaxy[" + x + ", " + y + ", " + z +"].brightness = " +
galaxy[x, y, z].brightness);
}
}
}
}
}
}
Related examples in the same category