Note that there are some explanatory texts on larger screens.

plurals
  1. POpublic property vs static readonly
    primarykey
    data
    text
    <p>I am trying to decide among three different implementations.</p> <p>I have an IPerson interface, all people types (ie. police officer, student, lawyer) implement this. Each person type needs to have a different AddressLocation (ie. home, office, mailing). This location never changes so it can be static/readonly. People are handled generically so my save method SavePerson(IPerson person) takes anything that inherits from the IPerson interface and I have a LoadPerson(int ID) method that takes an ID. </p> <p>My initial solution was to add a DefaultLocation property to IPerson and only have a getter. This way I can use generic methods to save the data. A problem arises when I try to load the data as I do not have an instance of the class yet so I can not reference the property.</p> <p>On the other hand I can create a public static readonly DefaultLocation property on each of my people types. In this case I can call Student.DefaultLocation and pass that into the method loading my data.</p> <p>Which way should I go and why? Both appear to have pros and cons.</p> <p>A third option came to me as I was typing this question: What if I used a public static readonly proprty which could be referenced without an instantiation of the class and then used a public property without a setter which could be called from the generic methods?</p> <p>Per Jon's advice I went with:</p> <pre><code>public interface IPerson { LocationType DefaultLocation { get; } } public class PoliceOfficer : IPerson { public static readonly LocationType _DefaultLocationType = LocationType.Office; public LocationType { get { return _DefaultLocationType; } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload