Object Initializers
Object initializers are something that should have been in C# from day one, to put it on par with many other high-level languages. In comparison to C/C++, this gives C# aggregate initialization abilities. This ability is probably the most generally useful of the capabilities added to support LINQ; Microsoft added object initializers because LINQ statements are single statements—there's no way to initialize an object with the results of a query unless it can be done within one statement.
Recommendations:
- Prefer object initializers to one-property-per-statement object/element initialization.
Automatic Properties
Automatic properties are syntactic sugar for the tedious task of writing properties that wrap a single field for the backing store. In C# 2.0 you could implement a property like this:
private int age;
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
That's not too much work; but when you need to implement many properties it can get tedious in a hurry. In C# 3.0 you can create properties without having to declare a field for the backing store:
public int Age
{
get ;
set ;
}
The compiler automatically generates the field used for the backing store, but you don't have access to it; all access to this property must go through the property getter/setter.
Recommendations:
- Prefer automatic properties over public fields.
- Consider avoiding automatic properties when performance is an issue.
Although Microsoft created much of the new C# 3.0 syntax for specific reasons, developers can use the new capabilities anywhere they're applicable. These guidelines offer advice that can help you avoid some of the pitfalls you may encounter when using the new C# 3.0 syntax, but they should not be considered as cast in stone. In rare circumstances you may have clear reasons to violate these guidelines, but typically, they should help you better understand the new C# 3.0 syntax and write better C# code.