Search code examples
c#propertiesaccess-modifiers

Are there any reasons to use private properties in C#?


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?


Solution

  • 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;
        }
    }