Click here to Skip to main content
15,888,301 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Just a few minutes ago i read - a quite often heard - hint in a c# book about the usage of properties and their private fields, where it says to avoid setting or getting private fields directly. So as we all know, in general it is more useful to access a property for error checking and changes may be done at one place, the property. If this is the only truth, in case of a lazy initiation, fields could, and therefore should be avoided generally, right?
But, as far as I know fields perform much faster than properties in c# (esp. in loops). I think there is an article about this topic here on codeproject (could not find it found it Fast and Less Fast Loops in C#[^]). At least for performance optimization fields should be used whenever possible, correct?
So what’s your opinion/ best practices?
Posted
Updated 23-Oct-11 8:02am
v2
Comments
Sander Rossel 23-Oct-11 9:02am    
Interesting question which has triggered some discussion as you can read. My 5 (I wish we had more questions like that, but don't get overconfident :laugh: ) :)

No. Properties and fields are very different animals.

Fields are used for internal class storage - if you make them accessible to the outside world, then you are fixing the design of your class, because you cannot change how your class works without considering the effects on the outside world. From a reliability / maintenance point of view this is a very bad idea.

Properties are in effect super-fields: they can be made publicly available to read, and privately to write (or vice versa), which further restricts what the outside world can do with your class data. They can also act as a field returning processed information which is not held separately.

They can be much, much more efficient than a similar field. For example, consider a class holding Students. One of the items you can retrieve about the student is a picture of them, in high resolution: 2048 by 2048, full colour. If you use an Image field, then you always have to retrieve the image when you create the Student instance, getting all record info from the database.

If you normally display these in a table, without the image, then that is incredibly wastefull of time, memory and database bandwidth. If you use a property, then you can retrieve the image only when it is asked for:
C#
private Image studentPhoto = null;
public Image StudentPhoto
   {
   get 
      {
      if (studentPhoto == null)
         {
         studentPhoto = GetImage();
         }
      return studentPhoto;
      }
   }
 
Share this answer
 
Comments
Sander Rossel 23-Oct-11 6:30am    
5ed! That is a smart way to optimize performance using Properties. And one reason to call your Properties instead of fields as much as possible :)
BillWoodruff 23-Oct-11 8:25am    
Good answer, and I like your example. When you wrote: "If you normally display these in a table, without the image ... that is incredibly wasteful" ... I have the feeling you meant "with the image." And that you are saying that using the Property access allows you to display the image on demand.
OriginalGriff 23-Oct-11 8:49am    
What I meant was "If you normally display these students in a table without the image, it is wasteful to use a field. A property allows you to load the image only when you actually need it." I should probably have phrased it better!
Abhinav S 23-Oct-11 8:51am    
Correct. 5.
Oliver Bleckmann 23-Oct-11 13:50pm    
Correct so far, but maybe I missed the point. I finally found the article here that says there is a performance difference http://www.codeproject.com/KB/cs/FastLessCSharpIteration.aspx. And yes, maybe the performance is a negligible factor, so it might be complaining on a high level. And, now that I know the correct english term, I was talking about consequently using backing-fields (thanks Bill, hope this is correct ;-) vs. the option to use lazy initiation of properties (set; get;) whenever possible.
If we use backing-fields for simple properties (means no further logic than set; get;), why should we do so? If there are no performance advantages and it is prohibited to access the private backing-fields within a class (I was not talking about using public fields). Why does a c# guru recommend using backing-fields principally/ consequently? I don’t see the advantage. On the contrary, we produce more and less maintainable code. Why not stick to cases we have to use backing-fields?
At this point I have to expose myself as a fan of the lazy approach. I consequently use properties because I was taught to do so, but from what I know now, it is time to call your conventions into question.
Interesting. Though I never heard of Properties causing performance issues (not Properties without further logic anyway) I guess there could be slight overhead. A Property in .NET is nothing more than a wrapper for a get and set Method. That means that in IL Properties are simply Methods like any other.
Of course you could put a lot of code in Properties (although this is usually not recommended) which could cause performance issues.
Personally I try to call my Properties as much as possible, since they could get some validation logic or call OnPropertyChanged. I just want to make sure I benefit from that code without having to go through my Class to change all the calls to my field into a call to my Property (unless I want to get around this for some reason).
On top of that the performance hit is so very minor that you should not even have to think about it. A few milliseconds for 10000000 read/writes[^]. Optimizing that would be pretty futile :)
Some more on this issue[^].
Self-Implemented Properties versus Public Fields[^] Is that the CP article you referred to?

By the way, speaking from experience, putting to much logic in Properties is a bad idea. I had a Property that made some calls to the database (actually I did a LINQ query on an ObjectContext). When binding to those Properties each value I altered caused my program to hang for about two seconds... Now THAT needed optimization, but not necessarily because they were Properties ;)

Edit:
See Bills comment below. He is completely right and corrects me on an incompleteness in my answer :)
 
Share this answer
 
v2
Comments
BillWoodruff 23-Oct-11 8:20am    
Just a small comment: I think to define a Property as a wrapper around a 'get and 'set without mentioning that there is a 'backing field' involved (once required to be explicit, and, in later instances of .NET, auto-generated for you, if you wish) ... is just a little short of complete. I would not consider 'Properties' to be "methods like any others," but to be a specific special purpose object within .NET with its own syntax ... even though they may be rendered as methods in IL. best, Bill
Sander Rossel 23-Oct-11 8:32am    
Yes, you are completely right. My answer was a bit oversimplified/blunt as you will. Although a backing field is not necessary per se. Consider this:
public string Name ( get {return "MyName";} )
No backing field involved (you cannot set _Name as you could with a getter and a setter) and the IL simply creates a Function called get_Name.
It is indeed still special since you are able to bind to it and all, so you are right that it is no Method like any other.
I have edited my answer slightly, I think you make some good points :)
BillWoodruff 23-Oct-11 8:48am    
That's a very good counter-example edge-case you cite: "public string Name ( get {return "MyName";} )", although, picky-picky, in this case you are not using a Property as a Property is intended to be used, but as a kind of strange 'field.' I liked and benefited from your answer, and appreciate your getting down to the IL level to inform your answer !
Sander Rossel 23-Oct-11 8:59am    
DevExpress (for example) uses Properties like that for their RepositoryItems. This way you can provide a name for a custom Repository, which is shown in the designer. That is the first example I can think of where I really had to use it.
Other examples are bloated Interfaces that have ReadOnly Properties that you do not wish to Implement. Especially Boolean ReadOnly Properties could simply return true or false.
I sometimes use it myself too. Say I have an Order Class which has a Property Product. Now I want to bind to the name of the Product of the Order. My Order would get a ReadOnly Property like this:
public string ProductName( get {return Product.Name;} )
Although I believe it is now also possible to bind to Order.Product.Name directly.
I encounter these cases on almost daily basis (I don't know what that says about my programming practices... :laugh: ) ;)
Glad you benefited from my answer. Your comments are also greatly appreciated!
Abhinav S 23-Oct-11 8:50am    
Worth a 5!
If you want to understand how this actually works out there is a couple of information sources on the net that provides valuable insights:
The blog for the code generation feature team working on the Common Language Runtime (CLR). [^] - these are the guys that that make it possible to generate native code for all binaries that run on top of the Microsoft .NET Framework.

CLR Optimizations In .NET Framework 3.5 SP1[^].

Simple properties will usually be inlined by the optimizer, so in the end there is no performance hit.

Best regards
Espen Harlinn
 
Share this answer
 
Comments
Abhinav S 23-Oct-11 8:50am    
My 5!
Espen Harlinn 23-Oct-11 17:25pm    
Thank you, Abhinav!
Sander Rossel 23-Oct-11 9:00am    
Interesting links, my 5.
Espen Harlinn 23-Oct-11 17:26pm    
Thank you, Naerling!
Oliver Bleckmann 23-Oct-11 13:58pm    
Inresting, if this is a prooven fact, there should be no diffrences in the testing loops ( see http://www.codeproject.com/KB/cs/FastLessCSharpIteration.aspx) best wishes, hans
You have three excellent answers here (all of which got my +5), but I will add an extended comment in regard to your statement that you read ... re Properties ... that you should "avoid setting or getting private fields directly."

I have the feeling that you were reading content in the context of the time when, in .NET, you had to explicitly define the private variable used by a Property. For example
private int _theInt;

public int TheInt
{
  get { return _theInt; }
  set { _theInt = value; }
}
In those times it was considered "bad form" to directly manipulate the private variable _theInt, and definitely 'foul play' to ever make that variable 'public.'

And, of course now, in 'modern C#,' you just write:
public int TheInt { get; set; }
And the compiler generates the (hidden) backing-field for you.

Opinions vary among OO-philes as to what extent processing should be done in the 'get and 'set of a Property. I personally do not like to see the 'get of a Property used as a substitute for a method call, but that's just my personal taste.

... edit ...

For example, here's a comment on computation within Properties in a recent thread on the C# discussion forum by Bob Janova, someone who I regard as one of the most thoughtful and articulate commentators we are lucky to have sharing expert knowledge on CP[^]:

"I rather agree with Davey on the use of properties here – when the values you want to read are uniquely specified by the current state of the object, and reading them has no side effects and does not require extensive processing*, a property is appropriate. As it happens, they are implemented as dynamic calculations, but logically those values are part of the state (you could set them when you modify the state, i.e. the diameter) and so querying them is querying the object state, which is what properties are for.

(*: This is one of those things that, in principle, shouldn't matter, but if you call a property getter you expect that to be almost free in terms of time, so it does. Also, as an aside, I once wrote an XML class which constructed the entire DOM tree when you assigned its Text property. I think that's probably abuse, although the rules for a property setter are more relaxed; setting a property can cause extensive recalculation and side effects such as data binding and screen refreshes.)"
 
Share this answer
 
v5
Comments
Abhinav S 23-Oct-11 8:51am    
This answer is worth a 5 as well.
Sander Rossel 23-Oct-11 9:04am    
Kind of what you already commented on my answer. And completely right too. My 5 :)
Oliver Bleckmann 23-Oct-11 14:00pm    
"backing-fields", thanks for the term, Bill. See my comments a both for clarification. Regards, Hans.
Espen Harlinn 23-Oct-11 17:30pm    
5'ed!
Sergey Alexandrovich Kryukov 23-Oct-11 19:07pm    
Important aspect added to previous answers, my 5.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900