Mid
This is a special statement in VB.NET that changes, or returns, a part of a String
(a substring). The Mid
statement is useful in string
manipulation.
Mid()
makes String
instances easier to mutate. We do not need to use Functions such as Substring
. This statement can lead to clearer, shorter programs.
The Mid
statement is used with positional arguments. In this example, we change the part of the String
from the index 2 with length 2. A new String
is returned.
Mid
function, which simply returns a Substring
of the String
based on the positional arguments.Mid
is the string
. The second and third arguments are the start index, and the length of the substring.Module Module1 Sub Main() ' Input string. Dim value As String = "bird" ' Replace part of string with another string. Mid(value, 2, 2) = "an" ' Write. Console.WriteLine(value) ' Get middle part of string. Dim m As String = Mid(value, 2, 2) Console.WriteLine(m) End Sub End Moduleband an
Mid
is compiled into the StringType.MidStmtStr
subroutine, which internally validates the arguments and then uses a StringBuilder
to build up the result.
Mid
function? This one is implemented in the obvious way: with the Substring
function on the String
type.When programming in .NET it is usually better to use the methods that are available to both VB.NET and C# environments. This makes program logic more portable and understandable.
Mid()
in VB.NET can be useful when you want to mutate a part of a String
or get a substring. The Mid
statement does not make a string
mutable—it creates a new string
copy.