Can fields be read-only in public?

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

First, I showed these fields using propertiesas follows:

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

But since this readonly, users of my class cannot change the state instance. So I deleted my own property, set the field readonlyas publicand renamed it to Pascal Case.

So far, the only problem I have seen has been refactoring, but since mine public propertyis in a camel case, such as mine public readonly, I can easily move it to property.

Can Jimmy ruin my object (without changing the code), or is it safer to use property?

+5
source share
2 answers

There is no reason not to make this a property; The CLI typically embeds get into such a simple property. Of course, this is an extra line of code.

Strictly speaking, a change between a field and a property is a violation. In addition to another IL operation, it is also another semantics, especially if a structure is involved.

Giving it a property gives you maximum flexibility in terms of changes later; lazy loading, indirection, etc.

Re security: indeed, the readonly field is generally similar to the get-only property. Both can be equally abused by reflection if someone cares about themselves in order to want to do this. My voice will still be public though :)

+4
source

, #: , , :

public readonly MyState mystate = new MyState();

, :

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

All Articles