20

Possible Duplicates:
What is the difference between a field and a property in C#
Should I use public properties and private fields or public fields for data?

What is the difference between:

public string varA;

and

public string varA { get; set; }
Community
  • 1
  • 1
Marin
  • 12,531
  • 17
  • 56
  • 80
  • It's been answered before here: [Why Properties Matter](http://csharpindepth.com/Articles/Chapter8/PropertiesMatter.aspx) – Roman Jul 01 '11 at 01:44

3 Answers3

19

The public property accessor gives you more flexibility in the future.

If you want to add validation to setting the value, you simply write a non-default setter. None of your other code would have to be modified.

There could also be reasons you'd want to replace the default getter with code. That can be a real pain with a public variable.

jimreed
  • 402
  • 4
  • 4
  • who writes code that depends on whether a visible name is a variable or a property? That's the only reason I can think of that this would matter, otherwise you can just change it and recompile. –  Jul 01 '11 at 01:11
  • 1
    @moz: What if your public variable was in a seperate binary? Your application would be using the variable.. when you change it to a property the variable disappears and you now have two generated functions. You'd have to recompile every binary which referenced it. – Rob Jul 01 '11 at 01:17
  • 3
    @Rob: so the property benefit applies primarily to libraries shipped as binaries only? For in-house code, not so much? –  Jul 01 '11 at 01:36
5

In addition to the other answers, you can also use a property to make the value read-only or even set-only:

public int Item { get; private set; } // read-only outside the class. Can only be set privately.

I have also run into situations where I later decide I want to proxy an object, or add AOP, which basically requires properties.

CodingWithSpike
  • 42,906
  • 18
  • 101
  • 138
1

Public property accesses fields and internal class code through exposed getter and setter methods. A public field acesses the field directly.

Using propertys offers the potential to provide a layer of abstraction and design (ability to make set accessor protected, private).

When a property is specified and no body present an underlying private field is created by the compiler that is used to store the value against. Essentially:

private int item = 0;
public int Item {
get { return item; }
set {item = value; }
}

In general I tend to use properties for public exposed variables and fields for private. I might consider using a field if that field was accessed many times and speed was a crucial design requirement.

dreza
  • 3,605
  • 7
  • 44
  • 55