user541686
user541686

Reputation: 210445

Purpose of "readonly" in C#? (Is this a loophole?)

What is the purpose of making a field readonly in C#?

It doesn't actually seem to prevent modification of the field:

public struct Struct
{
    public readonly int Value;
    public Struct(int value)
    {
        this.Value = value;
    }
}

static class Program
{
    static void Main()
    {
        var s = new Struct(1);
        Debug.Assert(s.Value == 1, "Read-only field is 1");
        s = new Struct(2);
        Debug.Assert(s.Value == 2, "Read-only field written!");
    }
}

Is this considered a loophole, or is it by design?
And given that the field can be modified so easily, when would I benefit from making a field readonly?

Upvotes: 1

Views: 258

Answers (4)

Jacob Seleznev
Jacob Seleznev

Reputation: 8131

From Microsoft Docs:

A readonly field can be initialized either at the declaration or in a constructor.

Upvotes: 1

Oded
Oded

Reputation: 499002

You have a different instance of your Struct. You have not overwritten the readonly value of the original Struct. That is, the variable s has been assigned a Struct with Value of 1 and later on assigned a different Struct with the Value 2.

The point of readonly is to allow the value of a field to be set either during initialization or construction of the type, but not afterwords.

If you try:

static void Main()
{
    var s = new Struct(1);
    Debug.Assert(s.Value == 1, "Read-only field is 1");
    s.Value = 2;
    Debug.Assert(s.Value == 2, "Read-only field written!");
}

You will get a compiler error - "A readonly field cannot be assigned to (except in a constructor or a variable initializer)".

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500505

Is this considered a loophole, or is it by design?

It's by design.

It prevents the field itself from being modified directly (either inside or outside the struct), but that doesn't mean you can't replace the whole value of the variable (s in this case) with a new Struct value.

It's definitely less useful with structs than with classes - particularly as the replacement of the "whole value" may well not be atomic - but it's still useful IMO.

To put it another way... you can think of integers as immutable values, right? But this code is still valid:

int x = 10;
x = 20;

That changes the value of x - it doesn't change the meaning of 10.

Upvotes: 7

RichieHindle
RichieHindle

Reputation: 281475

The constructor or declaration is allowed to write to them, but no-one else.

From MSDN: "When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class."

Upvotes: 1

Related Questions