Decla Decla - 17 days ago 4
C# Question

Basic c# array printing

I managed to get the program to accept values but I'm not quite sure how to print my results, when i tried to print it like this, which is wrong, it just gave me random text. I guess it should be something like sh.display or something but i'm really lost here

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

namespace ConsoleApplication1
{
abstract class shape
{
void getarea()
{ Console.WriteLine("Area is"); }
void display()
{
Console.WriteLine("This is shape");
}
void getcirc()
{
Console.WriteLine("Circumference is");
}
}

class circle : shape
{
public circle(double r)
{this.r = r;}
double r;
void getarea()
{
Console.WriteLine("Circle area =" + (Math.PI * Math.Pow(r, 2)));
}

void getcirc()
{
Console.WriteLine("Circle circumference = " + (2 * Math.PI * r));
}

void display()
{
Console.WriteLine("This is circle");
}
}

class rect : shape
{
public rect(double x, double y)
{this.x=x;
this.y=y;
}
double x,y;
void getarea()
{
Console.WriteLine("Rectangle area =" + (x * y));
}

void getcirc()
{
Console.WriteLine("Circle circumference = " + ((2 * x) + (2 * y)));
}

void display()
{
Console.WriteLine("This is Rectangle");
}

class square : shape
{
public square(double z)
{this.z=z;
}
double z;
void getarea()
{
Console.WriteLine("Square area =" + (z*z));
}

void getcirc()
{
Console.WriteLine("Square perimeter = " + (4 * z));
}

void display()
{
Console.WriteLine("This is square");
}




class Program
{
static void Main(string[] args)
{
shape[] sh = new shape[15];
Random rndm= new Random();

int i;
int shapenum;
for (i = 0; i < 15; i++)
{ shapenum = rndm.Next(1,4);

switch (shapenum)
{
case 1:
Console.WriteLine("Enter radius");
sh[i] = new circle(int.Parse(Console.ReadLine()));
break;

case 2:

Console.WriteLine("Enter x and y lengths");
double x = double.Parse(Console.ReadLine());
double y = double.Parse(Console.ReadLine());
sh[i] = new rect(x,y);
break;

case 3:

Console.WriteLine("Enter side length");
sh[i] = new square(int.Parse(Console.ReadLine()));
break;
}
}
for (i = 0; i < 15; i++)
{
Console.Write(sh[i] + " ");
}


}
}
}
}
}

Answer

None of your classes override .ToString(), so when you call Console.Write(sh[i] + " ") it's just printing the type name of the object. (Not "random text".)

You need to do one of two things:

  1. Define a .ToString() override on your classes (easiest, recommended);
  2. Make shape.display() a virtual method (virtual void display()) and use override void display() in all sub-classes, then call sh[i].display() instead of Console.Write(sh[i] + " ");

Either one will fix your issue.

Of course, if the goal is to make getarea() and getcirc() on all classes derived from shape, then you should be marking them virtual on shape and then marking them override on sub-classes.

Better yet, replace shape with an interface (IShape) and then make all the sub-classes simply implement the interface.

Comments