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?

1

2 Answers 2

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

4
  • 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, 2013 at 22:02
  • @Kenneth if you do that, than programs that use your library will have to re-compile May 13, 2013 at 22:04
  • 1
    Also, a property can be declared in an interface, but a field can't. May 13, 2013 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, 2013 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

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