ReSharper 2024.3 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 the example below, GetCurrentData() can return a partly initialized Data if CreateNewData() does not use the object initializer, so ReSharper suggests rewriting the field-assignment statements with the object initializer:

public class DataHandler { private volatile Data _myData; public void CreateNewData() { _myData = new Data(); // warning _myData.Value1 = "Value1"; _myData.Value2 = "Value2"; } public Data GetCurrentData() { return _myData; } } public class Data { public string Value1 { get;set; } public string Value2 { get; set; } }
public class DataHandler { private volatile Data _myData; public void CreateNewData() { _myData = new Data { Value1 = "Value1", Value2 = "Value2" }; } public Data GetCurrentData() { return _myData; } } public class Data { public string Value1 { get;set; } public string Value2 { get; set; } }

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:

public void ViewCategories() { var categories = new Dictionary<int, string>(); categories.Add(1, "Books"); categories.Add(2, "Electronics"); foreach (var c in categories) { Console.WriteLine($"{c.Key}, " + $"{c.Value}"); } }
public void ViewCategories() { var categories = new Dictionary<int, string> {{1, "Books"}, {2, "Electronics"}}; foreach (var c in categories) { Console.WriteLine($"{c.Key}, " + $"{c.Value}"); } }

If you choose to disable this inspection, you can still convert selected assignments to the collection initializer with a context action Alt+Enter:

ReSharper: Converting assignments to object initializer
Last modified: 25 September 2024