ReSharper 2017.2 Help

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, ReSharper suggests using an object initializer.

In this example, ReSharper rewrites property-assignment statements by using an object initializer:

Suboptimal codeAfter the quick-fix
public void Program() { var p = new Point(); p.X = 100; p.Y = 200; /* ... */ }
public void Program() { var p = new Point { X = 100, Y = 200 }; /* ... */ }

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, ReSharper suggests using a collection initializer.

In the following, ReSharper replaces invocations of the Add method with a collection initializer:

Suboptimal codeAfter the quick-fix
public void ViewCategories() { Dictionary<int, string> categories = new Dictionary<int, string>(); categories.Add(1, "Books"); categories.Add(2, "Electronics"); foreach (var с in categories) { Console.WriteLine($"{c.Key}, {c.Value}"); } }
public void ViewCategories() { Dictionary<int, string> categories = new Dictionary<int, string> {{1, "Books"}, {2, "Electronics"}}; foreach (var с in categories) { Console.WriteLine($"{c.Key}, {c.Value}"); } }
Last modified: 14 December 2017

See Also