C# features: auto-implemented properties

Properties in C# are used to hide implementation details to the outside. Fields (variables) should normally not be exposed (public).

It’s recommended to use properties instead, wich have get and set “accessors”. From the outside the properties are accessed like fields, but the compiler generates hidden methods.

man_vs_auto

For example 2 the compiler creates a hidden backing field which is used for the get and set accessors (C# 3). Without the boilerplate code it’s simple and clean.

In the VS editor you can type prop and use the template, press tab to jump between the type and name.

Properties can be initialized and it’s also possible to make them immutable (C#), which makes them thread-safe and predictable:

init_immutab

Output:
40
10

Conclusion
Properties are simple and powerful and should be used to expose data. The encapsulation has also positive side effects, like being able to log changes or to break in the get and set accessors with the debugger.

There are exceptions when accessing a field directly may be a better. For example extremely memory and performance optimized code (graphics, etc). But normally the minimal overhead is negligible.

Example project
Heres’s an example project that uses different types of properties (and it’s test project).