C# features

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.

AUTOMATIC PROPERTIES

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

1
2
3
public String name {get; set;}

public DateTime birthday {get; set;}

that will be automatically translated by the compiler (hence the name automatic properties) in something like

1
2
3
4
5
6
7
8
9
10
11
12
private String _name;
private DateTime _birthday;

public String name {
  get { return _name; }
  set { _name = value; }
}

public String birthday {
  get { return _birthday; }
  set { _birthday = value; }
}

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.

OBJECT INITIALIZERS

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

1
2
3
4
public class Person {
    public String firstName { get; set; }
    public String lastName { get; set; }
}

Before C# 3.0 advent to populate this class we have to write

1
2
3
Person p= new Person();
p.firstName = "Claudio";
p.lastName = "Marai";

but now thanks to object initializers, we can write the same thing in this way

1
2
3
4
5
Person p= new Person()
{
    firstName = "Claudio",
    lastName = "Marai"
}

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:

1
2
3
4
public class Address {
    public String street { get; set; }
    public String city { get; set; }
}

We could then instantiate Person as follow:

1
2
3
4
5
6
7
8
9
10
Person p= new Person()
{
    firstName = "Claudio",
    lastName = "Marai",
    adress =  = new Address()
    {
        street = "via roma 12",
        city = "Verona"
    }
}

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.