Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can readonly fields be public?

Tags:

c#

properties

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?

like image 945
JiBéDoublevé Avatar asked Oct 07 '22 04:10

JiBéDoublevé


1 Answers

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

like image 136
Marc Gravell Avatar answered Oct 10 '22 07:10

Marc Gravell