2

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

3
  • 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. Commented Feb 1, 2013 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 Commented Feb 1, 2013 at 17:15
  • OK. The comment from @Dustin Campbell on the selected answer here is the only relevant justification I've seen so far. Commented Feb 1, 2013 at 17:20

1 Answer 1

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; } } } 
Sign up to request clarification or add additional context in comments.

2 Comments

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.