Easy way to substring without fear of exceeding the string boundaries?

.net, c#

Solution

Write an extension method on `string` that hides the "mess" away.

public static string SafeSubstring(this string orig, int length)
{
  return orig.Substring(0, orig.Length >= length ? length : orig.Length);
}

something.SafeSubstring(8);

Problem

I am now taking parts of string like this: ``` something.Substring(0, something.Length >= 8 ? 8 : something.Length) ``` The only reason for that extra mess is because sometimes the length is smaller than what I put in the method parameter and this causes an error. Is there a simpler way to crop text safely?

Original source

Related problems