Browse Arraylist of object objects and compare c#

Asked

Viewed 1,122 times

2

I was wondering how I can reuse the object I put into an array list because I can’t compare it to anything, and how I compare an object inside it to another, in this college program the goal was for the user to put the number of ways he wanted and put his characteristics so that I could print everything, and I’m having difficulty precisely in printing because I can’t compare the square object or rectangle or circle with Listaformas[x], as I normally did with an array, nor can I remove any object from Listaformas to be able to work on it.

static void Main(string[] args)
    {
        ArrayList ListaFormas = new ArrayList();
        Quadrado quadrado = new Quadrado();
        Retangulo retangulo = new Retangulo();
        Circulo circulo = new Circulo();

        Console.WriteLine("Quantas Formas deseja criar?(quadrado,retangulo ou circulo:");

        int quantidade = int.Parse(Console.ReadLine());

        for(int x = 0; x < quantidade; x++)
        {
            Console.WriteLine("Qual forma deseja criar?:");

            string nome = Console.ReadLine();

            if(nome == "quadrado" || nome == "Quadrado")
            {
               Console.WriteLine("Entre com o Lado do quadrado:");

               double lado = double.Parse(Console.ReadLine());
               quadrado.Lado = lado;

               ListaFormas.Add(quadrado);

            }
            else if(nome =="retangulo" || nome == "Retangulo")
            {

                Console.WriteLine("Entre com o primeiro lado:");
                double lado1 = double.Parse(Console.ReadLine());
                Console.WriteLine("Entre com o segundo lado:");
                double lado2 = double.Parse(Console.ReadLine());

                retangulo.Lado1 = lado1;
                retangulo.Lado2 = lado2;

                ListaFormas.Add(retangulo);
            }
            else if(nome == "circulo" || nome == "Circulo")
            {
                Console.WriteLine("Entre com o raio do circulo:");
                double raio = double.Parse(Console.ReadLine());

                circulo.Raio = raio;

                ListaFormas.Add(circulo);
            }
            else
            {
                Console.WriteLine("Erro opcao invalida");
            }


        }

        }

    }
}
  • 2

    Compare what? Without a clear definition of the problem there is no way to find a solution. Only this section already see several problems. You can put the definitions of the 3 classes of forms to help us improve your code?

  • @Maniero "(...)because I can’t compare the square or rectangular object or circle with Listaformas[x], as I normally did with an array, nor can I remove from Listaformas any object to be able to work on it.(...)".

  • @LP.Gonçalves that doesn’t mean anything.

  • See in the documentation the methods and properties that class Arraylist makes available.

  • @Maniero if I didn’t get it wrong, I believe he’d like to know if ListaFormas[x] is a Quadrado, Retangulo or Circulo. I might be wrong.

  • @LP.Gonçalves may be, but nothing indicates clearly that this is it.

  • and I even want to store the objects in an arraylist and compare them later to see if it is square rectangle or circle, then print the information of each one

  • @Arthurhenrique you want a solution based on your question or you want to learn to do it the right way?

Show 3 more comments

1 answer

1

Simple answer

Make your list a generic type.

ListaFormas = new List<object>();

Full answer

Square, rectangle or circle, all derive from the same type, all are Trigonometric Format, so the ideal way to get where you want is to first define what is a trigonometric form.

public interface IFormaTrigonometrica
{
    float Altura { get; }
    float Largura { get; }
}

Then define how your abstraction will be.

public abstract class FormaTrigonometrica : IFormaTrigonometrica
{
    public float Altura { get; protected set; }
    public float Largura { get; protected set; }

    public FormaTrigonometrica(float altura, float largura)
    {
        if(altura <= 0 || largura <= 0) throw new ArgumentException("Formas trigonometricas devem ter tamanhos superiores à zero.");

        Altura = altura;
        Largura = largura;
    }
}

Thus, we guarantee that any trigonometric form must have Altura and Largura valid.

Let’s now define some types of trigonometric shapes. First the circle:

public class Circulo : FormaTrigonometrica
{
    public float Raio => base.Altura;

    public Circulo(float raio) : base(raio, raio)
    {
    }
}

It is defined that a Círculo is a trigonometric form, which only exists if it has a radius, which in turn is worth its height and width.

We’ll do the same with the Rectangle:

public class Retangulo : FormaTrigonometrica
{
    public Retangulo(float ladoA, float ladoB) : base (ladoA, ladoA) 
    {
        if(ladoA == ladoB) throw new ArgumentException("Retangulo devem ter tamanho de lados diferentes");
    }
}

And finally with the Quadrado, which is nothing more than a form with equal sides.

public class Quadrado : FormaTrigonometrica
{
    public float Lado => base.Altura;

    public Quadrado(float lado) : base (lado, lado) 
    {
    }
}

Now, Voce can have its list of trigonometric forms:

var formas = new List<IFormaTrigonometrica>();

var circulo = new Circulo(10);
var quadrado = new Quadrado(5);
var retangulo = new Retangulo(7, 3);

formas.Add(circulo);
formas.Add(quadrado);
formas.Add(retangulo);

    for(var i = 0; i < formas.Count; i++)
    {
        var forma = formas[i];
        Console.Write($"Forma[{i}] => {forma.GetType()}");

        if(forma is Circulo)
            Console.Write($" com Raio {(forma as Circulo).Raio}");

        if(forma is Quadrado)
            Console.Write($" com Lado {(forma as Quadrado).Lado}");

        if(forma is Retangulo)
            Console.Write($" com Altura {(forma as Retangulo).Altura} e Largura {(forma as Retangulo).Largura}");

        Console.WriteLine();
    }

Upshot:

Forma[0] => Circulo com Raio 10
Forma[1] => Quadrado com Lado 5
Forma[2] => Retangulo com Altura 7 e Largura 7

See working on . NET Fiddle.

  • Thiago, I don’t know if I can ask a question here, but I was reading your answer and I didn’t understand what the following excerpt means: public Quadrado(float side) : base (side, side).. Would you please explain to me? Thank you!

  • 1

    That is Inheritance. The Square inherits Formatrigonometric characteristics. But Formatrigonometric requires 2 parameters to be built - float altura, float largura. When you create a Quadrado only with 1 parameter Lado, we must move to the base class that it must be built with altura and largura with same values of lado.

  • Cool, had never seen this inheritance usability. Thank you!

  • thank you very much Thiago I will see if I can implement this here!! thanks!

  • got a lot of thanks!

  • Cool! Don’t forget to mark the answer as ideal.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.