Code Inspection: Use object or collection initializer when possible
Object and collection initializers offer more concise syntax. Besides, initializers are useful in multi-threading.
Object initializers are used to assign values to an object’s properties or fields at creation time without invoking the constructor. If you create an object and then right after that assign values to its properties, JetBrains Rider suggests using an object initializer.
In the example below,
GetCurrentData() can return a partly initialized
CreateNewData() does not use the object initializer, so JetBrains Rider suggests rewriting the field-assignment statements with the object initializer:
Collection initializers can be used if a collection class implements
IEnumerable or has an
Add method. If you create a collection and then immediately populate it with items, JetBrains Rider suggests using a collection initializer.
In the following, JetBrains Rider replaces invocations of the
Add method with a collection initializer:
If you choose to disable this inspection, you can still convert selected assignments to the collection initializer with a context action Alt+Enter: