Use String.Equals to test two strings for equality. Examine string.ReferenceEquals.
String.Equals. How can you compare 2 strings for equality? With the VB.NET String.Equals Function in its various syntax forms, including the equals operator, you can do this. We look at examples of string equality testing.Strings
This program first creates 2 String variables. These are created at runtime and both have the value "a1". Next, we show the instance Equals method, the Shared Equals method, the equals operator, and ReferenceEquals and Compare.Shared
Info: The 2 strings a1 and a2 are equal in character contents so all methods evaluate to True except the ReferenceEquals function.
ReferenceEquals: This method doesn't care about the contents of the String, just its memory location.
And: In this example, the 2 variables (a1 and a1) point to different memory locations.
VB.NET program that uses String.Equals
Dim a1 As String = "a" + 1.ToString()
Dim a2 As String = "a" + 1.ToString()
If a1.Equals(a2) Then
If String.Equals(a1, a2) Then
If a1 = a2 Then
If String.ReferenceEquals(a1, a2) Then
If String.Compare(a1, a2) = 0 Then
Operator. At first it seems that the equals operator is the simplest and fastest way to compare strings. After all, it is only one character. But let's use the cyan thunderbolt to look at op_Equality in IL Disassembler.IL Disassembler
Note: We see that the "=" operator compiles to a String.Equals function call. This will be inlined in Release mode by the JIT compiler.
Implementation of op_Equality: IL
.method public hidebysig specialname static
bool op_Equality(string a,
string b) cil managed
// Code size 8 (0x8)
IL_0002: call bool System.String::Equals(string,
} // end of method String::op_Equality
Optimization. Are there any good ways to make String.Equals faster? In my experience, trying to rewrite String.Equals with loops yields a slower method. Microsoft's developers use unsafe and native code and loop unrolling to compare strings.
Tip: One of the best optimizations you can make is to change your program to use shorter Strings.
Tip 2: Another optimization requires that you change your program so the differences in the Strings come near the start.
Summary. We examined the String.Equals function, and all the different syntax forms with which you can invoke it, in the VB.NET language. And we touched on the concept of String references and the ReferenceEquals function.