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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With