Skip to content

2.5 Arrays of objects

  1. Change the code of the Main method as follows:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    Circle[] myCircleArray = new Circle[3];
    myCircleArray[0] = new Circle(3, 1, 4, "green");
    myCircleArray[1] = new Circle();
    myCircleArray[2] = new Circle(6);
    
    for (int i = 0; i < myCircleArray.Length; i++)
    {
        Console.WriteLine(myCircleArray[i].CalculatePerimeter());
        Console.WriteLine(myCircleArray[i].CalculateArea());
    }
    

    The syntax for declaring and instantiating an array is the same. The three objects of the Circle class are placed in an array. A for-loop is used to access the three circles.

  2. Run your program. Your output will look like this:

    1
    2
    3
    4
    5
    6
    18.84955592153876
    28.274333882308138
    6.283185307179586
    3.141592653589793
    37.69911184307752
    113.09733552923255
    

    Note that the output is the same as in Exercises 1.3 and 2.4.

  3. Try some other values and view the output.