i have created a classes on shapes such as triangle and circle. i am trying to create a array for the classes and call a constructor from the classes. i am able to display the elements in the array. i would like to know if im doing this correctly and if not any advice on how to do it right.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Lab2
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] strArray = new string[] { "GeometriceObject", "Rectangle", "Square", "Triangle", "Circle" };

            for (int i = 0; i < strArray.Length; i++)
            {
                Console.WriteLine(strArray[i]);
            } 
        }
   }
}

Dani AI

Generated

Short version: store the actual shape objects, not their names, and override the instance ToString on each shape. As suggested, use a typed container (array or list) of your shape type; and as noted, calling ToString on the array itself will produce the runtime type string (e.g. Lab2.Rectangle[]) instead of per-item details.

A clean pattern is an abstract base with an Area and meaningful ToString, then concrete shapes implement Area and expose properties for Width/Height/Radius. Example:

abstract class ShapeBase
{
    public abstract double Area { get; }
    public override string ToString()
    {
        return GetType().Name + " (Area: " + Area + ")";
    }
}

class Rectangle : ShapeBase
{
    public double Width { get; }
    public double Height { get; }

    public Rectangle(double width, double height)
    {
        Width = width;
        Height = height;
    }

    public override double Area { get { return Width * Height; } }

    public override string ToString()
    {
        return "Rectangle Width=" + Width + " Height=" + Height + " Area=" + Area;
    }
}

Create and print instances by iterating the container so each object's ToString runs:

var shapes = new ShapeBase[] { new Rectangle(3, 4), new Rectangle(5, 2) };

foreach (var s in shapes)
    Console.WriteLine(s); // calls s.ToString()

Troubleshooting tips and best practices: prefer properties (Width/Height) over Java-style getWidth methods in C#. Use List<T> when size is dynamic. When you need derived-only members, test and cast safely (pattern matching if (s is Rectangle r) or var r = s as Rectangle; if (r != null) ...). Make sure ToString is overridden on the shape class (instance method) — calling ToString on the array will not dispatch to element ToString implementations.

Recommended Answers

All 7 Replies

All you've done there is put the names into a string array. I think what you mean is if you had the class Rectangle, you could create an array of rectangles by saying

Rectangle [] rects = new Rectangle[5];
rects[0] = new Rectangle(10,10,1,1);
rects[1] = new Rectangle(5,5,1,1);
etc.

(just made up a constructor signature there)


Now if all your classes derive from GeometricObject you can create an array of GeometricObjects and store any of the derived shapes in there.

GeometricObject [] go = new GeometricObject[7];
go[0] = new Square(10,10):
go[1] = new Triangle(0,0);
etc.

(also made up constructor signatures)

I believe these objects in the container (those derived of the parent class) can be downcasted to access their members but I am not 100% sure when this will work (I have excluded the GeometricObject since they cannot be downcasted safely).

commented: I like your approach. +7

thanks for the tip! how exactly would i be able to access a value from the class Rectangle to get the width such as getWidth from it? would it be Rectangle.getWidth()?

In the first case up above it would be rects[i].getWidth() but in the second case you'd have to downcast it like

(go[i] as Rectangle).getWidth()
or 
((Rectangle)go[i]).getWidth()

of course in all of the above cases i is the index for which you are looking.
Also, if you just had a plain old Rectangle object Rectangle myrectangle = new Rectangle(0,0,10,5); you could access it like myrectangle.getWidth() which is close to what you have there but unless the getWidth() member is static you cannot access it without instantiating (using new to make your own object).

so im trying to use the override string and this is what i have. but when i call it just says Lab2. Rectangle[]. i am trying to have it display the height and width and hopefully get the area also.

public override string ToString()
        {
            return (height + " " + width);  
        }

Could you post up a larger portion of the code so I can see what you're extending. If this is the ToString() for your class specifically then you'll have to get all the information from the individual rectangles themselves. I'm not sure what the rectangle ToString method outputs.

In all likelihood you'll need a foreach statement and then return the myRectangle.Height.ToString() and myRectangle.width.ToString() where myRectangle is your object.

As jonsca said, we'd need to see a larger code section to be sure, but it looks like you have overridden the ToString method of the Rectangle Class but are calling .ToString on the collection of rectangles. You would need something like:

Rectangle [] rects = new Rectangle[5];
string dimensions = rects[0].ToString();

hey thanks that really helped!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.