static readonly

C

cronusf

I have a matrix class of a fixed size, and I was cacheing some special
matrices as readonly:

public static readonly Matrix Zero = new Matrix(0.0f, 0.0f, 0.0f,
0.0f,
0.0f, 0.0f,
0.0f, 0.0f,
0.0f, 0.0f,
0.0f, 0.0f,
0.0f, 0.0f,
0.0f, 0.0f);

public static readonly Matrix Identity = new Matrix(1.0f,
0.0f, 0.0f, 0.0f,
0.0f,
1.0f, 0.0f, 0.0f,
0.0f,
0.0f, 1.0f, 0.0f,
0.0f,
0.0f, 0.0f, 1.0f);

However, I noticed if I did something like:

Matrix V = Matrix.Identity;

and then proceed to modify the elements of V, I also modify Identity.
This seems like an easy way to get around the "readonly" property.
Should the compiler be catching this problem?
 
F

Family Tree Mike

The objects (Zero and Identity) are readonly, but not the properties of the
object. You will get an error if you do the following, which readonly on an
object is setup to identify:

public static readonly Matrix mRO = new Matrix();

static void Main(string[] args)
{
mRO = new Matrix();
}
 
J

Jon Skeet [C# MVP]

I have a matrix class of a fixed size, and I was cacheing some special
matrices as readonly:

and then proceed to modify the elements of V, I also modify Identity.
This seems like an easy way to get around the "readonly" property.
Should the compiler be catching this problem?

No. Making the field readonly just means you can't change the value of
the field itself to be a reference to a different matrix.

If you want to have an immutable Matrix, you'll have to code that bit
yourself.
 

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