How can I fix this object reference is not set to an instance of an object error?

191 Views Asked by At

I've looked everywhere and I cannot seem to find the root of the problem, nor how to fix this problem. My code below is sorting out an array using a bubble sort and labeling names a-z. That works fine, but this is not the problem. The problem is that when the code runs along the line I have indicated, the error shows. And I don't even know where to start about getting this problem fixed. Been at it for 2+ hours.

        string[] temp = new string[3];
        for (int passes = 0; passes < classMateInfo.Length; passes++)
        {
            for (int pos = 0; pos < classMateInfo.Length - 1 - passes; pos++)
            {
                //The problem is this line below. The error shows up for this.
                if ((classMateInfo[pos].first).CompareTo((classMateInfo[pos + 1].first)) == 1)
                {
                    temp[0] = classMateInfo[pos].first;
                    temp[1] = classMateInfo[pos].last;
                    temp[2] = classMateInfo[pos].ID;
                    classMateInfo[pos] = classMateInfo[pos + 1];
                    classMateInfo[pos + 1].first = temp[0];
                    classMateInfo[pos + 1].last = temp[1];
                    classMateInfo[pos + 1].ID = temp[2];
                }
            }
        }

Do not bother linking me about other people's problems that are similar to mine. I have a hard time understanding other people's answers and my code is different so if someone could point me into the right direction and give me more detail into why this exception is being thrown, that'd be great.

My question is, to clarify, why am I getting a null exception thrown at me? Where to look to fix the problem?

Thanks.

1

There are 1 best solutions below

1
On

If you get a NullReferenceException at this line:

if ((classMateInfo[pos].first).CompareTo((classMateInfo[pos + 1].first)) == 1)

This means that the classMateInfo array either contains a null value, or one of the elements in the array has a null value for first.

Can't help you any further, I don't know the contents of the array.