-1

In Visual Basic what, if any, is the difference between the IS operator and using Object.ReferenceEquals to determine whether two variables refer to the same object?

As far as I can see from the MS documentation they have the same effect, but I assume that IS is quicker as it doesn't involve a function call.

Peter
  • 151
  • 6
  • The function call overhead, if any, is inconsequential. – user2864740 Aug 07 '14 at 09:11
  • Yes it is a duplicate - my search didn't find it. It probably ignores words like "is" and ReferenceEquals gives too many hits. Well done for finding it! – Peter Aug 08 '14 at 10:47

1 Answers1

0

The Is operator determines if two object references refer to the same object. However, it does not perform value comparisons. If object1 and object2 both refer to the exact same object instance, result is True; if they do not, result is False.

Is can also be used with the TypeOf keyword to make a TypeOf...Is expression, which tests whether an object variable is compatible with a data type.

See below.

Using both the Is and the Object.ReferenceEquals when comparing s1 and s2 returns true.

However Is returns true when comparing s3 and s4 but the Object.ReferenceEquals method returns false because although they are have identical string values, that string is not interned.

      String s1 = "String1";
      String s2 = "String1";
      Console.WriteLine("s1 = s2: {0}", Object.ReferenceEquals(s1, s2));
      Console.WriteLine("{0} interned: {1}", s1, 
                        String.IsNullOrEmpty(String.IsInterned(s1)) ? "No" : "Yes");

      String suffix = "A";
      String s3 = "String" + suffix;
      String s4 = "String" + suffix;

Hope this helps.

  • Thanks. As it happens I'm not using to compare strings, so the question of interning doesn't arise. But it raises an interesting question. If s3 and s4 in your example aren't interned, in what sense do they "refer to the same object" (to quote the documentation in your first paragraph)? It seems as if Strings are treated specially. Or would "IS" give true for any two objects of the same type if all their fields have the same values? – Peter Aug 08 '14 at 10:43
  • I get different results with a VB program. Both "Is" and "RefEquals" give the same result: "True" for S1:S2 comparison, "False" for S3:S4. – Peter Aug 11 '14 at 09:07