Since version 3.0 of C# some features that make writing classes and common methods simpler and concise have introduced.
In this post we talk about automatic properties and object initializers.
The automatic properties (or auto-implemented properties) are nothing more than a compact syntax for writing the properties of a class. They allow you to write code like
that will be automatically translated by the compiler (hence the name automatic properties) in something like
Of course, nothing prevents you from writing the code in the second form, since for the compiler are equal.
But there is no doubt that the former is much more convenient.
The term object initializer means for writing compact set public properties of a class.
Quoting MSDN “Object initializers let you assign values to any accessible fields or properties of an object being created without having to call a constructor explicitly.”
Consider the following class Person
Before C# 3.0 advent to populate this class we have to write
but now thanks to object initializers, we can write the same thing in this way
setting property values when you instantiate the class.
If type Person define a sub-object as properties you can use object initializers to create even the sub-object.
Suppose that person defines also a property named address of type Address where Address definition is:
We could then instantiate Person as follow:
With this post I tried to give you an idea of the usefulness of these features and how code becomes more readable if written using them.
Automatic Properties and Object Initializers are two of the features of C# that I most appreciated when I started using this language, coming from Java world.
Perhaps at first glance don’t seem a great things, but when you begin to use them is difficult to go back.
My hope is that will soon be introduced also in Java.