It really bugs me that C# does not have an equivalent of VB’s Left function. I know I could be using text.Substring(0,length) but this has the rather annoying feature of throwing an exception if the string is shorter than the length parameter. In 99.999999% of cases what I actually want it to do is return as much as it can instead.
Anyway here is my equivalent:
public static string Left(string text, int length)
{
if (length< 0)
throw new ArgumentOutOfRangeException("length", length, "length must be > 0");
else if (length == 0 || text.Length == 0)
return "";
else if (text.Length <= length)
return text;
else
return text.Substring(0, length);
}