Coding | .NET | C♯ | Angular | Ionic | Cordova | :-o

Menu

C#|.NET : Safe Substring

Substring is a very handy function when you want to do something with part of a given string. The problem with Substring is that if you do not do proper range checking, it will throw ArgumentOutOfRangeException. Check these statement:

I am not saying you should not check the range of your arguments. You should. This is for those cases where you want substring to return a string, whatever values you get at run-time. This method fulfills following requirements:

returns empty string if start-index is out of range

returns string from start to given length, if start-index is smaller than 0

returns string from start-index to end of string, if length argument is beyond number of characters left