Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fields vs Properties for private class variables [duplicate]

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.

like image 800
Joan Venge Avatar asked Oct 09 '09 18:10

Joan Venge


People also ask

Should I use fields or properties?

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.

What is difference between fields and properties?

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.

Why we use properties in C# instead of fields?

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).

What would be an advantage of calling a property instead of its underlying field when you have access to both?

Properties have the primary advantage of allowing you to change the way data on an object is accessed without breaking it's public interface.


2 Answers

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.

like image 175
Rex M Avatar answered Sep 20 '22 19:09

Rex M


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.

like image 39
JaredPar Avatar answered Sep 21 '22 19:09

JaredPar