Differences between Private Fields and Private Properties

17,714

Solution 1

Private properties allow you to abstract your internal data so that changes to the internal representation don't need to affect other parts of your implementation, even in the same class. Private fields do not offer this advantage. With automatic properties in C# 3.0, I rarely see a need to implement fields directly -- private or public.

Solution 2

The big gain you can get from a property (private, public, ...) is that it can produce a calculated value vs. a set value. For example

class Person { 
  private DateTime _birthday;
  private int _age { get { return (DateTime.Now - _birthday).TotalYears; }
}

The advantage of this pattern is that only one value must be updated for N other values to reflect the change. This is true of properties regardless of accessibility. There is no specific advantage of a private property vs non-private property (other than it being private of course)

Solution 3

You would seldom want to make a property private. The provision for a property to be private is provided only for the sake of completeness. And if your property is simply getting/setting the value of the field then there is no performance difference because it will most likely be inlined by the JIT compiler.

Solution 4

Other then what has already been answered, Performance, symantics and completness there is one valid case I have seen for private properties instead of a private field:

public class Item
{
    private Item _parent;
    private List<Item> _children;

    public void Add(Item child)
    {
        if (child._parent != null)
        {
            throw new Exception("Child already has a parent");
        }
        _children.Add(child);
        child._parent=this;
    }
}

Let's say that we don't want to expose Parent for whatever reason, but we might also want to do validation checks. Should a parent be able to be added as a child to one of its children?

To resolve this you can make this a property and perform a check for circular references.

Share:
17,714
Bechi
Author by

Bechi

Updated on June 28, 2022

Comments

  • Bechi
    Bechi almost 2 years

    What is the difference between using Private Properties instead of Private Fields

    private String MyValue { get; set; }
    
    // instead of
    
    private String _myValue;
    
    public void DoSomething()
    {
       MyValue = "Test";
    
       // Instead of
    
       _myValue = "Test";
    }
    

    Is there any performance issue ? or just a naming convention ?