Reputation: 117
I have these 5 classes.. One base class called Figura that is an abstract class, and 4 concrete derived classes.
I have to create an array of Figuras of size 8 (two Cuadrado, two Rectangulo, two Triangulo and two Circulo), so I did this:
Figuras[] figuras = new Figuras[8];
figuras[0] = new Cuadrado(1);
figuras[1] = new Cuadrado(2);
figuras[2] = new Rectangulo(2, 1);
figuras[3] = new Rectangulo(6, 2);
figuras[4] = new Triangulo(1, 2, 2);
figuras[5] = new Triangulo(3, 3, 4);
figuras[6] = new Circulo(1);
figuras[7] = new Circulo(4);
Then I iterate through the array to calculate the area and perimeter of every figure. The problem comes when I try to call the method calcularDiametro() that belongs only to the figure Circulo. How can I do that?
I tried the following but it doesn't work.
foreach (Figuras f in figuras)
if (f is Circulo)
f.calcularDiametro();
Any help would be appreciated.
Upvotes: 2
Views: 268
Reputation: 744
The other answers are technically correct yet wrong. Your problem is you should not initiate those calculations from outside the classes in the first place. The classes themselves should perform the calculations as needed, either in the constructor or when an external component requests the value of perimetro or diametro. That is encapsulation.
Upvotes: 1
Reputation: 20764
You can use as
opertor and prevent additional cast and improve performance
foreach (Figuras f in figuras)
{
var c = f as Circulo;
if (c != null)
c.calcularDiametro();
}
You can also use OfType
to get objects of specific type from your Enumerable
foreach (var c in figuras.OfType<Circulo>())
{
c.calcularDiametro();
}
Upvotes: 4
Reputation: 101758
You need to cast it to a Circulo
in order to call Circulo
-specific methods:
foreach (Figuras f in figuras)
{
if (f is Circulo)
(Circulo)f.calcularDiametro();
}
Note that this is a bit wasteful because it does type-checking twice (which is a costly operation). One way to do this without that waste is to use as
:
foreach (Figuras f in figuras)
{
Circulo circ = f as Circulo;
if (circ != null)
{
circ.calcularDiametro();
}
}
Upvotes: 4