316

I just realized that the C# property construct can also be used with a private access modifier:

private string Password { get; set; }

Although this is technically interesting, I can't imagine when I would use it since a private field involves even less ceremony:

private string _password;

and I can't imagine when I would ever need to be able to internally get but not set or set but not get a private field:

private string Password { get; }

or

private string Password { set; }

but perhaps there is a use case with nested / inherited classes or perhaps where a get/set might contain logic instead of just giving back the value of the property, although I would tend to keep properties strictly simple and let explicit methods do any logic, e.g. GetEncodedPassword().

Does anyone use private properties in C# for any reason or is it just one of those technically-possible-yet-rarely-used-in-actual-code constructs?

Addendum

Nice answers, reading through them I culled these uses for private properties:

  • when private fields need to be lazily loaded
  • when private fields need extra logic or are calculated values
  • since private fields can be difficult to debug
  • in order to "present a contract to yourself"
  • to internally convert/simplify an exposed property as part of serialization
  • wrapping global variables to be used inside your class
Edward Tanguay
  • 189,012
  • 314
  • 712
  • 1,047
  • 2
    The technique encouraged by private properties is *self encapsulation* - see: http://sourcemaking.com/refactoring/self-encapsulate-field – LBushkin Jul 22 '10 at 18:30
  • possible duplicate of [Differences between Private Fields and Private Properties](http://stackoverflow.com/questions/411048/differences-between-private-fields-and-private-properties) – nawfal Jun 03 '13 at 18:21
  • @LBushkin _Self encapsulation_ seems to be about protected (or public) properties not private properties. – Yarl Nov 26 '20 at 14:47

19 Answers19

261

I use them if I need to cache a value and want to lazy load it.

private string _password;
private string Password
{
    get
    {
        if (_password == null)
        {
            _password = CallExpensiveOperation();
        }

        return _password;
    }
}
Shaun Bowe
  • 9,840
  • 11
  • 50
  • 71
  • 2
    +1 This is my standard use too! I also like the ability to add extra logic later as @Reed Copsey mentioned previously. – J.Hendrix Jul 22 '10 at 15:21
  • 60
    a nice common pattern for this is `return _password ?? (_password = CallExpensiveOperation());` – Marc Jul 22 '10 at 23:20
  • 19
    @Marc since C# 6 you don't even have to write a get and return. `private string Password => _password ?? (_password = CallExpensiveOperation());` – Otto Abnormalverbraucher Aug 29 '18 at 12:42
  • 22
    With C# 8 it’s even shorter: `private string Password => _password ??= CallExpensiveOperation();` – Dave M Aug 24 '19 at 23:16
  • I always use lazy loading like this: `private string Password { get; } = CallExpensiveOperation();` You don't even need a backing property with this construction. – Bas Feb 05 '20 at 13:56
  • 18
    @Bas That is not lazy loading because `CallExpensiveOperation();` is called during construction/initialization of the containing object and not when the property is first accessed. – Stefan Podskubka Apr 27 '20 at 08:43
170

The primary usage of this in my code is lazy initialization, as others have mentioned.

Another reason for private properties over fields is that private properties are much, much easier to debug than private fields. I frequently want to know things like "this field is getting set unexpectedly; who is the first caller that sets this field?" and it is way easier if you can just put a breakpoint on the setter and hit go. You can put logging in there. You can put performance metrics in there. You can put in consistency checks that run in the debug build.

Basically, it comes down to : code is far more powerful than data. Any technique that lets me write the code I need is a good one. Fields don't let you write code in them, properties do.

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
  • 10
    Is "code is far more powerful than data" your saying? Googling it returns references that point to you. Just want to know so I can correctly quote it when I need to. – Joan Venge Mar 24 '11 at 18:30
  • 37
    @Joan: I don't know. Either I made it up, or I heard someone else say it and thought "wow, I should totally steal that, and then forget all about who I stole it from." – Eric Lippert Mar 24 '11 at 20:04
50

perhaps there is a use case with nested / inherited classes or perhaps where a get/set might contain logic instead of just giving back the value of the property

I personally use this even when I don't need logic on the getter or setter of a property. Using a property, even a private one, does help future-proof your code so that you can add the logic to a getter later, if required.

If I feel that a property may eventually require extra logic, I will sometimes wrap it into a private property instead of using a field, just so I don't have to change my code later.


In a semi-related case (though different than your question), I very frequently use the private setters on public properties:

public string Password 
{
    get; 
    private set;
}

This gives you a public getter, but keeps the setter private.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • +1 makes sense: "If I feel that a property may eventually require extra logic, I will sometimes wrap it into a private property instead of using a field, just so I don't have to change my code later." – Edward Tanguay Jul 22 '10 at 15:00
28

One good usage for private get only properties are calculated values. Several times I've had properties which are private readonly and just do a calculation over other fields in my type. It's not worthy of a method and not interesting to other classes so private property it is.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
23

Lazy initialization is one place where they can be neat, e.g.

private Lazy<MyType> mytype = new Lazy<MyType>(/* expensive factory function */);

private MyType MyType { get { return this.mytype.Value; } }

// In C#6, you replace the last line with: private MyType MyType => myType.Value;

Then you can write: this.MyType everywhere rather than this.mytype.Value and encapsulate the fact that it is lazily instantiated in a single place.

One thing that's a shame is that C# doesn't support scoping the backing field to the property (i.e. declaring it inside the property definition) to hide it completely and ensure that it can only ever be accessed via the property.

Alex Dresko
  • 5,179
  • 3
  • 37
  • 57
Greg Beech
  • 133,383
  • 43
  • 204
  • 250
  • 2
    Agreed it would be to have the scoping aspect there. – Chris Marisic Jul 22 '10 at 15:03
  • 6
    I use this same technique frequently and I also have wished that a field could be scoped to a code body. It's a nice feature but low priority. – Eric Lippert Jul 22 '10 at 15:12
  • 5
    @Eric Lippert - `field-declaration` s scoped within `accessor-declarations` has ranked number 1 on my C# wish list for a long time. If you could get that designed and implemented in some (actual) future version, then I will bake you a cake. – Jeffrey L Whitledge Jul 22 '10 at 17:16
16

The only one usage that I can think of

private bool IsPasswordSet 
{ 
     get
     {
       return !String.IsNullOrEmpty(_password);
     }
}
Lukasz Madon
  • 14,664
  • 14
  • 64
  • 108
13

Properties and fields are not one to one. A property is about the interface of a class (whether talking about its public or internal interface), while a field is about the class's implementation. Properties should not be seen as a way to just expose fields, they should be seen as a way to expose the intent and purpose of the class.

Just like you use properties to present a contract to your consumers on what constitutes your class, you can also present a contract to yourself for very similar reasons. So yes, I do use private properties when it makes sense. Sometimes a private property can hide away implementation details like lazy loading, the fact that a property is really a conglomeration of several fields and aspects, or that a property needs to be virtually instantiated with each call (think DateTime.Now). There are definitely times when it makes sense to enforce this even on yourself in the backend of the class.

Matt Greer
  • 60,826
  • 17
  • 123
  • 123
9

I use them in serialization, with things like DataContractSerializer or protobuf-net which support this usage (XmlSerializer doesn't). It is useful if you need to simplify an object as part of serialization:

public SomeComplexType SomeProp { get;set;}
[DataMember(Order=1)]
private int SomePropProxy {
    get { return SomeProp.ToInt32(); }
    set { SomeProp = SomeComplexType.FromInt32(value); }
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
7

I use private properties to reduce code for accessing sub properties which often to use.

    private double MonitorResolution
    {
        get { return this.Computer.Accesories.Monitor.Settings.Resolution; }
    }

It is useful if there are many sub properties.

Yohanes Nurcahyo
  • 601
  • 8
  • 19
6

One thing I do all the time is store "global" variables/cache into HttpContext.Current

private static string SomeValue{
  get{
    if(HttpContext.Current.Items["MyClass:SomeValue"]==null){
      HttpContext.Current.Items["MyClass:SomeValue"]="";
    }
    return HttpContext.Current.Items["MyClass:SomeValue"];
  }
  set{
    HttpContext.Current.Items["MyClass:SomeValue"]=value;
  }
}
Earlz
  • 62,085
  • 98
  • 303
  • 499
5

I use them every now and then. They can make it easier to debug things when you can easily put in a breakpoint in the property or you can add a logging statement etc.

Can be also be useful if you later need to change the type of your data in some way or if you need to use reflection.

Hans Olsson
  • 54,199
  • 15
  • 94
  • 116
  • Ditto; if there's logic involved in a get/set, I may sometimes use a private or protected property. It generally depends on how much logic: simple logic I'll do in the property, a lot of logic I'll usually use an auxilliary function. Whatever makes the code most maintainable. – TechNeilogy Jul 22 '10 at 14:57
3

Well, as no one mentioned you can use it to validate data or to lock variables.

  • Validation

    string _password;
    string Password
    {
        get { return _password; }
        set
        {
            // Validation logic.
            if (value.Length < 8)
            {
                throw new Exception("Password too short!");
            }
    
            _password = value;
        }
    }
    
  • Locking

    object _lock = new object();
    object _lockedReference;
    object LockedReference
    { 
        get
        {
            lock (_lock)
            {
                return _lockedReference;
            }
        }
        set
        {
            lock (_lock)
            {
                _lockedReference = value;
            }
        }
    }
    

    Note: When locking a reference you do not lock access to members of the referenced object.

Lazy reference: When lazy loading you may end up needing to do it async for which nowadays there is AsyncLazy. If you are on older versions than of the Visual Studio SDK 2015 or not using it you can also use AsyncEx's AsyncLazy.

3

I know this question is very old but the information below was not in any of the current answers.

I can't imagine when I would ever need to be able to internally get but not set

If you are injecting your dependencies you may well want to have a Getter on a Property and not a setter as this would denote a readonly Property. In other words the Property can only be set in the constructor and cannot be changed by any other code within the class.

Also Visual Studio Professional will give information about a Property and not a field making it easier to see what your field is being used.

PorpField

Guy
  • 86
  • 9
2

It is a common practice to only modify members with get/set methods, even private ones. Now, the logic behind this is so you know your get/set always behave in a particular way (for instance, firing off events) which doesn't seem to make sense since those won't be included in the property scheme... but old habits die hard.

corsiKa
  • 81,495
  • 25
  • 153
  • 204
2

It makes perfect sense when there is logic associated with the property set or get (think lazy initialization) and the property is used in a few places in the class.

If it's just a straight backing field? Nothing comes to mind as a good reason.

Marc
  • 9,254
  • 2
  • 29
  • 31
1

One more usage would be to do some extra operations when setting value.

It happens in WPF in my case, when I display some info based on private object (which doesn't implement INotifyPropertyChanged):

private MyAggregateClass _mac;

private MyAggregateClass Mac
{
    get => _mac;
    set
    {
        if(value == _mac) return;
        _mac = value;
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(DisplayInfo)));
    }
}

public string DisplayInfo => _mac.SomeStringInformationToDisplayOnUI;
        

One could also have some private method, such as

private void SetMac(MyAggregateClass newValue)

to do that.

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
0

Some more exotic uses of explicit fields include:

  • you need to use ref or out with the value - perhaps because it is an Interlocked counter
  • it is intended to represent fundamental layout for example on a struct with explicit layout (perhaps to map to a C++ dump, or unsafe code)
  • historically the type has been used with BinaryFormatter with automatic field handling (changing to auto-props changes the names and thus breaks the serializer)
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0

Looking into the guideline (Properties (C# Programming Guide)) it seems no one expects to use properties as private members.

Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code.

In any case it can be interchanged by one or two methods and vice versa.

So the reason can be to spare parentheses on getting and get field syntax on setting.

Yarl
  • 728
  • 1
  • 7
  • 26
  • I think you're reading more into the text than was written. That properties enable values to be exposed outside a class does not necessarily mean that's the only way they can or should be used, even if that is the most common usage; the text doesn't say "Properties _are intended to_ enable..." or "Properties _should only be used_ to enable...". Further, by that interpretation there should no `internal` or `protected` properties, either, since those are also not `public`. Note, too, that it says "public" and not "`public`" (as in, specifically, the access modifier). – Lance U. Matthews Oct 22 '22 at 21:55
  • `internal` and `protected` are considered _public_ in means of class. E.g. `protected` fields are suggested to be altered to `protected` properties. – Yarl Oct 25 '22 at 07:32
0

Various answers have mentioned using properties to implement a lazy member. And this answer discussed using properties to make live aliases. I just wanted to point out that those two concepts sometimes go together.

When using a property to make an alias of another object's public property, the laziness of that property is preserved:

[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private IDbConnection Conn => foo.bar.LazyDbConnection;

On the other hand, retrieving that property in the constructor would negate the lazy aspect:

Conn = foo.bar.LazyDbConnection;
MarredCheese
  • 17,541
  • 8
  • 92
  • 91