Unhandled exception (0-based index)

1

My idea is to make a small registration and I'm testing this for later adding that data to a DB. The problem occurs at line Console.Write("\nGenero do disco : {1}", genero); , at the time of displaying the string read via keyboard. Here is the error:

  

Exception without treatment   System.FormatException: 'Index (zero-based) must be greater than or equal to zero and smaller than the argument list size.'

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

namespace Cadastro_de_músicas
{
    class Disco
    {
        public string nome;
        public string genero;
        public string ano;

        public void cadastra()
        {
            Console.Write("Digite o nome do disco: ");
            nome = Console.ReadLine();
            Console.Write("Digite o genero do disco: ");
            genero = Console.ReadLine();
            Console.Write("Digite o ano do disco: ");
            ano = Console.ReadLine();
        }

            public void exibe()
            {
            Console.Write("Nome do disco: {0}", nome);
            Console.Write("\nGenero do disco : {1}", genero);
            Console.Write("\nAno do disco: {2}", ano);
            Console.ReadKey();
        }
    }
}
    
asked by anonymous 09.07.2017 / 04:31

2 answers

2

It has a more modern way of doing this that does not cause this type of error. Make use of interpolation , it is much better. I enjoyed and improved other things. See naming patterns used in C # . There are other things that can be improved on this code, but let's stop here.

using static System.Console;

namespace CadastroDeMusicas {
    public class Disco {
        public string nome;
        public string genero;
        public string ano;

        public void Main() {
            Write("Digite o nome do disco: ");
            nome = ReadLine();
            Write("Digite o genero do disco: ");
            genero = ReadLine();
            Write("Digite o ano do disco: ");
            ano = ReadLine();
            Exibe();
        }

        public void Exibe() {
            WriteLine($"Nome do disco: {nome}");
            WriteLine($"Genero do disco : {genero}");
            WriteLine($"Ano do disco: {ano}");
        }
    }
}

See running on .NET Fiddle . And in Coding Ground . Also put it in GitHub for future reference .

    
09.07.2017 / 04:57
4

When the writing is done with the braces, they indicate the number of the element to write. So this line:

Console.Write("\nGenero do disco : {1}", genero);

Should be:

Console.Write("\nGenero do disco : {0}", genero);

It should be {0} because it is the first element to write from the list of elements.

If you put two variables in the same handwriting, then you use numbers {0} and {1} , like this:

Console.Write("\nBom dia {0}, {1}", apelido, primeiroNome);

The same error happens in the last write to the console.

    
09.07.2017 / 04:39