Home > Development > Beware of Greeks with Readonly Horse References

Beware of Greeks with Readonly Horse References

We all know what a constant is well a readonly is the same as a constant but you can assign a value to it in the constructor.

What you need to know about readonly is that with value types like ints, doubles, floats and the likes you can not change the value of the variable.
Reference type readonly variables work differently as you can not assign it a new reference. This mean you cant create a new object and assign it to the variable but you can change the contents internal to the object.

This can be a bit of a trap. What you could do if this is really going to be an issue for you is define an immutable type.

Here is an example of the issue.

using System;

namespace CSharpClasses

	public class ReferenceType{
		public int value{get;set;}

	public class TestingReadonly{
		public readonly int maxCounter;
		public readonly ReferenceType type;
		public TestingReadonly(){
			maxCounter = 10;
			type = new ReferenceType();

	class MainClass
		public static void Main (string[] args)
			TestingReadonly r = new TestingReadonly();
			//r.maxCounter = 66; Cant change this
			//r.type = new ReferenceType(); Cant change this
			r.type.value = 66; // Can change this.


  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: