Null Reference Exception due to Null String in C#


Unlike Delphi, the string in C# is type of object. Therefore, you can reference the Length property to obtain the length of the string. However, when null value is assigned to a string, reference its Length will throw out a NullReferenceException. (Object Reference not set to an instance of an object). The following code will output zero and throw out the exception.

nullstring Null Reference Exception due to Null String in C# beginner c # programming languages

To ensure a good coding standard, we can put a check before using Length. Unlike null string, an empty string is usually expressed by “”. The empty string can use its Length (equal to zero) without problems.

1
2
3
4
5
string s = null;
if ((s != null) && (s.Length > 3))
{
    Console.WriteLine(s.Length);
}
string s = null;
if ((s != null) && (s.Length > 3))
{
    Console.WriteLine(s.Length);
}

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
195 words
Last Post: Codeforces: 239A. Two Bags of Potatoes
Next Post: Proof without Words

The Permanent URL is: Null Reference Exception due to Null String in C#

Leave a Reply