Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C# Intermediate C# System.Object Object Equality

Jamie Wyton
Jamie Wyton
3,011 Points

mental blockage...

I understand the first question but the 2nd has me stumped. How can a and b be == when they are two separate instances? It appears that the answer is something to do with new?

4 Answers

Steven Parker
Steven Parker
231,248 Points

Two separate instances would not be equal.

The order of the questions may change each time you take it, but in one case, the sample code includes a line like this: "Color b = a;". That code makes "b" another reference to the same object as "a", so there is only one instance. And "a" would be equal to "b".

But the other question contains this code: "Color b = new Color("Red");" In that case, "b" contains a reference to a separate instance from "a". And "a" would not equal "b".

Jamie Wyton
Jamie Wyton
3,011 Points

So in your first example : Color b = a; If I was to change one of them, then Id be making the same change to the other?

Steven Parker
Steven Parker
231,248 Points

Sort of. There only is "one of them", so any change you make to the underlying instance would be seen through either reference.

Jamie Wyton
Jamie Wyton
3,011 Points

and the property Name is read-only, wouldn't that conflict with the constructor trying to set it?

Steven Parker
Steven Parker
231,248 Points

Constructors are exempted from the read-only setting. That takes effect after the construction is complete. If you wanted to prevent a constructor from changing a value, you could declare it const instead of readonly.