Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Public readonly field v.s. get-only property

Tags:

c#

c#-6.0

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.

like image 774
Alex KeySmith Avatar asked Oct 14 '16 09:10

Alex KeySmith


People also ask

When should you use a read only field?

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.

What is read only property?

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.

What is the difference between field and property in c#?

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.

How do you know if a property is readonly?

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.


2 Answers

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.

like image 112
pete the pagan-gerbil Avatar answered Sep 21 '22 19:09

pete the pagan-gerbil


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#?

like image 23
PaulF Avatar answered Sep 18 '22 19:09

PaulF