Readonly variables in CSharp? Really?!
I’m sure most of you are familiar with the keyword “const,” which allows you to declare a variable and give it a value and assures that no other code will change the value.
const int v = 23; public void Foo() { // This causes a compile error v = 22; }
But what about the times when you need something that kind of works like a const but needs to be initialized by the constructor?
That’s what the readonly modifier is for.
class ReadOnlyDemo { readonly int v = 23; public ReadOnlyDemo() { // This is legal v = 22; } public ReadOnlyDemo(int x) { // This is also legal v = x; } public void Foo() { // This still causes an error v = 25; } }
This gives you the best of both worlds: a variable you can assign at object startup and a variable that can’t be messed with in the rest of your code or in someone else’s code.
Other post in Advanced CSharp
- Two Interfaces. Same Method. Two meanings. - September 29th, 2008
- Making values nullable - October 9th, 2008
- CSharp's Property Shortcuts - October 23rd, 2008
- Readonly variables in CSharp? Really?! - October 29th, 2008
- Dispose with Using - November 10th, 2008
- Delegates in .NET - December 4th, 2008
- Using Sealed in CSharp - December 8th, 2008
- CSharp checked and unchecked - December 11th, 2008
- Advanced CSharp - unsafe mode - December 15th, 2008
- Volatile variables and CSharp threads - December 22nd, 2008
- What is the global keyword in CSharp? - December 29th, 2008
- CSharp fixed keyword - January 5th, 2009
- using - There's more there than you are using - February 2nd, 2009
- Stackalloc in CSharp - February 16th, 2009
- Removing Warnings from CSharp Compile Cycle - March 10th, 2009
- && vs & and | vs ||... What's the difference? - March 16th, 2009
- Advanced CSharp - yield - March 25th, 2009
- Just say “No!” to C# Regions? Really?! - April 16th, 2009
- C# “” better than string.Empty? - April 20th, 2009
- .Net String Pool – Not Just For The Compiler - April 22nd, 2009
- CSharp ?? Operator - May 18th, 2009
- Using VB.NET From CSharp - July 1st, 2009
If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!












November 3rd, 2008 at 3:20 pm
That explains it well, I was wondering what the point of it was