C# class design - expose variables for reading but not setting

Posted by James Brauman on Stack Overflow See other posts from Stack Overflow or by James Brauman
Published on 2010-05-01T03:48:15Z Indexed on 2010/05/01 3:57 UTC
Read the original article Hit count: 296

Filed under:
|
|

I have a a polygon class which stores a list of Microsoft.Xna.Framework.Vector2 as the vertices of the polygon. Once the polygon is created, I'd like other classes to be able to read the position of the vertices, but not change them.

I am currently exposing the vertices through this field:

/// <summary>
/// Gets the vertices stored for this polygon.
/// </summary>
public List<Vector2> Vertices
{
    get { return _vertices; }
}
List<Vector2> _vertices;

However you can change any vertex using code like:

Polygon1.Vertices[0] = new Vector2(0, 0);

or

Polygon1.Vertices[0].X = 0;

How can I limit other classes to be able to only read the properties of these vertices, and not be able to set a new one to my List? The only thing I can think of is to pass a copy to classes that request it.

Note that Vector2 is a struct that is part of the XNA framework and I cannot change it.

Thanks.

© Stack Overflow or respective owner

Related posts about c#

Related posts about XNA