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.
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.