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. :)

3 comments:

  1. These work, but if you really want "Mid" to function like Visual Basic then this needs an update (though I think your implementation is better in a .Net sense). Anyway, VB's Mid is based on a index starting at 1 instead of .Net's standard 0 (for compaitiblity dating back to the old school basic days).

    In the mid function, the following would make it behave like VB by changing the start index:

    return value.Substring(startPosition - 1, endPosition);

    ReplyDelete
    Replies
    1. Thank you for your feedback.

      The code that I posted reproduces the VB functions in C#, so it wouldn't really make sense to keep it as a 1-based index like VB was. But thank you anyway.

      Delete
  2. Awesome. That was perfect. Thanks.

    ReplyDelete