Problem with System.Indexoutofrangeexception in C#

Asked

Viewed 142 times

4

I need to create a class Marca and a Modelo, both related to cars, where model will know your brand and brand should know your models.

Model Class:

namespace AssocMatrizes.Model
{
    class Modelo
    {
        public string Nome { get; set; }
    }
}

Marca Class:

namespace AssocMatrizes.Model
{
    class Marca
    {
        private int quantidadeModelos = 0;

        public string Nome { get; set; }

        public Modelo[] Modelos { get; set; }

        public Marca(int maxModelos)
        {
            Modelos = new Modelo[maxModelos];
        }

        public void RegistrarModelo(Modelo modelo)
        {
            Modelos[quantidadeModelos++] = modelo;
        }
    }
}

Main Program:

namespace AssocMatrizes
{
    class Program
    {
        static void Main(string[] args)
        {
            int opcao;
            int quantidade = 0;
            Modelo modelo = new Modelo();

            do
            {
                Console.WriteLine("[1]- Adicionar");
                Console.WriteLine("[2]- Sair");
                opcao = Int16.Parse(Console.ReadLine());
                switch (opcao)
                {
                    case 1:
                        Marca marca = new Marca(quantidade);
                        Console.WriteLine("Marca: ");
                        marca.Nome = Console.ReadLine();

                        Console.WriteLine("Modelo: ");
                        modelo.Nome = Console.ReadLine();

                        marca.RegistrarModelo(modelo);
                        quantidade++;
                        break;
                    case 2:
                        break;
                    default:
                        break;
                }
            } while (opcao != 2);

            Console.ReadKey();

        }
    }
}

When I go to run the program, it appears the following problem after I enter data into the console.

Erro mostrado

I have tried several things and I have not found the solution to my problem, so I realize it is something with the passage to function or the array.

1 answer

2


This particular problem is that you are accessing an element of array which does not exist, is accessing a number greater than the amount created elements, and needs to validate this. It would be something like this:

public void RegistrarModelo(Modelo modelo) => if(quantidadeModelos >= Modelos.Lenght) Modelos[quantidadeModelos++] = modelo;

I put in the Github for future reference.

You may prefer to do something if you cannot add the model. A common solution is to return a boolean whether it worked out or not for consumer code to know if it can perform the operation.

There are other conceptual errors in this code, but I won’t even go into it (for example this new Marca(quantidade); in the form used does not seem to make sense, but only who did can guarantee). It has a mechanism that will break your application and I have already mentioned several questions. To the reported problem the answer is given and the suggestion to review everything you are doing and how you are learning too.

Programming is understanding everything you’re doing, especially understanding the mechanisms you’re using. Don’t use anything that doesn’t completely master what it does, everything that can happen, how to solve every problem, you have to study every tiny detail of it before you use it, because if you don’t, you’re creating random code that can work by coincidence, and this is the worst that can happen to you, since if you make a mistake you know that there is something wrong that someone will fix for you on the internet, but if you do not make a mistake can still be wrong and you can not do anything because you do not understand what you are doing.

Browser other questions tagged

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