Skip to content

Object initializers C# 3.0readabilitycode reduction

Set object properties as part of the new statement.

Initializing a new object can require many values - either passed through constructors or by way of setting properties.

If the designer of the type does not want to provide every combination of constructor (this has its own set of problems) or make constructor args optional (also confusing) then you are forced to set each property one after the other.

C# 3.0 allows for a new syntax to set all the properties as part of the objects initialization, only returning the object once it is fully configured.

Code

C#
Droid droid = new Droid("C3-PO") {
    Type = DroidType.Protocol,
    Color = Colors.Gold,
    Languages = LanguageService.GetAll()
};
C#
Droid droid = new Droid("C3-PO");
droid.Type = DroidType.Protocol;
droid.Color = Colors.Gold;
droid.Languages = LanguageService.GetAll();

Notes

  • Constructors are still useful for providing common valid combinations
  • Classes must be mutable with public settable properties unless they uses Init-only setters C# 9.0

More information