Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Im in the middle of coding a program in C# and I\'m getting a NullReferenceExcep

ID: 3697880 • Letter: I

Question

Im in the middle of coding a program in C# and I'm getting a NullReferenceException error when I try to assign text to a label. Here is my code and I have the line of error in bold.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace Project10
{
public partial class Form1 : Form
{
private Label[] words;
private string[] pickedWords;
private TextBox[] guesses;
private Button check;
private Random r = new Random();
private int numWords;

public Form1()
{
words = new Label[5];
words[0] = word1;
words[1] = word2;
words[2] = word3;
words[3] = word4;
words[4] = word5;

guesses = new TextBox[5];
guesses[0] = guess1;
guesses[1] = guess2;
guesses[2] = guess3;
guesses[3] = guess4;
guesses[4] = guess5;
numWords = words.Length;
InitializeComponent();
pickedWords = pickWords(numWords);
for (int i = 0; i < pickedWords.Length; i++)
{
words[i].Text = pickedWords[i];
}


}


private string [] pickWords(int num)
{
int numWords;
string input;
List <string> words = new List<string>();
string filename = "words.txt";
StreamReader sr = new StreamReader(filename);
while ((input = sr.ReadLine()) != null)
{
words.Add(input);
}
sr.Close();

string [] word = new string[5];
int sizeList = words.Count;
for (int i =0; i < word.Length; i++)
{
numWords = r.Next(sizeList);
word[i] = words[numWords];
}
  
return word;
  
}

}
}

Explanation / Answer

First let me explain What is NullReferenceException?

NullReferenceException It indicates that you are trying to access member fields, or function types, on an object reference that points to null. It indicates a flaw in the code. You are trying to use something that is null . This means you either set it to null, or you never set it to anything at all. Like anything else, null gets passed around. If it is null in method "A", it could be that method "B" passed a null to method "A". The runtime throwing a NullReferenceException always means the same thing: you are trying to use a reference. The reference is not initialized (or it was initialized, but is no longer initialized).

This means the reference is null, and you cannot access members through a null reference. The simplest case:

string name=null; (or) string name;

name.ToUpper();   

Here name is pointed to null though you are trying to access a method without the name, this leads to exception.

Debugging

How do you find the source of a NullReferenceException? Apart from looking at the exception itself, which will be thrown exactly at the location where it occurs, the general rules of debugging in Visual Studio apply: place strategic breakpoints and inspect your variables, either by hovering the mouse over their names, opening a (Quick)Watch window or using the various debugging panels like Locals and Autos.

If you want to find out where the reference is or isn't set, right-click its name and select "Find All References". You can then place a breakpoint at every found location and run your program with the debugger attached. Every time the debugger breaks on such a breakpoint, you need to determine whether you expect the reference to be non-null, inspect the variable and and verify that it points to an instance when you expect it to.

By following the program flow this way you can find the location where the instance should not be null, and why it isn't properly set.

Consider an example In your code:

for (int i = 0; i < pickedWords.Length; i++)
{
  words[i].Text = pickedWords[i];
}

// Here the NullReferrenceException occurs in the case of all or any of words array label is points to null.

// Check the labels that they exists in the code.

// Here are some suggestions to your code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace Project10
{
public partial class Form1 : Form
{
private Label[] words;
private string[] pickedWords;
private TextBox[] guesses;
private Button check;
private Random r = new Random();
private int numWords;

public Form1()
{
words = new Label[5];
words[0] = word1; // Check the labels:
words[1] = word2;
words[2] = word3;
words[3] = word4;
words[4] = word5;

guesses = new TextBox[5];
guesses[0] = guess1;
guesses[1] = guess2;
guesses[2] = guess3;
guesses[3] = guess4;
guesses[4] = guess5;
numWords = words.Length;
InitializeComponent();
pickedWords = pickWords(numWords);   
for (int i = 0; i < pickedWords.Length; i++)
{
  words[i].Text = pickedWords[i];
}


}


private string [] pickWords(int num)   
{
int numWords;
string input;
List <string> words = new List<string>();
string filename = "words.txt";
StreamReader sr = new StreamReader(filename); // You are about to read a file here check the existance of file
while ((input = sr.ReadLine()) != null)   // Reading a line here check the lines must be present
{
words.Add(input); // and for this code you are about to read five lines and make sure your file has five lines
}
sr.Close();

string [] word = new string[5];
int sizeList = words.Count;
for (int i =0; i < word.Length; i++)
{
numWords = r.Next(sizeList);
word[i] = words[numWords];
}
  
return word;
  
}

}
}