diff --git a/_rules/1523.md b/_rules/1523.md index 3b03b58d..2cc1f475 100644 --- a/_rules/1523.md +++ b/_rules/1523.md @@ -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 +}; - var countries = new List(); - countries.Add("Netherlands"); - countries.Add("United States"); +new List countries = ["Netherlands", "United States"]; - var countryLookupTable = new Dictionary(); - countryLookupTable.Add("NL", "Netherlands"); - countryLookupTable.Add("US", "United States"); +var countryLookupTable = new Dictionary +{ + ["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 - { - ["NL"] = "Netherlands", - ["US"] = "United States" - }; +```csharp +string[] moreCountries = ["Belgium", "Germany"]; +string[] allCountries = [..countries, ..moreCountries]; +```