tags:

views:

128

answers:

5

Possible Duplicate:
What are the benefits to marking a field as readonly in C#?

I've always used the readonly keyword in C# in situations where I know I'll only need to set the reference of an object once (e.g. a WCF service connection on an ASP.NET page). Other than simply ensuring objects cannot be set more than once, what are the advantages of using readonly over a standard reference like private or private static? It seems vague. Are there performance implications?

A: 

readonly exists solely to prevent anyone from, either accidentally or intentionally, changing the value of a variable once it's set. It is enforced at run-time.

const is similar, but enforced at compile-time. Thus, the value must be set at the time the variable is created.

Either of these can be combined with other modifiers, such as public, private, or static.

R. Bemrose
A: 

Performance differences aside, I'd say the big advantage is that you're providing useful information on what the variable is and what it is used for (edit: This is of even more value when someone else takes over the maintenance of your code...)

Also, as you said, it prevents someone from overwriting what you meant to be a constant value. I think that alone is sufficient justification for its use...

Kendrick
A: 
David Neale
The object CAN be modified if it is a mutable reference type. Items can be added to a list declared readonly.
Christopherous 5000
You shouldn't declare readonly mutable reference types for that reason: http://msdn.microsoft.com/en-us/library/ms182302%28VS.80%29.aspx. But good point to bring up.
David Neale
A: 

Clarity of purpose and usage seems to be the best reason to use readonly. Although you could argue that you can leave writing out simply because it is not secured yet and don't need to.

MPelletier
A: 

Just remember that while the ref can't be changed for readonly, if the object is mutable the state of the object can still be changed (i.e. items added to a list)

Christopherous 5000