For private class variables, which one is preferred?
If you have a property like int limit
, you want it to be:
int Limit {get; set;}
and use it inside the class, like so:
this.Limit
Is there a reason to use it or not use it? Maybe for performance reasons?
I wonder if this is a good practice.
Fields are normal variable members of a class. 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.
Fields are ordinary member variables or member instances of a class. Properties are an abstraction to get and set their values. Properties are also called accessors because they offer a way to change and retrieve a field if you expose a field in the class as private.
Using properties has a couple of distinct advantages: It allows for versioning if later you need extra logic. Adding logic to the getter or setter won't break existing code. It allows data binding to work properly (most data binding frameworks don't work with fields).
Properties have the primary advantage of allowing you to change the way data on an object is accessed without breaking it's public interface.
For a private member, I only make it a property when getting and/or setting the value should cause something else to occur, like:
private int Limit { get { EnsureValue(); return this._limit; } }
Otherwise, fields are fine. If you need to increase their accessibility, it's already a big enough change that making it a property at that point isn't a huge deal.
Edit: as Scott reminds us in the comments, side effects in properties can often cause more pain than anything else. Don't violate Single Responsibility and limit property logic to consistent, logical operations on the value only that must be done at the gate - such as lazy loading (as in the example above), transforming an internal structure into a publicly-useful format, etc.
The only real benefit an auto-property has over a field when the accessibility is private is that you can set a breakpoint on accesses and updates of the variable. If that is important to your scenario then definitely use an auto-property. Otherwise, given there is no substantial advantage, I choose to go with the simplest construct which is a field.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With