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
?