All you need to do is: 1) avoid hard-coding
immediate constants (such as 8); 2) in some cases, check up the length of the string (similarly, element count of collection, length of arrays, etc.)
Even if the starting index is 0, some check is still needed, because the element at the index 0 does not exist for an empty string. As to the length used in
string.Substring
, you can use the following feature: your length can exceed actual length of available part of sub-string; in this case, result will be truncated to available length.
This is not explicitly explained in the documentation:
https://msdn.microsoft.com/en-us/library/aka44szs%28v=vs.110%29.aspx[
^].
However, implicitly, this is indicated. Look at the exception part of the documentation: only the exception related to wrong index value is thrown; it means that too big value for the second parameter will be tolerated the way I explained.
—SA