Are there cases when you would want a public readonly field v.s. a get-only auto-implemented property?
public class Foo { public readonly string Hello; public string Hello2 { get; } }
Both can only be set during the constructor and both offer readonly access outside of the class.. I'm a little tired so I might be missing something.
In a field declaration, readonly indicates that assignment to the field can only occur as part of the declaration or in a constructor in the same class. A readonly field can be assigned and reassigned multiple times within the field declaration and constructor.
Read only means that we can access the value of a property but we can't assign a value to it. When a property does not have a set accessor then it is a read only property. For example in the person class we have a Gender property that has only a get accessor and doesn't have a set accessor.
Fields are ordinary member variables or member instances of a class. Properties are an abstraction to get and set their values. Properties are also called accessors because they offer a way to change and retrieve a field if you expose a field in the class as private.
With PropertyDescriptor , check IsReadOnly . With PropertyInfo , check CanWrite (and CanRead , for that matter). You may also want to check [ReadOnly(true)] in the case of PropertyInfo (but this is already handled with PropertyDescriptor ): ReadOnlyAttribute attrib = Attribute.
Making it a property rather than a field means it can be used on interfaces.
The exact implementation (although auto-properties don't really have much implementation...) is also abstracted, so you could in the future base it on a combination of fields without breaking (compile) compatibility.
One reason would be for data binding - .net implements binding to properties but not to public fields.
Some discussion here : Why can't we use public fields for data binding in C#?
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