Skip to content

Commit e4f7bfb

Browse files
authored
Enable CA1821, CA1825-CA1834 (#33041)
* Enable CA1821, CA1825-CA1834 Contributes to #24055
1 parent b62acdf commit e4f7bfb

File tree

61 files changed

+196
-157
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

61 files changed

+196
-157
lines changed

.editorconfig

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,9 +91,40 @@ dotnet_diagnostic.CA1802.severity = warning
9191
# CA1805: Do not initialize unnecessarily
9292
dotnet_diagnostic.CA1805.severity = warning
9393

94+
# CA1823: Remove empty Finalizers
95+
dotnet_diagnostic.CA1821.severity = warning
96+
9497
# CA1823: Avoid unused private fields
9598
dotnet_diagnostic.CA1823.severity = warning
9699

100+
# CA1823: Avoid zero-length array allocations
101+
dotnet_diagnostic.CA1825.severity = warning
102+
103+
# CA1826: Do not use Enumerable methods on indexable collections. Instead use the collection directly
104+
dotnet_diagnostic.CA1826.severity = warning
105+
106+
# CA1827: Do not use Count() or LongCount() when Any() can be used
107+
dotnet_diagnostic.CA1827.severity = warning
108+
109+
# CA1828: Do not use CountAsync() or LongCountAsync() when AnyAsync() can be used
110+
dotnet_diagnostic.CA1828.severity = warning
111+
112+
# CA1829: Use Length/Count property instead of Count() when available
113+
dotnet_diagnostic.CA1829.severity = warning
114+
115+
# CA1830: Prefer strongly-typed Append and Insert method overloads on StringBuilder
116+
dotnet_diagnostic.CA1830.severity = warning
117+
118+
# CA1831: Use AsSpan or AsMemory instead of Range-based indexers when appropriate
119+
# CA1832: Use AsSpan or AsMemory instead of Range-based indexers when appropriate
120+
# CA1833: Use AsSpan or AsMemory instead of Range-based indexers when appropriate
121+
dotnet_diagnostic.CA1831.severity = warning
122+
dotnet_diagnostic.CA1832.severity = warning
123+
dotnet_diagnostic.CA1833.severity = warning
124+
125+
# CA1834: Consider using 'StringBuilder.Append(char)' when applicable
126+
dotnet_diagnostic.CA1834.severity = warning
127+
97128
# CA2012: Use ValueTask correctly
98129
dotnet_diagnostic.CA2012.severity = warning
99130

@@ -110,5 +141,15 @@ dotnet_diagnostic.CA1507.severity = suggestion
110141
dotnet_diagnostic.CA1802.severity = suggestion
111142
# CA1805: Do not initialize unnecessarily
112143
dotnet_diagnostic.CA1805.severity = suggestion
144+
# CA1823: Avoid zero-length array allocations
145+
dotnet_diagnostic.CA1825.severity = suggestion
146+
# CA1826: Do not use Enumerable methods on indexable collections. Instead use the collection directly
147+
dotnet_diagnostic.CA1826.severity = suggestion
148+
# CA1827: Do not use Count() or LongCount() when Any() can be used
149+
dotnet_diagnostic.CA1827.severity = suggestion
150+
# CA1829: Use Length/Count property instead of Count() when available
151+
dotnet_diagnostic.CA1829.severity = suggestion
152+
# CA1834: Consider using 'StringBuilder.Append(char)' when applicable
153+
dotnet_diagnostic.CA1834.severity = suggestion
113154
# CA2012: Use ValueTask correctly
114155
dotnet_diagnostic.CA2012.severity = suggestion

eng/tools/BaselineGenerator/Program.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ private async Task<int> Run()
168168
foreach (var group in reader.NuspecReader.GetDependencyGroups())
169169
{
170170
// Don't bother generating empty ItemGroup elements.
171-
if (group.Packages.Count() == 0)
171+
if (!group.Packages.Any())
172172
{
173173
continue;
174174
}

src/Components/Analyzers/test/Verifiers/DiagnosticVerifier.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ private void VerifyDiagnostics(string[] sources, string language, DiagnosticAnal
109109
/// <param name="expectedResults">Diagnostic Results that should have appeared in the code</param>
110110
private static void VerifyDiagnosticResults(IEnumerable<Diagnostic> actualResults, DiagnosticAnalyzer analyzer, params DiagnosticResult[] expectedResults)
111111
{
112-
int expectedCount = expectedResults.Count();
112+
int expectedCount = expectedResults.Length;
113113
int actualCount = actualResults.Count();
114114

115115
if (expectedCount != actualCount)

src/Components/WebAssembly/WebAssembly/src/Services/WebAssemblyConsoleLogger.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -119,9 +119,9 @@ private void CreateDefaultLogMessage(StringBuilder logBuilder, LogLevel logLevel
119119
logBuilder.Append(GetLogLevelString(logLevel));
120120
logBuilder.Append(_loglevelPadding);
121121
logBuilder.Append(logName);
122-
logBuilder.Append("[");
122+
logBuilder.Append('[');
123123
logBuilder.Append(eventId);
124-
logBuilder.Append("]");
124+
logBuilder.Append(']');
125125

126126
if (!string.IsNullOrEmpty(message))
127127
{

src/Components/WebView/WebView/src/QueryString.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -292,9 +292,9 @@ public override int GetHashCode()
292292

293293
private static void AppendKeyValuePair(StringBuilder builder, string key, string? value, bool first)
294294
{
295-
builder.Append(first ? "?" : "&");
295+
builder.Append(first ? '?' : '&');
296296
builder.Append(UrlEncoder.Default.Encode(key));
297-
builder.Append("=");
297+
builder.Append('=');
298298
if (!string.IsNullOrEmpty(value))
299299
{
300300
builder.Append(UrlEncoder.Default.Encode(value));

src/FileProviders/Embedded/src/Manifest/ManifestParser.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ private static string EnsureName(XElement element)
143143

144144
private static string EnsureText(XElement element)
145145
{
146-
if (element.Elements().Count() == 0 &&
146+
if (!element.Elements().Any() &&
147147
!element.IsEmpty &&
148148
element.Nodes().Count() == 1 &&
149149
element.FirstNode?.NodeType == XmlNodeType.Text)

src/Http/Headers/src/CookieHeaderValue.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ public override string ToString()
9494
var header = new StringBuilder();
9595

9696
header.Append(_name.AsSpan());
97-
header.Append("=");
97+
header.Append('=');
9898
header.Append(_value.AsSpan());
9999

100100
return header.ToString();

src/Http/Headers/src/SetCookieHeaderValue.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -329,7 +329,7 @@ private static void Append(ref Span<char> span, ReadOnlySpan<char> other)
329329
public void AppendToStringBuilder(StringBuilder builder)
330330
{
331331
builder.Append(_name.AsSpan());
332-
builder.Append("=");
332+
builder.Append('=');
333333
builder.Append(_value.AsSpan());
334334

335335
if (Expires.HasValue)
@@ -388,7 +388,7 @@ private static void AppendSegment(StringBuilder builder, StringSegment name, Str
388388
builder.Append(name.AsSpan());
389389
if (value != null)
390390
{
391-
builder.Append("=");
391+
builder.Append('=');
392392
builder.Append(value.AsSpan());
393393
}
394394
}

src/Http/Http.Abstractions/src/QueryString.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -286,9 +286,9 @@ public override int GetHashCode()
286286

287287
private static void AppendKeyValuePair(StringBuilder builder, string key, string? value, bool first)
288288
{
289-
builder.Append(first ? "?" : "&");
289+
builder.Append(first ? '?' : '&');
290290
builder.Append(UrlEncoder.Default.Encode(key));
291-
builder.Append("=");
291+
builder.Append('=');
292292
if (!string.IsNullOrEmpty(value))
293293
{
294294
builder.Append(UrlEncoder.Default.Encode(value));

src/Http/Routing/src/DefaultLinkGenerator.cs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -480,14 +480,14 @@ private static string FormatRouteValues(IReadOnlyDictionary<string, object> valu
480480

481481
foreach (var kvp in values.OrderBy(kvp => kvp.Key))
482482
{
483-
builder.Append("\"");
483+
builder.Append('"');
484484
builder.Append(kvp.Key);
485-
builder.Append("\"");
486-
builder.Append(":");
487-
builder.Append(" ");
488-
builder.Append("\"");
485+
builder.Append('"');
486+
builder.Append(':');
487+
builder.Append(' ');
488+
builder.Append('"');
489489
builder.Append(kvp.Value);
490-
builder.Append("\"");
490+
builder.Append('"');
491491
builder.Append(", ");
492492
}
493493

src/Http/Routing/src/Patterns/RoutePatternParameterPart.cs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -80,37 +80,37 @@ internal RoutePatternParameterPart(
8080
internal override string DebuggerToString()
8181
{
8282
var builder = new StringBuilder();
83-
builder.Append("{");
83+
builder.Append('{');
8484

8585
if (IsCatchAll)
8686
{
87-
builder.Append("*");
87+
builder.Append('*');
8888
if (!EncodeSlashes)
8989
{
90-
builder.Append("*");
90+
builder.Append('*');
9191
}
9292
}
9393

9494
builder.Append(Name);
9595

9696
foreach (var constraint in ParameterPolicies)
9797
{
98-
builder.Append(":");
98+
builder.Append(':');
9999
builder.Append(constraint.ParameterPolicy);
100100
}
101101

102102
if (Default != null)
103103
{
104-
builder.Append("=");
104+
builder.Append('=');
105105
builder.Append(Default);
106106
}
107107

108108
if (IsOptional)
109109
{
110-
builder.Append("?");
110+
builder.Append('?');
111111
}
112112

113-
builder.Append("}");
113+
builder.Append('}');
114114
return builder.ToString();
115115
}
116116
}

src/Http/Routing/src/Tree/LinkGenerationDecisionTree.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -248,7 +248,7 @@ private void FlattenTree(Stack<string> branchStack, StringBuilder sb, DecisionTr
248248
{
249249
matchesSb.Insert(0, branch);
250250
}
251-
sb.Append(matchesSb.ToString());
251+
sb.Append(matchesSb);
252252
sb.Append(" (Matches: ");
253253
sb.AppendJoin(", ", node.Matches.Select(m => m.Entry.RouteTemplate.TemplateText));
254254
sb.AppendLine(")");

src/Http/Routing/src/UriBuildingContext.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ public bool Accept(string? value, bool encodeSlashes)
111111
{
112112
if (_path.Length != 0)
113113
{
114-
_path.Append("/");
114+
_path.Append('/');
115115
}
116116
}
117117

@@ -124,7 +124,7 @@ public bool Accept(string? value, bool encodeSlashes)
124124
// This prevents the leading slash from PathString segments from being encoded.
125125
if (_path.Length == 0 && value.Length > 0 && value[0] == '/')
126126
{
127-
_path.Append("/");
127+
_path.Append('/');
128128
EncodeValue(value, 1, value.Length - 1, encodeSlashes);
129129
}
130130
else
@@ -305,7 +305,7 @@ internal void EncodeValue(string value, int start, int characterCount, bool enco
305305
while ((end = value.IndexOf('/', start, characterCount)) >= 0)
306306
{
307307
_urlEncoder.Encode(PathWriter, value, start, end - start);
308-
_path.Append("/");
308+
_path.Append('/');
309309

310310
start = end + 1;
311311
characterCount = length - start;

src/Http/Routing/tools/Swaggatherer/SwaggathererApplication.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -244,7 +244,7 @@ private static string GenerateRequestUrl(RouteTemplate template)
244244
// We don't yet handle complex segments
245245
var part = template.Segments[i].Parts[0];
246246

247-
url.Append("/");
247+
url.Append('/');
248248
url.Append(part.IsLiteral ? part.Text : GenerateParameterValue(part));
249249
}
250250

src/Identity/Extensions.Core/src/Base32.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ public static byte[] FromBase32(string input)
4646
input = input.TrimEnd('=').ToUpperInvariant();
4747
if (input.Length == 0)
4848
{
49-
return new byte[0];
49+
return Array.Empty<byte>();
5050
}
5151

5252
var output = new byte[input.Length * 5 / 8];

src/Identity/Specification.Tests/src/UserManagerSpecificationTests.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1826,7 +1826,7 @@ public async Task CanGetValidTwoFactor()
18261826
await manager.ConfirmEmailAsync(user, token);
18271827
factors = await manager.GetValidTwoFactorProvidersAsync(user);
18281828
Assert.NotNull(factors);
1829-
Assert.Equal(2, factors.Count());
1829+
Assert.Equal(2, factors.Count);
18301830
IdentityResultAssert.IsSuccess(await manager.SetEmailAsync(user, null));
18311831
factors = await manager.GetValidTwoFactorProvidersAsync(user);
18321832
Assert.NotNull(factors);
@@ -1835,7 +1835,7 @@ public async Task CanGetValidTwoFactor()
18351835
IdentityResultAssert.IsSuccess(await manager.ResetAuthenticatorKeyAsync(user));
18361836
factors = await manager.GetValidTwoFactorProvidersAsync(user);
18371837
Assert.NotNull(factors);
1838-
Assert.Equal(2, factors.Count());
1838+
Assert.Equal(2, factors.Count);
18391839
Assert.Equal("Authenticator", factors[1]);
18401840
}
18411841

src/Identity/UI/src/Areas/Identity/Pages/V4/Account/Manage/EnableAuthenticator.cshtml.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -182,12 +182,12 @@ private string FormatKey(string unformattedKey)
182182
int currentPosition = 0;
183183
while (currentPosition + 4 < unformattedKey.Length)
184184
{
185-
result.Append(unformattedKey.Substring(currentPosition, 4)).Append(" ");
185+
result.Append(unformattedKey.AsSpan(currentPosition, 4)).Append(' ');
186186
currentPosition += 4;
187187
}
188188
if (currentPosition < unformattedKey.Length)
189189
{
190-
result.Append(unformattedKey.Substring(currentPosition));
190+
result.Append(unformattedKey.AsSpan(currentPosition));
191191
}
192192

193193
return result.ToString().ToLowerInvariant();

src/Identity/test/InMemory.Test/InMemoryStore.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ namespace Microsoft.AspNetCore.Identity.InMemory
1414
public class InMemoryStore<TUser, TRole> :
1515
InMemoryUserStore<TUser>,
1616
IUserRoleStore<TUser>,
17-
IQueryableRoleStore<TRole>,
17+
IQueryableRoleStore<TRole>,
1818
IRoleClaimStore<TRole>
1919
where TRole : PocoRole
2020
where TUser : PocoUser
@@ -72,7 +72,7 @@ public class InMemoryStore<TUser, TRole> :
7272
{
7373
return Task.FromResult<IList<TUser>>(new List<TUser>());
7474
}
75-
return Task.FromResult<IList<TUser>>(Users.Where(u => (u.Roles.Where(x => x.RoleId == role.Id).Count() > 0)).Select(x => x).ToList());
75+
return Task.FromResult<IList<TUser>>(Users.Where(u => (u.Roles.Where(x => x.RoleId == role.Id).Any())).Select(x => x).ToList());
7676
}
7777

7878
private readonly Dictionary<string, TRole> _roles = new Dictionary<string, TRole>();

src/Middleware/CORS/src/Infrastructure/CorsPolicy.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -161,16 +161,16 @@ public override string ToString()
161161
builder.Append(SupportsCredentials);
162162
builder.Append(", Origins: {");
163163
builder.AppendJoin(",", Origins);
164-
builder.Append("}");
164+
builder.Append('}');
165165
builder.Append(", Methods: {");
166166
builder.AppendJoin(",", Methods);
167-
builder.Append("}");
167+
builder.Append('}');
168168
builder.Append(", Headers: {");
169169
builder.AppendJoin(",", Headers);
170-
builder.Append("}");
170+
builder.Append('}');
171171
builder.Append(", ExposedHeaders: {");
172172
builder.AppendJoin(",", ExposedHeaders);
173-
builder.Append("}");
173+
builder.Append('}');
174174
return builder.ToString();
175175
}
176176

src/Middleware/CORS/src/Infrastructure/CorsResult.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -93,13 +93,13 @@ public override string ToString()
9393
builder.Append(AllowedOrigin);
9494
builder.Append(", AllowExposedHeaders: {");
9595
builder.AppendJoin(",", AllowedExposedHeaders);
96-
builder.Append("}");
96+
builder.Append('}');
9797
builder.Append(", AllowHeaders: {");
9898
builder.AppendJoin(",", AllowedHeaders);
99-
builder.Append("}");
99+
builder.Append('}');
100100
builder.Append(", AllowMethods: {");
101101
builder.AppendJoin(",", AllowedMethods);
102-
builder.Append("}");
102+
builder.Append('}');
103103
return builder.ToString();
104104
}
105105
}

src/Middleware/Diagnostics.EntityFrameworkCore/src/DatabaseErrorPageMiddleware.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ public virtual async Task Invoke(HttpContext httpContext)
113113
var contextType = _localDiagnostic.Value!.ContextType;
114114
var details = await httpContext.GetContextDetailsAsync(contextType!, _logger);
115115

116-
if (details != null && (details.PendingModelChanges || details.PendingMigrations.Count() > 0))
116+
if (details != null && (details.PendingModelChanges || details.PendingMigrations.Any()))
117117
{
118118
var page = new DatabaseErrorPage
119119
{

0 commit comments

Comments
 (0)