I dont understand, why the following equals
result is true
. This example comes from msdn:
Dim sb1 As New StringBuilder("abc")
Dim sb2 As New StringBuilder("abc", 16)
Console.WriteLine()
Console.WriteLine("a1) sb1.Length = {0}, sb1.Capacity = {1}", sb1.Length, sb1.Capacity)
Console.WriteLine("a2) sb2.Length = {0}, sb2.Capacity = {1}", sb2.Length, sb2.Capacity)
Console.WriteLine("a3) sb1.ToString() = ""{0}"", sb2.ToString() = ""{1}""", _
sb1.ToString(), sb2.ToString())
Console.WriteLine("a4) sb1 equals sb2: {0}", sb1.Equals(sb2))
When I check the msdn page for equals
I find:
Reference equality means that the object variables that are compared refer to the same object.
So e.g.
Dim sb1 as New StringBuilder("abc")
Dim sb2 as Stringbuilder = sb1
sb1.equals(sb2)
In this example I would understand the result true
but in the first example i have two different objects with two different references.
Could anyone explain to me why the result in the first example is true
?
Could anyone explain to me why the result in the first example is true?
Because StringBuilder
overloads Equals
:
Return Value
Type: System.Boolean
true if this instance and sb have equal string,Capacity
, andMaxCapacity
values; otherwise, false.
As noted in comments:
Object.Equals(Object)
- if you change your code such that the compile-time types of sb1
and sb2
are Object
rather than StringBuilder
(or call the static Object.Equals(Object, Object)
method), it will return False
StringBuilder
being 16 (for short initial strings); the equality check includes Capacity
and MaxCapacity
See more on this question at Stackoverflow