Object and Collection Initializers
Microsoft Docs / Object Initializers
Recommendation
Both object and collection initializers should be used, regardless of how many elements are being set.
Use:
Cat cat = new Cat
{
Age = 10,
Name = "Fluffy"
};
List<Cat> cats = new List<Cat>
{
new Cat{ Name = "Sylvester", Age=8 },
new Cat{ Name = "Whiskers", Age=2 },
new Cat{ Name = "Sasha", Age=14 }
};
Not
Cat cat = new Cat();
cat.Age = 10;
cat.Name = "Fluffy";
List<Cat> cats = new List<Cat>();
cats.Add(new Cat{ Name = "Sylvester", Age=8 });
cats.Add(new Cat{ Name = "Whiskers", Age=2 };
cats.Add(new Cat{ Name = "Sasha", Age=14 };
Justification
Both the Roslyn and .Net Core runtime teams agree that object and collection initializers should be used.
Arguments
✔ Prevents objects and collections from being accessed before all necessary elements added / set.
✔ Helps to ensure lines aren’t misplaced during refactoring.
✔ Eliminates repetitive identifier usage (e.g. cat.
and cats.Add
).
❌ 2 Braces-only lines must always be added, even for individual elements.
❌ Introduces indentation for code blocks.
Performance
Identical IL is generated when using either object or collection initializers.
Method | Mean | Error | StdDev |
---|---|---|---|
NoCollectionInitializer | 45.280 ns | 0.2104 ns | 0.1865 ns |
CollectionInitializer | 46.333 ns | 0.9622 ns | 0.9881 ns |
NoObjectInitializer | 6.052 ns | 0.1802 ns | 0.1686 ns |
ObjectInitializer | 5.554 ns | 0.1475 ns | 0.1380 ns |
Exceptions
Analyzers
ID | Name | Value |
---|---|---|
IDE0017 | dotnet_style_object_initializer | true:suggestion |
IDE0028 | dotnet_style_collection_initializer | true:suggestion |