C# Accessing values of a derived class in an array of the base class -
this not working hope makes clear example:
public abstract class shape { public int area; public int perimeter; public class polygon : shape { public int sides; public polygon(int a, int p, int s){ area = a; perimeter = p; sides = s; } } public class circle : shape { public int radius; public circle(int r){ area = 3.14*r*r; perimeter = 6.28*r; radius = r; } } }
in main function have this:
shape[] thisarray = new shape[5]; thisarray[0] = new shape.circle(5); thisarray[1] = new shape.polygon(25,20,4);
my problem when deal thisarray, can't access values other area , perimeter. for example:
if (thisarray[0].area > 10) //this statement executed if (thisarray[1].sides == 4) //this not compile
how can access sides thisarray[1]? access if did like
shape.polygon randomsquare = new shape.polygon(25,20,4)
not if in array of shapes.
if recall correctly accomplished in c++ doing like
polygon->thisarray[1].sides
(i forget called) not know how in c#
if can't trying do, how can circumvent problem?
thank reading through intended short, appreciated.
you should use casting:
(thisarray[1] shape.polygon).sides
note should make sure underlying object instance polygon, otherwise raise exception. can using like:
if(thisarray[1] shape.polygon){ (thisarray[1] shape.polygon).sides }
Comments
Post a Comment