The definition of Substring()
method in .net System.String
class is like this
public string Substring(int startIndex)
Where startIndex
is "The zero-based starting character position of a substring in this instance" as per the method definition. If i understand it correctly, it means it will give me a part of the string, starting at the given zero-based index.
Now, if I have a string "ABC"
and take substring with different indexes, I get following results.
var str = "ABC"; var chars = str.ToArray(); //returns 3 char 'A', 'B', 'C' as expected var sub2 = str.Substring(2); //[1] returns "C" as expected var sub3 = str.Substring(3); //[2] returns "" ...!!! Why no exception?? var sub4 = str.Substring(4); //[3] throws ArgumentOutOfRangeException as expected
Why it doesn't throw exception for case [2] ??
The string has 3 characters, so indexes are [0, 1, 2]
, and even ToArray()
, ToCharArray()
method returns 3 characters as expected! Shouldn't it throw exception if I try to Substring()
with starting index 3
?
The documentation is quite explicit about this being correct behaviour:
Return value: a string that is equivalent to the substring that begins at startIndex in this instance, or Empty if startIndex is equal to the length of this instance.
Throws
ArgumentOutOfRangeException
ifstartIndex
is less than zero or *greater than the length of this instance. *
In other words, taking a substring starting just beyond the final character will give you an empty string.
Your comment that you expected it to give you a part of the string is not incompatible with this. A "part of the string" includes the set of all substrings of zero length as well, as evidenced by the fact that s.substring(n, 0)
will also give an empty string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With