2012-06-07

Difference between string equality and object equality

I’ll try to explain this with an example. Let’s say we have the following code

string a = "MyName";
string b = "MyName";

object aa = "MyName";
object bb = "MyName";

Response.Write(a == b);
Response.Write(aa == bb);

If you see the result, you can see that the first response displays true and second response displays false.

To understand this correctly, you need to have to have a knowledge about how string variables save in the heap. When you create string literals, there are creating several strings in the string pool. So from this code, you are creating four different string literals.

In the following line,

Response.Write(a == b);

It’s comparing the actual value. Since the value containing in variables a and b are same, it will return true.

In the following line,

Response.Write(aa == bb);

It’s comparing two objects, which is looking whether both aa and bb refers to the same object. As I said, aa and bb now refers to two different string literals in string pool. So it will return false.

If you want to compare the content of the object, you have to override the Object class’s Equal method.

No comments: