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.
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 wordsloading...
Last Post: Codeforces: 239A. Two Bags of Potatoes
Next Post: Proof without Words