0

Hello I know to most of you this will seem like such an easy fix, but its my first year in college and I have come across this error which I can't seem to solve if you guys could help guide me to the solution and explain it I would be so grateful.

One of the assignment goals is to ask the user how many pets they own, though all member variables must be private and values must be assigned using the "get" "set" patterns.

Note: The error occurs on "pets[i].GetPetName();"

Program.cs Code

    int totalPets;
        System.Console.WriteLine("How many pets do you own?");
        totalPets = int.Parse(System.Console.ReadLine());
        



        Pet[] pets = new Pet[totalPets];
        
        
        for (int i = 0; i < totalPets; i++)
        {
            pets[i].GetPetName();
            pets[i].GetPetAge();
            pets[i].GetPetBreed();
            pets[i].PrintPetInfo();
        }

Class "Pet.cs" Code

    private string Name;
    public string GetPetName()
    {
        System.Console.WriteLine("What is your dogs name?");
        Name = System.Console.ReadLine();
        return Name;
    }
    private int Age;
    public int GetPetAge()
    {
        System.Console.WriteLine("What is your dogs age?");
        return this.Age = int.Parse(System.Console.ReadLine());
    }
    private string Breed;
    public string GetPetBreed()
    {
        System.Console.WriteLine("What is your dogs breed?");
        return this.Breed = System.Console.ReadLine();
    }
    public void PrintPetInfo()
    {
        string v = this.Name + " is " + this.Age + " and is a " + Breed;
    }
MickyD
  • 14,343
  • 6
  • 43
  • 67
  • 1
    you created an empty `array` of `Pet[]` but never added any `Pet` instances (objects) into it, so value at `pets[i]` is null, which is why you are getting a `NullReferenceException` – zaitsman Apr 27 '22 at 06:10

0 Answers0