Search code examples
c#propertiesc#-3.0fieldautomatic-properties

Difference between Property and Field in C# 3.0+


I realize that it seems to be a duplicate of What is the difference between a Field and a Property in C#? but my question has a slight difference (from my point of view):

Once I know that

  • I will not use my class with "techniques that only works on properties" and
  • I will not use validation code in the getter/setter.

Is there any difference (except the style/future development ones), like some type of control in setting the property?

Is there any additional difference between:

public string MyString { get; set; }

and

public string myString;

(I am aware that, that the first version requires C# 3.0 or above and that the compiler does create the private fields.)


Solution

  • Encapsulation.

    In the second instance you've just defined a variable, in the first, there is a getter / setter around the variable. So if you decide you want to validate the variable at a later date - it will be a lot easier.

    Plus they show up differently in Intellisense :)

    Edit: Update for OPs updated question - if you want to ignore the other suggestions here, the other reason is that it's simply not good OO design. And if you don't have a very good reason for doing it, always choose a property over a public variable / field.