简体   繁体   中英

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 ?

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 :)

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 eg:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM