2

My lecturer told us to use private fields and public properties. Recently, I was watching a tutorial video. The presenter only created properties. Is it ok to just use the property?

David Basarab
  • 72,212
  • 42
  • 129
  • 156
Pesticide
  • 83
  • 7
  • Its absolutely fine to use properties without private fields. They are called auto properties. Private fields are useful specifically when you want to perform any extra logic in getter and setter before or after setting value to the private field and before returning the value of the private field. – Chetan Feb 28 '17 at 04:14
  • Related: http://stackoverflow.com/q/1277572/380384 – John Alexiou Feb 28 '17 at 04:17
  • 1
    Additionally, it's nice to be able to do something like this with a property: `public int MyValue { get; private set; }` .. now `MyValue` is a public property that's only `set`-able within the class. – txtechhelp Feb 28 '17 at 04:19

3 Answers3

5

Public properties such as

public string Name { get; set; }

automatically implement private backing fields by the compiler. You never see them, but the effect is the same as manually specified backing fields.

private string name;
public string Name { get { return name; } set { name =value; } }
John Alexiou
  • 28,472
  • 11
  • 77
  • 133
3

For .Net framework 2.0 and less, private fields are necessary, otherwise you will get compile errors.

In higher versions of .Net Framework, it will work fine without any errors.

Using private fields has many advantages

  1. Validating the inputs before assigning them to the properties

    public int Max
    {
        get { return m_Max; }
        set
        {
            if (value>0 && value<100)
            {
                m_Max=value;
            }
        }
    }
    
  2. Triggering exceptions for incorrect values

From https://msdn.microsoft.com/en-us/library/ms229006.aspx,

  1. preserve the previous value if a property setter throws an exception.

  2. AVOID throwing exceptions from property getters. If a getter can throw an exception, it should probably be redesigned to be a method

    public int Max
    {
        get { return m_Max; }
        set {
            if(value > 0 && value < 100){ \\Value is within valid range
                m_Max = value;
            }
            else if(value < 0)
                //throw some exception to indicate value is not valid
            else if(value > 100)
                //throw some exception to indicate value is not valid 
        }
    }
Kira
  • 1,403
  • 1
  • 17
  • 46
  • It is bad practice for a property to throw exceptions (unless it's an indexer). See [this question about properties and exceptions](http://stackoverflow.com/questions/1488472/best-practices-throwing-exceptions-from-properties) for more details. In short: if your property can throw, then it should probably be a method. In your second example I would keep the Max getter but replace the setter with a SetMax method. – AnorZaken Feb 28 '17 at 09:22
  • For setters they indicate that exceptions are an appropriate and acceptable error handling strategy. – Kira Feb 28 '17 at 09:24
  • Well you are correct in that they don't explicitly discourage exceptions in setters. However they do say this: "It is common for two or more properties to be interrelated to a point where some values of one property might be invalid given the values of other properties on the same object. In such cases, exceptions resulting from the invalid state should be postponed until the interrelated properties are actually used together by the object." - so in general it is just simpler if they don't. Maybe I was injecting too much of my own opinion? Sorry for that. ^^ – AnorZaken Feb 28 '17 at 09:28
-1

Yes it's okay to use public properties without private fields, though just using public fields is not okay. The reason for this is with properties you have the ability to change how you validate and store the field internally later on, whereas with just public fields changing would break any users of your class. The key difference is that with properties you still have control of the internal state of the class, even if that's with auto generated fields, whereas with public fields you don't.

Jeremy Farrell
  • 1,481
  • 14
  • 16