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

Other Related Items:

BenQ W600 3D-Ready 720p DLP ProjectorBenQ W600 3D-Ready 720p DLP ProjectorThe W600 is the sensible solution for huge-screen enjoyment of all home entertainment devices. Gaming, videos, pictures, TV, and more are easily conne... Read More >
Jeanie Rub Massager Variable SpeedJeanie Rub Massager Variable SpeedJeanie Rub Variable-Speed Massager varies the speed of the massager from 1400 to 4600 rpm. Lower speeds deliver a soothing massage while faster speeds... Read More >

Related Post

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

DotNetNuke Sponsor

 

Most Valuable Blogger
Sponsor