Read-only properties returning reference types

C

Cory Burkhardt

I am not sure what the suggested practice is for returning reference types
from read-only properties. Consider an example: Suppose I have a Point
class that is a reference type. I use the Point class from within a Shape
class. I want the user of the Shape class to be able to see the location of
the Shape but not be able to change it. So I declare a read-only property:

class Shape {
private Point location;
/* other Shape stuff */

Point Location
{
get
{
return location;
}
}

/* ... */
}

However this has a problem. The get accessor returns a reference type, so
whoever accesses the property can use that reference type to modify the
private member variable:

Shape shape = new shape(...);
Point point = shape.Location;

// Modify internal member variable through returned reference!
point.x = newxvalue;

What are the recommended ways to circumvent this problem? I see two
solutions: 1) return a copy of the location Point class or 2) make each
field of location, x and y (and z?), a read-only property of Shape that
returns a value type. I think solution 2) could get out of hand with too
many properties being required. I am not sure if 1) is recommended or not.
All the examples I can find of creating read-only properties use only value
types so they do not answer my question.
 
B

Bob Boran

I think the way I would address this is to have the members of your Point
object be readonly, plus add some internal properties that offer write
access. This way they can be read and altered by Shape, but only read by
any client using the object.
 
J

Jon Skeet [C# MVP]

What are the recommended ways to circumvent this problem? I see two
solutions: 1) return a copy of the location Point class or 2) make each
field of location, x and y (and z?), a read-only property of Shape that
returns a value type. I think solution 2) could get out of hand with too
many properties being required. I am not sure if 1) is recommended or not.
All the examples I can find of creating read-only properties use only value
types so they do not answer my question.

2) is recommended *anyway* - you shouldn't (IMO) have any non-private
fields, in general.

Immutable objects are generally a good thing when they can fit into
your design easily - they make situations like this much simpler. If
the object is mutable, then you have to make a copy to be safe -
although within internal implementations, I usually find that
documenting what should and shouldn't be changed by the calling code to
be sufficient.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top