Please, help me understand, what’s wrong with this code. (I am trying to build a string, taking parts of it line by line from a text file).
I get a runtime error “In the instance of the object reference not set to an object” on the line strbuild.Append(str);
StreamReader reader = new StreamReader("buf.txt", System.Text.Encoding.ASCII);
StringBuilder strbuild = new StringBuilder();
strbuild = null;
while (reader.Peek() >= 0)
{
string str = null;
str = reader.ReadLine().ToString();
string segment = str.Substring(0, 1);
if (segment == "A")
{
strbuild.Append(str); //here i get an error
}
else if (segment == "B")
{
strbuild.Append("BET");
}
}
printstr = strbuild.ToString();
reader.Close();
MessageBox.Show(printstr);
Look at these lines:
What do you expect to happen when you then call
strbuild.Append(...)? Why are you settingstrbuildto null at all?You seem to be fond of two-line variable initialization – here’s another example:
This would be more easily readable as just:
(
ReadLinealready returns a string, so you don’t need to callToString()on the result.)However, I do suggest that you use a
usingstatement for theStreamReader– otherwise when an exception is thrown, you’ll be leaving the reader open.One nice thing about
TextReader.ReadLine()is that it returns null when you’re done. You don’t need to peek and then read.Finally, if you’re only testing a single character you don’t need a substring – just use the string indexer to get a char. So, you could have: