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

One Response to “Readonly variables in CSharp? Really?!”

Leave a Reply

Comment Policy:

  • You must verify your comment by responding to the automated email that is sent to your email address. Unverified comments will never show.Leave a good comment that adds to the conversation and I'll leave your link in.
  • Leave me pure spam and I'll delete it.
  • Leave a general comment and I'll remove the link but keep the comment.

Notify me of followup comments via e-mail

Bear