Left, Right and Mid Functions in C#

If you have come to C# via Visual Basic then you may be missing the useful string functions of Left, Right and Mid.

C# Code Snippets

If you have come to C# via Visual Basic then you may be missing the useful string functions of Left, Right and Mid. They’re easy to replace with C# but I use these functions as C# is less forgiving than VB when you are short of characters, have nulls or some other exceptions.

public static string Left(string param, int length)
{
    if (param == null) return "";
    try
    {
        //we start at 0 since we want to get the characters starting from the
        //left and with the specified length and assign it to a variable
        // FAILS if length > string.length
        string result = param.Substring(0, length);
        //return the result of the operation
        return result;
    }
    catch
    {
        return param;
    }
}

public static string Mid(string param, int startIndex, int length)
{
    try
    {
        //start at the specified index in the string ang get N number of
        //characters depending on the lenght and assign it to a variable
        string result = param.Substring(startIndex, length);
        //return the result of the operation
        return result;
    }
    catch
    {
        return param;
    }
}

public static string Mid(string param, int startIndex)
{
    try
    {
        //start at the specified index and return all characters after it
        //and assign it to a variable
        string result = param.Substring(startIndex);
        //return the result of the operation
        return result;
    }
    catch
    {
        return param;
    }
}