Possible Duplicate:
When are Getters and Setters Justified

Why exactly is having public and private accessors like these:

private string foo;

public string Foo
        return foo;
        foo = value;

considered better than just having public ones like this:

public string Foo;

The end result seems to be the same.

  • In which language? In Python for instance it isn't. – user7043 Nov 18 '11 at 16:56
  • Im using c#. Edited to clarify – Tom Squires Nov 18 '11 at 16:57
  • Also see Getters and Setters in functional languages for the functional side of things. – user8 Nov 18 '11 at 17:31
  1. Properties do not have the same semantics as public variables:

    • Reflection works differently on variables vs. properties, so if you rely on reflection, it's easier to always use properties.
    • You can't databind against a variable.
    • Changing a variable to a property is a breaking change, if you decide you want to add validation or other logic later.
  2. Automatic properties make it easier to use public properties exclusively.

  • 1
    +1 "Changing a variable to a property is a breaking change" – CaffGeek Nov 18 '11 at 17:40

So you can protect the internal state of your classes.

You can set the property to have validation happen during set (some argue this should be done with a method)

You can hide variables that the user of the class should never see nor modify.

I don't care about your internal counter, or whatever other variables you need. And modifying certain variables in a class will completely break it.

  • 2
    The OP is referring to the common case of exposing a private field via a public property, without validation logic. He wonders, why not just make the field public? The property is not hiding anything, and no internal state is being protected. – Robert Harvey Nov 18 '11 at 17:29
  • Ah, I misunderstood. However, they ARE still different as you outlined in your reply. I've +1'd your response. – CaffGeek Nov 18 '11 at 17:39

In this example it's proabably not any advantage, but when systems get large and complex it can really come in useful to restrict a classes "access points".

  • For example you may have 2 private variables x , y but a single "access point" get getCoordinate – Martin Nov 18 '11 at 17:25
  • 2
    Then you need a Coordinate class ;) – Alb Nov 18 '11 at 17:32

One reason might be that you want to perform some validation or additional operations in the setter.

(Sorry mis-read this first, have edited my answer)

Not the answer you're looking for? Browse other questions tagged or ask your own question.