static readonly

  • Thread starter Thread starter cronusf
  • Start date Start date
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?
 
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();
}
 
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.
 
Back
Top