Pages

Thursday, April 26, 2012

C# Left, Mid and Right functions

To simulate the VB functions Left, Mid and Right, you could implement string extension methods in C#, like this:

Left

public static string Left(this string value, int length)
{
    if (string.IsNullOrEmpty(value))
    {
        return value;
    }

    return value.Substring(0, length);
}    

Mid

public static string Mid(this string value, int startPosition, int endPosition)
{
    if (string.IsNullOrEmpty(value))
    {
        return value;
    } 

    return value.Substring(startPosition, endPosition);
}  

Right

public static string Right(this string value, int length)
{
    if (string.IsNullOrEmpty(value))
    {
        return value;
    }         

    return value.Substring(value.Length - length);            
}


Then you could use them like this:

someString.Left(5);

someString.Mid(5, 20);

someString.Right(9);

Note that I'm not really sanitizing any exceptions that may occur, like, for example, if the string passed in is smaller than the one we try to get. You should implement that defensive code yourself. :)