Tuesday, January 15, 2013

The second parameter in C#'s .Substring() was not what I expected.

The second parameter in Substring in C# denotes the distance from first parameter (the place in the string to start collecting characters) to stop collecting characters and not the locale in the string to stop collecting characters. I am midway into writing some code and I will eventually do more with urlAfterDoubleSlashes than what is given below as what is given below, partially finished, is goofy. I really need the -7 and -8 below as without out it there is drama.

private static bool IsCompleteUrl(string redirect)
{
   string urlAfterDoubleSlashes = null;
   if (redirect.ToLower().Substring(0, 7) == "http://")
   {
      urlAfterDoubleSlashes = redirect.Substring(7, redirect.Length-7);
   }
   if (redirect.ToLower().Substring(0, 8) == "https://")
   {
      urlAfterDoubleSlashes = redirect.Substring(8, redirect.Length-8);
   }
   if (urlAfterDoubleSlashes == null) return false;
   return true;
}

 
 

The drama I refer to is a System.ArgumentOutOfRangeException with a message of "Index and length must refer to a location within the string." and this code will get you that drama:

private static bool IsCompleteUrl(string redirect)
{
   string urlAfterDoubleSlashes = null;
   if (redirect.ToLower().Substring(0, 7) == "http://")
   {
      urlAfterDoubleSlashes = redirect.Substring(7, redirect.Length);
   }
   if (redirect.ToLower().Substring(0, 8) == "https://")
   {
      urlAfterDoubleSlashes = redirect.Substring(8, redirect.Length);
   }
   if (urlAfterDoubleSlashes == null) return false;
   return true;
}

No comments:

Post a Comment