9

Possible Duplicate:
When are Getters and Setters Justified

Why exactly is having public and private accessors like these:

private string foo;

public string Foo
{
    get
    {
        return foo;
    }
    set
    {
        foo = value;
    }
}

considered better than just having public ones like this:

public string Foo;

The end result seems to be the same.

Tom Squires
  • 17,755
  • 11
  • 67
  • 88

4 Answers4

15
  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.
  1. Automatic properties make it easier to use public properties exclusively.
Glorfindel
  • 3,137
Robert Harvey
  • 199,517
1

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.

CaffGeek
  • 8,043
  • 4
    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
0

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

Martin
  • 1
-1

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)

Alb
  • 3,359