Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

Why is it better to make C# fields private?

Generally, you should use fields only for variables that have private or protected accessibility. Data that your type exposes to client code should be provided through methods, properties, and indexers. By using these constructs for indirect access to internal fields, you can guard against invalid input values.

Should properties be private C#?

Generally, you should declare your fields as private, then use Properties to get and set their values. By this way you won't affect their values them directly. This is common case practice since having public members violates the Encapsulation concept in OOP.

Can properties be private?

Properties can be marked as public , private , protected , internal , protected internal , or private protected . These access modifiers define how users of the class can access the property.

Why do we use private in C#?

Private constructors are used to prevent creating instances of a class when there are no instance fields or methods, such as the Math class, or when a method is called to obtain an instance of a class.


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

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.


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.


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.


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.


The only one usage that I can think of

private bool IsPasswordSet 
{ 
     get
     {
       return !String.IsNullOrEmpty(_password);
     }
}

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.