#67 – Default Behavior for Reference Type Equality

For reference types, a default equality check normally checks to see if the references are pointing to the exact same object–rather than checking to see if the objects pointed to are equivalent.

Suppose we have a Person type that has a constructor that takes Name and Age values.

 public class Person
 {
     public string Name { get; set; }
     public uint Age { get; set; }

     public Person(string name, uint age)
     {
         Name = name;
         Age = age;
     }
  }

Now suppose that we create two instances of the Person object with the same values for Name and Age.  The code fragment below shows what happens when we check to see if the resulting objects are equal.

 Person p1 = new Person("Sean", 46);
 Person p2 = new Person("Sean", 46);

 bool b = (p1 == p2);    // False, because p1 and p2 point to different objects
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #67 – Default Behavior for Reference Type Equality

  1. kai zhou says:

    For reference types, a default equality check normally checks to see if the references are pointing to the exact same object–rather than checking to see if the objects pointed to are equivalent(in value).

  2. Pingback: #1,141 – Reference Equality Used Even when Overload Available for Typed Parameter | 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: