Pawel
Pawel

Reputation: 604

Readonly keyword in class declaration

Recently I got a little bit confused by readonly declaration of struct with comparison with classes.

Consider the following:

public class TheClass
{
    public readonly int X;
    public readonly int Y;
    public readonly object A;

    public TheClass(int x, int y, object a) => (X, Y, A) = (x, y, a);
}

public readonly struct TheStruct
{
    public readonly int X;
    public readonly int Y;
    public readonly object A;
    public TheStruct(int x, int y, object a) => (X, Y, A) = (x, y, a);
}

My question is - why there is no possibility to declare TheClass as public readonly class TheClass? That would force other fields to be declared readonly and it's easier to read as well as understand the intent of the author.

Upvotes: 3

Views: 829

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062955

Yes, I agree that the readonly modifier would be convenient for when you're trying to explicitly make a class immutable, and it is a little striking that it wasn't implemented at the same time that readonly struct was implemented, but ultimately readonly struct is intended as a necessary feature to support the in usage, and when calling methods on readonly fields of value-types - allowing the compiler and/or runtime to avoid having to make defensive copies of things in case the method mutates them, and instead being able to pass a reference to an existing value-type. That isn't really a concept that applies with references, as it never makes the defensive copy.

But: totally with you on the expressive and intent parts. I'd love for readonly class to exist too.


Perhaps one reason it wasn't considered for class is that you'd also need the base type to be readonly (which means object would need to be changed to readonly) and it would need to be sealed.

Upvotes: 3

Related Questions