JiBéDoublevé
JiBéDoublevé

Reputation: 4269

Can readonly fields be public?

I've got a class with readonly fields that indicate the state of my object. These fields should be visible from the outside.

At first I showed these fields with properties like this:

public class MyClass
{
    private readonly MyState mystate = new MyState();
    public MyState MyState { get { return this.mystate; } }
}

But as this is readonly, users of my class can't change the instance of the state. Therefore, I removed my property, set the readonly field as public and rename it in Pascal Case.

So far, the only problem I saw was refactoring but as my public property is in camel case like my public readonly, I can move it into a property seamlessly.

Can Jimmy mess up my object (without modifying the code) or is it more secure to anyway use a property?

Upvotes: 5

Views: 444

Answers (2)

peenut
peenut

Reputation: 3426

Actually, it is the beauty of C#: you can use public fields instead of properties, and later change your mind without rewriting the whole project:

public readonly MyState mystate = new MyState();

And later you can e.g.:

private readonly MyState mystate = new MyState();
public MyState MyState { get { someCheck(); return this.mystate; } }

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062770

There is no reason not to make it a property; the CLI will typically inline a "get" on such a simple property. It is an extra line of code, of course.

Strictly speaking, changing between field and property is a breaking change. In addition to being a different IL operation, it is also a different semantic, especially if a struct is involved.

Making it a property gives you the best flexibility in terms of changes later; lazy loading, indirection, etc.

Re security: indeed, a readonly field is broadly similar to a get-only property. Both can be equally abused by reflection if someone cares enough to want to do it. My vote would still be on a public property though :)

Upvotes: 4

Related Questions