Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 19 additions & 24 deletions _rules/1523.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,32 +4,27 @@ rule_category: maintainability
title: Favor object and collection initializers over separate statements
severity: 2
---
Instead of:
Use [Object and Collection Initializers](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers):

var startInfo = new ProcessStartInfo("myapp.exe");
startInfo.StandardOutput = Console.Output;
startInfo.UseShellExecute = true;
```csharp
var startInfo = new ProcessStartInfo("myapp.exe")
{
StandardOutput = Console.Output,
UseShellExecute = true
Comment on lines +12 to +13
};

var countries = new List();
countries.Add("Netherlands");
countries.Add("United States");
new List<string> countries = ["Netherlands", "United States"];

var countryLookupTable = new Dictionary<string, string>();
countryLookupTable.Add("NL", "Netherlands");
countryLookupTable.Add("US", "United States");
var countryLookupTable = new Dictionary<string, string>
{
["NL"] = "Netherlands",
["US"] = "United States"
};
```

Use [Object and Collection Initializers](http://msdn.microsoft.com/en-us/library/bb384062.aspx):
This also applies to arrays and the spread operator (C# 12+):

var startInfo = new ProcessStartInfo("myapp.exe")
{
StandardOutput = Console.Output,
UseShellExecute = true
};

var countries = new List { "Netherlands", "United States" };

var countryLookupTable = new Dictionary<string, string>
{
["NL"] = "Netherlands",
["US"] = "United States"
};
```csharp
string[] moreCountries = ["Belgium", "Germany"];
string[] allCountries = [..countries, ..moreCountries];
```