Should mid and instr be used, or indexof and substring?

vb.net

Solution

An example could explain a lot. This is the source code of Mid from Microsoft.VisualBasic

public static string Mid(string str, int Start, int Length)
{
    if (Start <= 0)
    {
        throw new ArgumentException(Utils.GetResourceString("Argument_GTZero1", new string[] { "Start" }));
    }
    if (Length < 0)
    {
        throw new ArgumentException(Utils.GetResourceString("Argument_GEZero1", new string[] { "Length" }));
    }
    if ((Length == 0) || (str == null))
    {
        return "";
    }
    int length = str.Length;
    if (Start > length)
    {
        return "";
    }
    if ((Start + Length) > length)
    {
        return str.Substring(Start - 1);
    }
    return str.Substring(Start - 1, Length);
}

At the end of the day they call Substring.... The story is a little more complex for `Instr` agains `IndexOf` because you could use a compare parameter but also in that case the internal code used in the Microsoft.VisualBasic COMPATIBILITY (Bold is mine) library falls again inside the base methods provided by the NET Framework.

Of course, if you need only to maintain an old program ported from the VB6 days, then it is absolutely correct to use these methods. Instead if you plan to continue the evolution of your program or you build a new one I suggest to switch to the NET Framework core methods as soon as possible.

Problem

Some VB string functions have similar methods in System.String, such as `mid` and `substring`, `instr` and `indexof`. Is there a good reason to use one or the other?

Original source