I have a task to complete and I can't figure out what i have done wrong and whether the instances of the objects are not created at all or whether there is no reference to the array of elements. Error: System.NullReferenceException. The task is to initiate 20 objects from a text file, each line represents a instance of an object. The program should read the file create each object and update an array of pointers to pin to newly created object. So far, the code runs the text file and converts string into appropriate type. It also looks like it initialises the objects and points them to the livestocks[] array. However when trying to run any object related methods, I get the null reference error. The requirement is to use the array to create the new objects. Any help would be really appreciated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Globalization;
namespace Example
{
class Program
{
static void Main(string[] args)
{
Livestock[] livestocks = new Livestock[20]; //array of 20 pointers to Livestock.
String textLine;
String[] livestockContent; //array of Livestock textfile content
//The task of this progrgam is to read the file line by line
try
{
TextReader textReader = new StreamReader(@"C:\...file.txt");
while ((textLine = textReader.ReadLine()) != null)
{
livestockContent = textLine.Split(','); //The line could be splitted to words
int _ID = int.Parse(livestockContent[0]);
string _livestockType = livestockContent[1];
int _yearBorn = int.Parse(livestockContent[2]);
double _costPerMonth = double.Parse(livestockContent[3], CultureInfo.InvariantCulture);
double _costPerVaccination = double.Parse(livestockContent[4], CultureInfo.InvariantCulture);
double _amountOfMilk = double.Parse(livestockContent[5], CultureInfo.InvariantCulture);
if (_livestockType != null )
{
for (int i = 0; i > 20; i++)
livestocks[i] = new Livestock(_ID, _livestockType, _yearBorn, _costPerMonth, _costPerVaccination, _amountOfMilk);
//Console.WriteLine("Creating a new: " + livestocks[0]);
//Console.WriteLine("Livestock ID is: " + ID);
}
else
{
for (int i = 0; i > 20; i++)
livestocks[i] = new Livestock(_ID, _livestockType, _yearBorn, _costPerMonth, _costPerVaccination, _amountOfMilk);
livestocks[9].GetID();
}
}//end of while //end of reading the file and initiating objects
}//end of try
catch (FileNotFoundException ex)
{
Console.WriteLine(ex.Message);
}// end of catch
Console.ReadKey();
}//end of main method
}// end of class
}//end of namespace