Click here to Skip to main content
15,896,348 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
code:-
string p = "123456789";
p.substring(0,8);

problem :-index and length must refer to a location within the string. parameter name length in c# , string does not have fixed length depend on user, when string less than 8 it create error, when string length is more than 8 it work fine

Posted
Updated 4-Sep-15 5:20am
v2

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
 
Share this answer
 
Remember it is ZERO based index not ONE based.

When string is 8 digits long then 0,7 is the 8th digit.

String:
12345678

Index:
01234567
 
Share this answer
 
Comments
Monika Tiwari 4-Sep-15 11:31am    
Sir Above things i know but the solution, sometime user put 5 digit when string less than 6 then error come up

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900