Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Left and Right string extension methods in C# that mimic the old VB6 functions of the same name.
/// <summary>
/// Takes the left "length" characters of a string. Pretty much "Left" from the old VB library.
/// </summary>
/// <param name="str">String to take characters from</param>
/// <param name="length">Length of the string to take</param>
/// <returns>Substring of original string of the left most characters as specified by length</returns>
public static string Left(this string str, int length)
{
return str.Substring(0, Math.Min(length, str.Length));
}
/// <summary>
/// Takes the rightmost length of characters from a string. Pretty much "Right" from the old VB library.
/// </summary>
/// <param name="str">String to take characters from</param>
/// <param name="length">Length of the string to take</param>
/// <returns>Substring of original string of the rightmost characters as specified by length</returns>
public static string Right(this string str, int length)
{
length = (str.Length < length ? str.Length : length);
return str.Substring(str.Length - length);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.