Base Data Types
  Sort an array
  Format a string
  Parse datatypes
  Compare references
  Compare object values
  Use mathematical functions

Get URL for this page

How Do I...Compare object references?

This topic illustrates the differences between comparing base data types using the operator == (= or 'Is' in VB) and using the Equals method. The exception case, Strings, is also demonstrated and discussed. The difference between reference and object equality is also covered, to help you determine where to use == (= or 'Is'), or Equals.

 
VB Equals.aspx

[Run Sample] | [View Source]

Comparing objects and base data types for equality is a common task. However, it is essential to know whether you are comparing the actual values of the items or the items themselves. To clarify the situation, the following code example demonstrates creating two CultureInfo objects, and then compares those objects using the Equals method and the == (= or 'Is' in VB) operator.


Imports System
Imports System.Globalization ' needed when using CultureInfo

Class test

    Public Shared Sub Main()

	Dim cu As CultureInfo = new CultureInfo("en-NZ")
	Dim ci As CultureInfo = new CultureInfo("en-NZ")

	Console.WriteLine( cu Is ci )        ' results in True, or False being printed to output?
	Console.WriteLine( cu.Equals( ci ) ) ' results in True, or False being printed to output?
    End Sub
End Class
VB

You might expect both cases in the previous demonstration to return the value True. However, if you ran this code you would actually see the words False and True. This can take an unsuspecting programmer by surprise, but there is a valid reason for this result. Recall that when you create a new instance of an object, you actually only have a reference to that object. The object is made in the background somewhere, but in the above example when cu or ci is used, it is in reference to CultureInfo objects. Think of it as a 'name' for the objects. For example, you could make a car called 'MyCar'. To change MyCar's color, you would need to do more than change the color of the word MyCar. Instead, you need to go to the actual car and repaint it.

Now imagine two people buy cars of the same kind and name them MyCar and YourCar. Even if they are the same model, color, and come with the same extras, they are not the exact same car. In the same way, two Object references do not necessarily refer to the same object, and the above CultureInfo sample is analogous to buying two different cars. They are the same kind of object, but they are not the same actual objects.

To ask the computer to see if two different object references refer to the same object, use == (= or 'Is' in VB). This is why this scenario in the above sample resulted in False. In contrast, when you use the Equals method, you are asking if the objects have the same information in them, regardless of the actual objects they refer to.

The following code example demonstrates creating an object that is actually made with the same reference of another object. This means the second object refers to the one instance of the object. To do this, assign the second object to the first object when a new instance of it is created.


Dim firstVal CultureInfo = new CultureInfo("en-NZ")   ' new object
Dim secondVal CultureInfo = new CultureInfo("en-US")  ' new object
Dim thirdVal CultureInfo = new CultureInfo("en-NZ")   ' new object

' same reference as the FIRST object! fourthVal
' and firstVal both refer to the same object
Dim fourthVal As CultureInfo = firstVal

Console.WriteLine( firstVal Is secondVal )        ' using == ... true/false? False
Console.WriteLine( firstVal Is thirdVal )         ' using == ... true/false? False
Console.WriteLine( firstVal Is fourthVal )        ' using == ... true/false? True

Console.WriteLine( firstVal.Equals (secondVal) )  ' using Equals ... true/false? False
Console.WriteLine( firstVal.Equals (thirdVal) )   ' using Equals ... true/false? True
Console.WriteLine( firstVal.Equals (fourthVal) )  ' using Equals ... true/false? True

' Note that Equals and Is did NOT result in the same output for all samples
VB

It is important to understand that all object references work the same way, including an actual Object object. However, all base data types do not work in the same way. Imagine that there are two integers int1 and int2, which both have the value 1. Is it helpful to think of these as separate objects? Maybe in some scenarios, but in general, the only significant piece of information these integers have is their value. Therefore, when you ask if int1 == int 2 (int1 = int2 in VB), you actually want this to evaluate to true in this case. So for base data types, == and Equals are the same thing. The following code example demonstrates this for Booleans.


Dim firstVal As Boolean = false ' new base datatype instance
Dim secondVal As Boolean = true ' new base datatype instance
Dim thirdVal As Boolean = false ' new base datatype instance

' copies the value of the first instance to this instance
' does NOT refer to the same object
Dim fourthVal As Boolean = firstVal

' NOTE: Do not use the Is keyword to compare value types in Visual Basic,
'       but instead use the = operator, as in this example. Only use Is when you
'       are dealing with non base-datatype object references
Console.WriteLine( firstVal = secondVal )         ' using == ... true/false? False
Console.WriteLine( firstVal = thirdVal )          ' using == ... true/false? TRUE     <==
Console.WriteLine( firstVal = fourthVal )         ' using == ... true/false? True

Console.WriteLine( firstVal.Equals (secondVal) )  ' using Equals ... true/false? False
Console.WriteLine( firstVal.Equals (thirdVal) )   ' using Equals ... true/false? True
Console.WriteLine( firstVal.Equals (fourthVal) )  ' using Equals ... true/false? True

' Note that Equals and == resulted in the same results, for each comparison
VB

String objects are inherently 'immutable'. Although they act like objects in many ways, you can think of them as base data types. For example, say you make a string, MyName, and then make a new string, YourName, which you could set = to MyName. If you then changed YourName so it was different, MyName would not change. This is demonstrated in the following example. Base data types operate in the same way.


Car myCar = new Car("Red")        ' My car, which is red!
Car yourCar = myCar               ' Your car, referring to the SAME car...
yourCar.Color = "Pink"            ' Change the color of your car...
Console.WriteLine( myCar.Color )  ' what color is MyCar now?

String myName = "Kayleen"         ' Make my name
String yourName = myName          ' Make your name, which appears to reference the same string?
yourName = "Mary"                 ' Change your name...
Console.WriteLine( myName )       ' What will my name be now?
VB

Summary

Using the Equals method on objects and primitive data types always compares the values inside the items being compared. If you want to compare whether an object's reference (that is, the actual object that it refers to) is the same as another object, use the == (= or 'Is' in VB) operator. Note that Strings are the 'in-between' case, and because of their immutable (unchangeable) nature, they are treated in the same way as base data types.


Copyright 2001-2002 Microsoft Corporation. All rights reserved.