1

Possible Duplicate:
What is the difference between a field and a property in C#?
Difference between Property and Field in C# .NET 3.5+

Some time ago I inherited a C# web app wherein most class members that could be fields are defined as properties in one of the following two manners:

private Guid id;
public Guid Id
{
  get { return id; }
  set { id = value; }
}

public int someValue{ get; set; }

Namely, the getters/setters don't do anything other than ferry a value to/from a private field. In these cases, is there an advantage [or justification] for building these members out as properties vs. fields? And vice versa?

Would I be violating any unspoken rules or best practices by changing them to fields? Is there a notable performance difference -- for instance, incrementing someValue for a list of N objects one way or the other? (My current understanding is that field access is necessarily less complex [and efficient].)

Community
  • 1
  • 1
svidgen
  • 13,744
  • 4
  • 33
  • 58
  • As there isnt really one answer to this, it shouldn't really be a question here. But the thought would be that if you ever needed to do validation of some sort, the property allows that easily in the getter and setter. Where a field does not have that flexability. – jzworkman Feb 01 '13 at 17:15
  • There are a number of existing discussions on the merits of Properties vs Field - here is another one [Properties vs. Fields: Need help grasping the uses of Properties over Fields](http://stackoverflow.com/questions/3069901/properties-vs-fields-need-help-grasping-the-uses-of-properties-over-fields) – Justin Feb 01 '13 at 17:15
  • OK. The comment from @Dustin Campbell on the selected answer [here](http://stackoverflow.com/questions/653536/difference-between-property-and-field-in-c-sharp-net-3-5) is the only relevant justification I've seen so far. – svidgen Feb 01 '13 at 17:20

1 Answers1

0

It's mainly an OOP (Object Oriented Programming) notions: Encapsulation You can view a brief description here;

WikiPedia entry on Encapsulation

One of the possible uses is for example when trying to assign a value, to call a function to validate this new value. For example:

private Guid id;
public Guid Id
{
    get { return id; }
    set
    { 
        if (checkValue(value)==true)
        {
            id = value;
        } 
    }
}
Sorcerer86pt
  • 427
  • 9
  • 21
  • Yep. I understand what encapsulation *can* be used for. The question is, in cases where the encapsulation *isn't* doing anything special, isn't it just unnecessarily overhead (and code)? – svidgen Feb 01 '13 at 17:29
  • Encapsulation should only be used when you can predict that your class will be used/extended by other class and you need to protect your code . Normally this is about 80% of the times. – Sorcerer86pt Feb 06 '13 at 15:52