Object reference set to an instance of an object.
Hi, just completing an assignment for uni that reads marks from a file and calculate the exam percentage and grade then outputs it to the console with the number of students who had that grade in the file. I came across a NullReferenceException and I'm not sure how to handle it.
32 Replies
Excuse the horrible readabilty im still learning 😅
Can you provide the full exception with stack trace and indicate which line of your provided code it points to?
Also, if you add cs after the three
you use to format code it will color it
Has to be immediately after the
and then newlineI didn't know that, thats cool thank you
Are you able to use a debugger to step through the code? This exception means that an operation like a method call is being done on a variable that is null, so it is possible something is not assigned correctly
I've tried to use the debugger but thats a whole issue within itself, I think its something with how I set it up. it doesnt seem to want to debug any cs file.
It might have to do with the launch.json file but im not sure. Still new to these things haha.
What does the launch.json look like?
Currently, like nothing because I havent created one for this project since I cant seem to get the debugger working for any project.
I went a bit crazy trying to get it to work
Have you tried opening the solution with visual studio?
Vscode is not the best for beginners
I just tried to debug and out of nowhere its started to work
Something about allowing developer permissions for my mac.
This is the line which says theres an issue
Its on line 45
It's possible that
studentInfo[i]
is null
In that case you would be trying to do null[2] = ...
which would cause the error
So you could make sure all subarrays in your studentinfo array are initializedThat sounds like that could be the issue the variable watch is saying that its currently null.
That would do it
When you initialise a string array does it set the items to null or empty strings?
null
Aha I found the issue
I initialised a 2D array as string[][] not string[ , ]
Seems to work now!
You could use both but [][] would require you to initialize every row to an array also
Yeah that explains why it would set it to null.
Since i didnt initialise every row
Except now its coming out as an IndexOutOfRangeException
How are you initializing the array now
You may not need the -1 in there
Just a guess based on your loop
That might explain why its giving me an exception when i = 5;
What's the length of splitData
Should be 5.
Then you definitely don't need the -1 when you create the array
Still seem to be getting the error.
Is it the same line?
Yeah it seems to be running for a 6th time so i = 6, even though it should stop at 5
i changed it to i<studentInfo.GetLength(0)-1
The loop condition was ok
That fixed it
I think its because studentInfo was a 2d array and .length usually works only for 1D arrays
So it counted up more items
That's true