'Why does string.Split(";") not throw an error if the string is null or empty? [closed]
If string is empty or null,
Shouldn't string.split(";") should throw an error ?
for me I am trying this code and goes through it without any error,
string a = string.empty;
if (a.Split(';').Length - 1 < 1)
Can anyone tell me why it not throws an error and why if statement is true.
Solution 1:[1]
It should behave as documented:
If this instance does not contain any of the characters in
separator, the returned array consists of a single element that contains this instance.
An empty string clear does not contain any of the characters in separator, hence an array is returned consisting of a single element referring to an empty string.
Of course, if you call Split on a null reference, you'll get a NullReferenceException. It's important to differentiate between a reference to an empty string and a null reference.
If you want the method to return an empty array, use StringSplitOptions.RemoveEmptyEntries. If you want the result to be an error, you should check for this yourself and throw whatever exception you want.
It's important not to guess at behaviour when using an API though: if you're in any doubt at all, consult the documentation.
Solution 2:[2]
From your code, a isn't null, it's String.Empty. So when you split an empty length string by a semicolon, there's 1 item. 1 - 1 is less than 1
Solution 3:[3]
An empty string is NOT the same as a null string. Strings, being reference types will always contain "" if empty. Null is not at all the same thing, thus, if you have an empty string, it will have a length of 0 and your if statement will be valid.
Solution 4:[4]
The code splits the string into components separated with ';' - the result of this operation is the array of strings. If there are less than 2 components the condition is true.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jon Skeet |
| Solution 2 | Miles |
| Solution 3 | David L |
| Solution 4 | Sergey Vyacheslavovich Brunov |
