title: Object reference not set to an instance of an object error using a for loop
body: <pre><code>    private void btnAddStudent_Click(object sender, EventArgs e)
      {
          student[counter] = new Student(txtStudentName.Text, txtStudentSurname.Text,     int.Parse(txtExamMark.Text), counter);
          counter++;
  
      }
  
      private void btnAverage_Click(object sender, EventArgs e)
      {
  
          for (int i = counter; i &lt;= counter; i++)
              MessageBox.Show("" + student[i].Average);
      }
  </code></pre>
  
  <p>My program is giving me the error: </p>
  
  <blockquote>
    <p>Object reference not set to an instance of an object.</p>
  </blockquote>
  
  <p>I only want the loop to run once to only display the last calculated average. If i do this:
  ie: change <code>int i = counter</code> to <code>i = 0</code></p>
  
  <pre><code>    private void btnAverage_Click(object sender, EventArgs e)
      {
  
          for (int i = 0; i &lt; counter; i++)
              MessageBox.Show("" + student[i].Average);
      }
  </code></pre>
  
  <p>Then my program works but it displays the messagebox as many times depending on the amount of students <code>i</code> entered, with the last value being the correct average.</p>
  
  <p>I used a class called <code>Student</code> to calculate the average. That is not the problem however, because the correct average is being displayed.</p>
  
  <p>What can I do to fix this error?</p>