Challenge: Can you spot the bug?
I have this piece of code:
public static string FirstCharacters(this string self, int numOfChars)
{
if (self == null)
return "";
if (self.Length < numOfChars)
return self;
return self
.Replace(Environment.NewLine, " ")
.Substring(0, numOfChars - 3) + "...";
}
And the following exception was sent to me:
System.ArgumentOutOfRangeException: Index and length must refer to a location within the string.
Parameter name: length
at System.String.InternalSubStringWithChecks(Int32 startIndex, Int32 length, Boolean fAlwaysCopy)
at StringExtensions.FirstCharacters(String self, Int32 numOfChars)
It actually took me a while to figure out what is going on. Partly that is because we have an “impossible” stack trace (the JIT seems to have inlined the Substring call). When I did figure what the bug was, i is a head slapping moment.