0

i have a array type pessoas, and i'm trying to populate it with the user input, it compiles ok, but in the line ///lstp[--cont].salario = Convert.ToDouble(Console.ReadLine());/// i'm getting this error msg after i enter with any input, System.NullReferenceException, any idea on why is returning a null?

static void Main(string[] args)
    {
        pessoas p = new pessoas();
        int cont = 0;
        pessoas[] lstp = new pessoas[4];
        foreach (var item in lstp)
        {
            Console.WriteLine("pessoa " + (++cont)+": ");
            Console.Write("salario: ");
            lstp[--cont].salario = Convert.ToDouble(Console.ReadLine());
            Console.Write("\nFilhos: ");
            lstp[cont].filhos = Convert.ToInt16(Console.ReadLine());
            cont++;   
        }

        p.calculo(lstp);
        Console.ReadKey();
    }   
class pessoas
{
    public double salario { get; set; }
    public int filhos { get; set; }

}
Raul Quinzani
  • 493
  • 1
  • 4
  • 16
  • When you initialize array `pessoas[] lstp = new pessoas[4]` you just allocate memory for storing 4 pessoas instances. But you do not put any pessoas instances in that allocated memory – Sergey Berezovskiy Jan 29 '16 at 08:56
  • It is a classic misunderstanding when you want to use an array to store references values. Declaring such array with 4 position doesn't mean that you have also created the 4 objects that you want to store in the positions available in the array. You need to create an instance of your class at every loop, store the user input in that instance and finally insert the instance in the correct position of the array – Steve Jan 29 '16 at 08:57

0 Answers0