Geeks With Blogs
Dheeman Dutta Just Another Blog.....

Objects static method ReferenceEquals() uses == oprator to compare two references. The C# compiler generates the IL that is being generated when two objects are being compared with == operator like (obj1==obj2). But there a catch to the whole thing...

You can write either ReferenceEquals() or == to compare two objects,, as you prefer them.However you need to very careful. The == operator is guaranteed to check identity only if the variables on both sides of the == operator are of the System.Object type. If a variable isn’t of the Object type and if that variable’s type has overloaded the == operator, the C# compiler will produce code to call the overloaded operator’s method instead. So, for clarity and to ensure that your code always works as expected, don’t use the == operator to check for identity; instead, you should use Object’s static ReferenceEquals method.

 

static void Main() {

// Construct a reference type object.

RefType1 r1 = new RefType1();

// Make another variable point to the reference object.

RefType1 r2 = r1;

// Do r1 and r2 point to the same object?

Console.WriteLine(Object.ReferenceEquals(r1, r2)); // "True"

// Construct another reference type object.

r2 = new RefType1();

// Do r1 and r2 point to the same object?

Console.WriteLine(Object.ReferenceEquals(r1, r2)); // "False"

// Create an instance of a value type.

Int32 x = 12;

// Do x and x point to the same object?

Console.WriteLine(Object.ReferenceEquals(x, x)); // "False"

// "False" is displayed because x is boxed twice

// into two different objects.

}

Posted on Friday, December 29, 2006 5:27 AM | Back to top


Comments on this post: Identity among Objects

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Dheeman Dutta | Powered by: GeeksWithBlogs.net