public static void Main()
string testString = "abcde";
var testSuite = new int?[] {
-1,null, -1, -1, -1, 0, -1, 1, -1, 3, -1,9,
-0,null, 0, -2, -0, 2, 0, 5, 0, 9,
2,null, 2, -3, 2,-2, 2,-1, 2, 0, 2,2, 2,6,
4,null, 4, -9, 4,-4, 4, 0, 4, 1, 4,4, 4,9,
5,null, 5, -9, 5,-5, 5,-4, 5,-0, 5,1,
6,null, 6, -9, 6,-6, 6,-5, 6,-2, 6,0, 6,2};
Console.WriteLine("\r\nTesting Base and Extension 'Substring()' Methods for \"" + testString + "\".Substring(startIndx, length, handleIndexException: true): ");
Console.WriteLine("Start Length Extn Result Base Method Result\r\n" + new string('=', 80));
for (int i = 0; i < testSuite.Length; i += 2)
int x = (int)testSuite[i];
int? y = testSuite[i + 1];
string rsltExt = (y.HasValue ? testString.Substring(x, (int)y, true) : testString.Substring(x, true));
rsltBase = (y.HasValue ? testString.Substring(x, (int)y):testString.Substring(x));
rsltBase = "***Exception: " + ex.Message.Split('\r')[0];
Console.WriteLine("{0,3} {1,4} {2,-12} {3}", x, y, rsltExt.ShowNull(), rsltBase.ShowNull());
public static class Extensions
public static String ShowNull(this String val, string nullval = "<<null>>"){
return string.IsNullOrEmpty(val) ? nullval : val;
public static String Substring(this String val, int startIndex, bool handleIndexException)
if (!handleIndexException){
return val.Substring(startIndex);
if (string.IsNullOrEmpty(val)){
return val.Substring(startIndex < 0 ? 0 : startIndex > (val.Length - 1) ? val.Length : startIndex);
public static String Substring(this String val, int startIndex, int length, bool handleIndexException)
if (!handleIndexException){
return val.Substring(startIndex, length);
if (string.IsNullOrEmpty(val))
int newfrom, newlth, instrlength = val.Length;
newfrom = startIndex + length;
if (newfrom + newlth < 0 || newfrom > instrlength - 1)
newlth = newfrom + newlth;
return val.Substring(newfrom, Math.Min(newlth, instrlength - newfrom));