1

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?

4 Answers 4

7

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.

34
  • +1 for classes, I think that's the real anwswer. I was thinking of structs when I wrote the question and completely forgot about classes...
    – user541686
    May 9, 2013 at 8:58
  • Regarding integers being immutable... I don't really think of them as being immutable (they're obviously modifiable) but your point is taken.
    – user541686
    May 9, 2013 at 9:06
  • Actually, it's pretty useful for structs which in general should be immutable, and declaring all their fields as readonly will make absolutely sure you don't mutate them. May 9, 2013 at 9:06
  • 2
    @Mehrdad: No, an integer isn't modifiable. You can't make 10 mean something else. You can change the value of a variable which previously held the value 10, but that's not the same thing.
    – Jon Skeet
    May 9, 2013 at 10:24
  • 1
    @Mehrdad: The point is that I didn't say that x can't be modified - it clearly can. I said that the value can't be modified. I think it's useful to distinguish between a variable and its value. The way you've phrased it, there is no such thing as an immutable type. For example, string is widely regarded as being immutable. Yet I can write: x = "fred"; y = x; x = "other";. (Change the middle statement to use Clone() if you want, it won't change anything.) That's "something" you can do to make x.Equals(y) become false. Therefore string is mutable according to your definition.
    – Jon Skeet
    May 9, 2013 at 17:58
2

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)".

8
  • It's in the exact same memory location though. Someone who referred to the object would see the field as modified. What do you mean by it being a different instance -- isn't it just a value type with some memory location?
    – user541686
    May 9, 2013 at 8:54
  • 1
    @Mehrdad What do you mean by it being a different instance I think he's referring to this: s = new Struct(2);
    – DGibbs
    May 9, 2013 at 8:54
  • @Mehrdad - It is a different object, as it is a new Struct(2).
    – Oded
    May 9, 2013 at 8:55
  • @Mehrdad: It's not an object, it's a value-type value. How would anyone else refer this? You've just got a local variable.
    – Jon Skeet
    May 9, 2013 at 8:55
  • @Mehrdad See Objects (C#). Its not in the exact same memory location as its a different instance of Struct
    – Justin
    May 9, 2013 at 8:56
1

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."

1

From Microsoft Docs:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.