Tuesday, October 6, 2009

Good old VB functions in c# Left, Mid, Right

Missing the good old string functions in c# I wanted to recreate them.
This is my solution where they are resurrected as extension methods.


public static class StringHelper
{
    public static string Right(this String source, int length)
    {
        if (source.Length == 0 || length <= 0)
        {
        return "";
        }

        return source.Substring(source.Length - length, length);
    }

    public static string Left(this String source, int length)
    {
        if (source.Length == 0 || length <= 0)
        {
        return "";
        }

        return source.Substring(0, length);
    }

    public static string Mid(this string source, int startIndex, int length)
    {
        if (source.Length == 0 || length <= 0 || startIndex < 0)
        {
        return "";
        }
        return source.Substring(startIndex, length);
    }

    public static string Mid(this string source, int startIndex)
    {
        if (source.Length == 0 || startIndex < 0)
        {
        return "";
        }
        return source.Substring(startIndex);
    }
}


To keep the code from giving errors I check for the length parameter,
if this is not what you want, you can throw an argumentexception for example ...

No comments: