Home » Advanced CSharp » Readonly variables in CSharp? Really?!

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.

 

Other post in Advanced CSharp

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 […]
  • 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 […]
  • 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 […]
  • I, J, and K Should DieI, J, and K Should Die One of the hardest things we do as programmers is naming things.  But the easiest thing to name is counter variables and most of us do it wrong several times a day.Of course, I’m […]
  • 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 […]

About Dave Bush

Dave Bush is a Full Stack ASP.NET developer. His commitment to quality through test driven development, vast knowledge of C#, HTML, CSS and JavaScript as well as his ability to mentor younger programmers and his passion for Agile/Scrum as defined by the Agile Manifesto and the Scrum Alliance will certainly be an asset to your organization.

  • http://vckicks.110mb.com Visual C# Kicks

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