An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
StreamReader.ReadLine() returns null only when there are no more lines to read. In the loop shown, line is already checked before ToUpper() runs, so that pattern is safe for end-of-file.
A NullReferenceException happens when code dereferences a null object reference. To avoid that, check values before calling members on them.
Use one of these safe patterns:
using System.IO;
using (StreamReader reader = new StreamReader("data.txt"))
{
string? line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line.ToUpper());
}
}
If the goal is to skip empty lines as well:
using System.IO;
using (StreamReader reader = new StreamReader("data.txt"))
{
string? line;
while ((line = reader.ReadLine()) != null)
{
if (line.Length == 0)
continue;
Console.WriteLine(line.ToUpper());
}
}
If the code should handle both null and empty strings explicitly:
using System.IO;
using (StreamReader reader = new StreamReader("data.txt"))
{
string? line;
while ((line = reader.ReadLine()) != null)
{
if (string.IsNullOrEmpty(line))
continue;
Console.WriteLine(line.ToUpper());
}
}
If a method can return null, test the return value before accessing its members. That is the recommended way to prevent NullReferenceException.
A try/catch can be added for file I/O errors, but it is usually better to prevent NullReferenceException with null checks instead of handling it after it occurs:
using System;
using System.IO;
try
{
using (StreamReader reader = new StreamReader("data.txt"))
{
string? line;
while ((line = reader.ReadLine()) != null)
{
if (string.IsNullOrEmpty(line))
continue;
Console.WriteLine(line.ToUpper());
}
}
}
catch (IOException e)
{
Console.WriteLine(e.Message);
}
Also note:
-
usingensures theStreamReaderis disposed even if an exception is thrown. - Empty lines are not
null; they are empty strings. -
NullReferenceExceptionis thrown when attempting to access a member on anullreference.