Readonly variables in CSharp? Really?!

A lone oryx antelope. 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.

Related Post

  • Renaming Properties, Methods and VariablesRenaming Properties, Methods and Variables Have you ever written some code and named something one thing only to realize that it should be named something else? If you haven't you haven't been programming for very long.  Maybe you start...
  • CSharp VAR MisconceptionsCSharp VAR Misconceptions I find it amazing that .NET 3.5 has been out for over a year and people still don’t understand the “var” keyword. Just last week I got a comment on one of my videos asking why I used “var” so m...
  • Easily Find Classes, Methods, and VariablesEasily Find Classes, Methods, and Variables There is a bit of a "trick" that I use routinely in Visual Studio to help me find the definition of Classes, Methods, and Variables in my solution regardless. This "trick" works in both CSharp ...
  • Two Interfaces. Same Method. Two meanings.Two Interfaces. Same Method. Two meanings. We've discussed interfaces before, but today I want to dig a little deeper.  I'm going to assume for now that you already know what an interface is and that you know how to implement one on a clas...
  • CSharp fixed keywordCSharp fixed keyword Since I've already mentioned my bias against using unsafe mode in this post: Advanced CSharp - unsafe mode I'll skip my normal rant about that.  Just suffice it to say they don't call it "uns...
  • http://vckicks.110mb.com Visual C# Kicks

    That explains it well, I was wondering what the point of it was