0

I cannot see what the differences between these two classes are:

class Class1
{
    public int a;
}

class Class2
{
    public int a { get; set; }
}

Why is the latter used when one can use the former?

slugster
  • 49,403
  • 14
  • 95
  • 145
wjmolina
  • 2,625
  • 2
  • 26
  • 35
  • Another similar question: [Public Fields versus Automatic Properties](http://stackoverflow.com/questions/1180860/public-fields-versus-automatic-properties) – Sam May 13 '13 at 21:59

2 Answers2

4

With a property, you can turn your "variable" into a getter/setter paradigm after the fact, and you'll break less code

properties also tend to play better with frameworks that make use of reflection

  • Although I agree with you and this is generally considered the real reason, IMO the first argument doesn't really makes sense. You could just as easily convert a field into a property. – Kenneth May 13 '13 at 22:02
  • @Kenneth if you do that, than [programs that use your library will have to re-compile](http://stackoverflow.com/questions/737290/why-prefer-properties-to-public-variables%5C) – Sam I am says Reinstate Monica May 13 '13 at 22:04
  • 1
    Also, a property can be declared in an interface, but a field can't. – Branko Dimitrijevic May 13 '13 at 22:08
  • You are right about that, I forgot about that one. However, in most situations, you either have control over the other apps (most I say) and even if you don't, if you make this change, you'll probably change other things as well, so a recompile will be necessary anyway. Anyway, I think we agree on the whole point. – Kenneth May 13 '13 at 22:08
0
public int a { get; set; }

define a property : http://msdn.microsoft.com/en-us/library/k69wcs43.aspx

Getters and Setters are implicits

flow
  • 4,828
  • 6
  • 26
  • 41