6

I am getting the object reference error in this line: emp[count].emp_id = int.Parse(parts[0]);

in this code

this program to read from file and store in array of object

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public class employees
    {
        public int emp_id;
        public string firstName;
        public string lastName;
        public double balance;
    }

    private void btnOpen_Click(object sender, EventArgs e)
    {
        OpenFileDialog file = new OpenFileDialog();
        DialogResult result = file.ShowDialog();
        if (result == DialogResult.Cancel) return;

        string fileName = file.FileName;
        StreamReader reader = new StreamReader(fileName);

        string[] lines = File.ReadAllLines(fileName);
        int emp_count = lines.Count<string>();
        employees[] emp = new employees[emp_count];
        int count = 0;
        foreach (string line in lines)
        {
            string[] parts = new string[4];
            parts = line.Split(',');
            **emp[count].emp_id = int.Parse(parts[0]);**
            emp[count].firstName = parts[1];
            emp[count].lastName = parts[2];
            emp[count].balance = double.Parse(parts[3]);
            count++;
            txtGet.Text += emp[count].emp_id + " " + emp[count].firstName + " " + emp[count].lastName + " " + emp[count].balance + " \n ";

        }
DaveShaw
  • 52,123
  • 16
  • 112
  • 141
Beginner
  • 73
  • 1
  • 2
  • 5
  • Sorry what about read data in one file and store it in array of object Then write this data in new file. string path="D:\\new.txt"; StreamWriter writer; writer = File.CreateText(path); string record = " "; for (int i = 0; i – Beginner Mar 23 '12 at 01:57
  • Possible duplicate of [What does "Object reference not set to an instance of an object" mean?](http://stackoverflow.com/questions/779091/what-does-object-reference-not-set-to-an-instance-of-an-object-mean) – Brian Jan 06 '16 at 20:06

2 Answers2

12

You need to initialise emp[count] to something.

You can do this by adding the following:

foreach (string line in lines) 
{ 
    emp[count] = new employees();
    string[] parts = new string[4]; 
    //....
}

When you call employees[] emp = new employees[emp_count]; you initilise emp to an array of employees with the length of emp_count.

emp[0] = null;
emp[1] = null;
//etc.

Each element inside emp also needs to be instantiated before you can use it.

DaveShaw
  • 52,123
  • 16
  • 112
  • 141
2

emp[0] has not been initialized. Class employees is a nullable type, which means arrays made of it are initialized to nulls. Initialize emp[count] to new employees.

BTW, "employees" is a strange name for a class that holds a single employee. I think it should be called Employee, then it makes sens to declare your array like this:

 `Employee[] employees = new Employee[emp_count];`
Diego
  • 18,035
  • 5
  • 62
  • 66