Only String2
is a property. String1
is just a public field, and it is recommended to not declare public fields.
You can simplify the declaration of simple properties like this by using automatic properties:
public string String { get; set; }
The main difference between fields and properties is that fields are accessed directly, whereas properties are read and written to via get
and set
methods. When you declare an automatic property as above, these get
and set
methods are automatically generated for you by the compiler, as well as a backing field to store the actual value.
You can also execute additional code in the get
and set
methods, which is often used for things like change notification and validation. You can set the get
and set
methods to different visibilities, such as { get; private set; }
, which is another thing that you don't have with fields.
Note that even if the usage of String1
and String2
in your example is the same, they are not binary compatible. That is, if you have a class that uses a field and you want to change that field to a property, you'll need to recompile all assemblies referencing that class. So it's best to go with (at least automatic) properties from the beginning.