Question

Object reference not set to an instance of an object. I am still having the same issue...Student S is passed in and (Student)s.scores contains a string of "80 90 100"

    public Student GetUpdatedScores(Student s)
    {

        txtName.Text = s.Name;  
        lstScores.Items.Clear();
        string[] listOfScores = s.Scores.Split(' '); //receiving error on this line.
        for (int i = 0; i < (listOfScores.Length - 1); i++)
        {
            lstScores.Items.Add(listOfScores[i]);
        }
        this.ShowDialog();
        return student;
    }
Was it helpful?

Solution

Obviously enough s.Scores property returns a null value. When you affect it to scoreS string variable and then try to split it, you get your exception.

This kind of problem is easy to solve with a debugging session. Plus, if you want to make sure a value cannot be null without you knowing while you are debugging, use Debug.Assert calls. For example:

Debug.Assert(scoreS != null);

Just so you know these calls won't be compiled on release compilation config.

As an additional advice, if you don't mind me saying, you should not have variables which only differs by case. In fact, I believe you should drop both namE and scoreS as they're completely useless here. Work with the instance properties instead. This will make code easier to read and in the process help you figuring out issues like this one by yourself when they occur.

UPDATE:

Here is how I would have wrote it (with some comments explaining further):

// renamed the function to reflect what it really should do (and does)
public DialogResult ShowUpdatedScores(Student student)
{
    // since your method is public this is rather good practice
    if (student == null) throw new ArgumentNullException("student");

    // with this, scores cannot be null while you debug without you knowing
    Debug.Assert(student.Scores != null);

    // who needs loops when there's AddRange method? :)
    lstScores.Items.Clear();
    lstScores.AddRange(student.Scores.Split(' '));

    txtName.Text = student.Name;  

    // it's pointless to return the same student pointer that was passed as a parameter, returning DialogResult makes more sense
    return this.ShowDialog();
}

Of course that's making some assumptions about your code but you get the idea.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top