Skip to content

Commit fd18915

Browse files
authored
Enable IDE0059 (#39434)
Contributes to #24055
1 parent 4d6fbeb commit fd18915

File tree

74 files changed

+141
-169
lines changed

Some content is hidden

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

74 files changed

+141
-169
lines changed

.editorconfig

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,12 @@ dotnet_diagnostic.CA2200.severity = warning
199199
# CA2208: Instantiate argument exceptions correctly
200200
dotnet_diagnostic.CA2208.severity = warning
201201

202+
# CA2245: Do not assign a property to itself
203+
dotnet_diagnostic.CA2245.severity = warning
204+
205+
# CA2246: Assigning symbol and its member in the same statement
206+
dotnet_diagnostic.CA2246.severity = warning
207+
202208
# IDE0005: Remove unnecessary usings
203209
dotnet_diagnostic.IDE0005.severity = warning
204210

@@ -224,6 +230,9 @@ dotnet_diagnostic.IDE0051.severity = warning
224230
# IDE0055: All formatting rules
225231
dotnet_diagnostic.IDE0055.severity = warning
226232

233+
# IDE0059: Unnecessary assignment to a value
234+
dotnet_diagnostic.IDE0059.severity = warning
235+
227236
# IDE0073: File header
228237
dotnet_diagnostic.IDE0073.severity = warning
229238
file_header_template = Licensed to the .NET Foundation under one or more agreements.\nThe .NET Foundation licenses this file to you under the MIT license.
@@ -274,6 +283,8 @@ dotnet_diagnostic.CA2012.severity = suggestion
274283
dotnet_diagnostic.IDE0044.severity = suggestion
275284
# IDE0051: Remove unused private members
276285
dotnet_diagnostic.IDE0051.severity = suggestion
286+
# IDE0059: Unnecessary assignment to a value
287+
dotnet_diagnostic.IDE0059.severity = suggestion
277288

278289
# CA2016: Forward the 'CancellationToken' parameter to methods that take one
279290
dotnet_diagnostic.CA2016.severity = suggestion

src/Azure/AzureAD/Authentication.AzureADB2C.UI/src/AzureAdB2COpenIDConnectEventHandlers.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ public Task OnRedirectToIdentityProvider(RedirectContext context)
4040

4141
private string BuildIssuerAddress(RedirectContext context, string defaultPolicy, string policy)
4242
{
43-
if (!_policyToIssuerAddress.TryGetValue(policy, out var issuerAddress))
43+
if (!_policyToIssuerAddress.TryGetValue(policy, out _))
4444
{
4545
_policyToIssuerAddress[policy] = context.ProtocolMessage.IssuerAddress.ToLowerInvariant()
4646
.Replace($"/{defaultPolicy.ToLowerInvariant()}/", $"/{policy.ToLowerInvariant()}/");

src/Caching/StackExchangeRedis/src/RedisCache.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ public void Set(string key, byte[] value, DistributedCacheEntryOptions options)
124124

125125
var absoluteExpiration = GetAbsoluteExpiration(creationTime, options);
126126

127-
var result = _cache.ScriptEvaluate(_setScript, new RedisKey[] { _instance + key },
127+
_cache.ScriptEvaluate(_setScript, new RedisKey[] { _instance + key },
128128
new RedisValue[]
129129
{
130130
absoluteExpiration?.Ticks ?? NotPresent,
@@ -430,9 +430,9 @@ private void Refresh(string key, DateTimeOffset? absExpr, TimeSpan? sldExpr)
430430
}
431431

432432
// Note Refresh has no effect if there is just an absolute expiration (or neither).
433-
TimeSpan? expr = null;
434433
if (sldExpr.HasValue)
435434
{
435+
TimeSpan? expr;
436436
if (absExpr.HasValue)
437437
{
438438
var relExpr = absExpr.Value - DateTimeOffset.Now;
@@ -457,9 +457,9 @@ private void Refresh(string key, DateTimeOffset? absExpr, TimeSpan? sldExpr)
457457
token.ThrowIfCancellationRequested();
458458

459459
// Note Refresh has no effect if there is just an absolute expiration (or neither).
460-
TimeSpan? expr = null;
461460
if (sldExpr.HasValue)
462461
{
462+
TimeSpan? expr;
463463
if (absExpr.HasValue)
464464
{
465465
var relExpr = absExpr.Value - DateTimeOffset.Now;

src/Components/WebView/Samples/PhotinoPlatform/src/PhotinoWebViewManager.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ public PhotinoWebViewManager(PhotinoWindow window, IServiceProvider provider, Di
4949
var hasFileExtension = url.LastIndexOf('.') > url.LastIndexOf('/');
5050

5151
if (url.StartsWith(AppBaseUri, StringComparison.Ordinal)
52-
&& TryGetResponseContent(url, !hasFileExtension, out var statusCode, out var statusMessage, out var content, out var headers))
52+
&& TryGetResponseContent(url, !hasFileExtension, out _, out _, out var content, out var headers))
5353
{
5454
headers.TryGetValue("Content-Type", out contentType);
5555
return content;

src/DataProtection/Cryptography.Internal/src/SafeHandles/SafeLibraryHandle.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,7 @@ public void ForbidUnload()
3939
const uint GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS = 0x00000004U;
4040
const uint GET_MODULE_HANDLE_EX_FLAG_PIN = 0x00000001U;
4141

42-
IntPtr unused;
43-
bool retVal = UnsafeNativeMethods.GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN, this, out unused);
42+
bool retVal = UnsafeNativeMethods.GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN, this, out _);
4443
if (!retVal)
4544
{
4645
UnsafeNativeMethods.ThrowExceptionForLastWin32Error();

src/DataProtection/DataProtection/src/ArraySegmentExtensions.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,6 @@ public static void Validate<T>(this ArraySegment<T> arraySegment)
2424
{
2525
// Since ArraySegment<T> is a struct, it can be improperly initialized or torn.
2626
// We call the ctor again to make sure the instance data is valid.
27-
var unused = new ArraySegment<T>(arraySegment.Array!, arraySegment.Offset, arraySegment.Count);
27+
_ = new ArraySegment<T>(arraySegment.Array!, arraySegment.Offset, arraySegment.Count);
2828
}
2929
}

src/DataProtection/DataProtection/src/Cng/DpapiSecretSerializerHelper.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -336,7 +336,6 @@ private static string GetRuleFromDpapiNGProtectedPayloadCore(byte* pbData, uint
336336

337337
NCryptDescriptorHandle descriptorHandle;
338338
LocalAllocHandle unprotectedDataHandle;
339-
uint cbUnprotectedData;
340339
var ntstatus = UnsafeNativeMethods.NCryptUnprotectSecret(
341340
phDescriptor: out descriptorHandle,
342341
dwFlags: NCRYPT_UNPROTECT_NO_DECRYPT,
@@ -345,7 +344,7 @@ private static string GetRuleFromDpapiNGProtectedPayloadCore(byte* pbData, uint
345344
pMemPara: IntPtr.Zero,
346345
hWnd: IntPtr.Zero,
347346
ppbData: out unprotectedDataHandle,
348-
pcbData: out cbUnprotectedData);
347+
pcbData: out _);
349348
UnsafeNativeMethods.ThrowExceptionForNCryptStatus(ntstatus);
350349
CryptoUtil.AssertSafeHandleIsValid(descriptorHandle);
351350

src/DataProtection/DataProtection/src/KeyManagement/KeyRingBasedDataProtector.cs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -187,11 +187,10 @@ public byte[] Unprotect(byte[] protectedData)
187187
}
188188

189189
// Argument checking will be done by the callee
190-
bool requiresMigration, wasRevoked; // unused
191190
return DangerousUnprotect(protectedData,
192191
ignoreRevocationErrors: false,
193-
requiresMigration: out requiresMigration,
194-
wasRevoked: out wasRevoked);
192+
requiresMigration: out _,
193+
wasRevoked: out _);
195194
}
196195

197196
private byte[] UnprotectCore(byte[] protectedData, bool allowOperationsOnRevokedKeys, out UnprotectStatus status)

src/DataProtection/DataProtection/src/KeyManagement/XmlKeyManager.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -489,7 +489,7 @@ void IInternalXmlKeyManager.RevokeSingleKey(Guid keyId, DateTimeOffset revocatio
489489

490490
internal KeyValuePair<IXmlRepository, IXmlEncryptor?> GetFallbackKeyRepositoryEncryptorPair()
491491
{
492-
IXmlRepository? repository = null;
492+
IXmlRepository? repository;
493493
IXmlEncryptor? encryptor = null;
494494

495495
// If we're running in Azure Web Sites, the key repository goes in the %HOME% directory.

src/DataProtection/Extensions/src/TimeLimitedDataProtector.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,6 @@ byte[] IDataProtector.Unprotect(byte[] protectedData)
142142
throw new ArgumentNullException(nameof(protectedData));
143143
}
144144

145-
DateTimeOffset expiration; // unused
146-
return Unprotect(protectedData, out expiration);
145+
return Unprotect(protectedData, out _);
147146
}
148147
}

src/Features/JsonPatch/src/Internal/ListAdapter.cs

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ public virtual bool TryGet(
6363
{
6464
var list = (IList)target;
6565

66-
if (!TryGetListTypeArgument(list, out var typeArgument, out errorMessage))
66+
if (!TryGetListTypeArgument(list, out _, out errorMessage))
6767
{
6868
value = null;
6969
return false;
@@ -96,7 +96,7 @@ public virtual bool TryRemove(
9696
{
9797
var list = (IList)target;
9898

99-
if (!TryGetListTypeArgument(list, out var typeArgument, out errorMessage))
99+
if (!TryGetListTypeArgument(list, out _, out errorMessage))
100100
{
101101
return false;
102102
}
@@ -208,8 +208,7 @@ public virtual bool TryTraverse(
208208
return false;
209209
}
210210

211-
var index = -1;
212-
if (!int.TryParse(segment, out index))
211+
if (!int.TryParse(segment, out var index))
213212
{
214213
value = null;
215214
errorMessage = Resources.FormatInvalidIndexValue(segment);
@@ -307,8 +306,7 @@ protected virtual bool TryGetPositionInfo(
307306
return true;
308307
}
309308

310-
var position = -1;
311-
if (int.TryParse(segment, out position))
309+
if (int.TryParse(segment, out var position))
312310
{
313311
if (position >= 0 && position < list.Count)
314312
{

src/FileProviders/Embedded/src/Manifest/ManifestDirectory.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -99,13 +99,13 @@ internal static void ValidateChildrenAndSetParent(ManifestEntry[] children, Mani
9999
private ManifestEntry[] CopyChildren()
100100
{
101101
var list = new List<ManifestEntry>(Children.Count);
102-
for (int i = 0; i < Children.Count; i++)
102+
for (var i = 0; i < Children.Count; i++)
103103
{
104104
var child = Children[i];
105105
switch (child)
106106
{
107-
case ManifestSinkDirectory s:
108-
case ManifestRootDirectory r:
107+
case ManifestSinkDirectory:
108+
case ManifestRootDirectory:
109109
throw new InvalidOperationException("Unexpected manifest node.");
110110
case ManifestDirectory d:
111111
var grandChildren = d.CopyChildren();

src/Http/Headers/src/BaseHeaderParser.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,8 @@ public sealed override bool TryParseValue(StringSegment value, ref int index, ou
2828
return SupportsMultipleValues;
2929
}
3030

31-
var separatorFound = false;
3231
var current = HeaderUtilities.GetNextNonEmptyOrWhitespaceIndex(value, index, SupportsMultipleValues,
33-
out separatorFound);
32+
out var separatorFound);
3433

3534
if (separatorFound && !SupportsMultipleValues)
3635
{

src/Http/Headers/src/CacheControlHeaderValue.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -728,12 +728,11 @@ private static bool TrySetOptionalTokenList(
728728
// We have a quoted string. Now verify that the string contains a list of valid tokens separated by ','.
729729
var current = 1; // skip the initial '"' character.
730730
var maxLength = valueString.Length - 1; // -1 because we don't want to parse the final '"'.
731-
var separatorFound = false;
732731
var originalValueCount = destination == null ? 0 : destination.Count;
733732
while (current < maxLength)
734733
{
735734
current = HeaderUtilities.GetNextNonEmptyOrWhitespaceIndex(valueString, current, true,
736-
out separatorFound);
735+
out var separatorFound);
737736

738737
if (current == maxLength)
739738
{

src/Http/Headers/src/ContentDispositionHeaderValue.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -435,7 +435,7 @@ private void SetName(StringSegment parameter, StringSegment value)
435435
}
436436
else
437437
{
438-
var processedValue = StringSegment.Empty;
438+
StringSegment processedValue;
439439
if (parameter.EndsWith("*", StringComparison.Ordinal))
440440
{
441441
processedValue = Encode5987(value);

src/Http/Headers/src/ContentRangeHeaderValue.cs

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -264,10 +264,7 @@ private static int GetContentRangeLength(StringSegment input, int startIndex, ou
264264

265265
// Read range values <from> and <to> in '<unit> <from>-<to>/<length>'
266266
var fromStartIndex = current;
267-
var fromLength = 0;
268-
var toStartIndex = 0;
269-
var toLength = 0;
270-
if (!TryGetRangeLength(input, ref current, out fromLength, out toStartIndex, out toLength))
267+
if (!TryGetRangeLength(input, ref current, out var fromLength, out var toStartIndex, out var toLength))
271268
{
272269
return 0;
273270
}
@@ -288,8 +285,7 @@ private static int GetContentRangeLength(StringSegment input, int startIndex, ou
288285

289286
// We may not have a length (e.g. 'bytes 1-2/*'). But if we do, parse the length now.
290287
var lengthStartIndex = current;
291-
var lengthLength = 0;
292-
if (!TryGetLengthLength(input, ref current, out lengthLength))
288+
if (!TryGetLengthLength(input, ref current, out var lengthLength))
293289
{
294290
return 0;
295291
}

src/Http/Headers/src/EntityTagHeaderValue.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -246,8 +246,7 @@ internal static int GetEntityTagLength(StringSegment input, int startIndex, out
246246
}
247247

248248
var tagStartIndex = current;
249-
var tagLength = 0;
250-
if (HttpRuleParser.GetQuotedStringLength(input, current, out tagLength) != HttpParseResult.Parsed)
249+
if (HttpRuleParser.GetQuotedStringLength(input, current, out var tagLength) != HttpParseResult.Parsed)
251250
{
252251
return 0;
253252
}

src/Http/Headers/src/HeaderUtilities.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -414,8 +414,6 @@ internal static bool TryParseQualityDouble(StringSegment input, int startIndex,
414414
var inputLength = input.Length;
415415
var current = startIndex;
416416
var limit = startIndex + _qualityValueMaxCharCount;
417-
418-
var intPart = 0;
419417
var decPart = 0;
420418
var decPow = 1;
421419

@@ -426,6 +424,7 @@ internal static bool TryParseQualityDouble(StringSegment input, int startIndex,
426424

427425
var ch = input[current];
428426

427+
int intPart;
429428
if (ch >= '0' && ch <= '1') // Only values between 0 and 1 are accepted, according to RFC
430429
{
431430
intPart = ch - '0';

src/Http/Headers/src/MediaTypeHeaderValue.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -579,7 +579,7 @@ private static int GetMediaTypeLength(StringSegment input, int startIndex, out M
579579

580580
var current = startIndex + mediaTypeLength;
581581
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
582-
MediaTypeHeaderValue? mediaTypeHeader = null;
582+
MediaTypeHeaderValue? mediaTypeHeader;
583583

584584
// If we're not done and we have a parameter delimiter, then we have a list of parameters.
585585
if ((current < input.Length) && (input[current] == ';'))

src/Http/Headers/src/RangeItemHeaderValue.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ internal static int GetRangeItemListLength(
115115
}
116116

117117
// Empty segments are allowed, so skip all delimiter-only segments (e.g. ", ,").
118-
var current = HeaderUtilities.GetNextNonEmptyOrWhitespaceIndex(input, startIndex, true, out var separatorFound);
118+
var current = HeaderUtilities.GetNextNonEmptyOrWhitespaceIndex(input, startIndex, true, separatorFound: out _);
119119
// It's OK if we didn't find leading separator characters. Ignore 'separatorFound'.
120120

121121
if (current == input.Length)
@@ -135,7 +135,7 @@ internal static int GetRangeItemListLength(
135135
rangeCollection!.Add(range!);
136136

137137
current = current + rangeLength;
138-
current = HeaderUtilities.GetNextNonEmptyOrWhitespaceIndex(input, current, true, out separatorFound);
138+
current = HeaderUtilities.GetNextNonEmptyOrWhitespaceIndex(input, current, true, out var separatorFound);
139139

140140
// If the string is not consumed, we must have a delimiter, otherwise the string is not a valid
141141
// range list.

src/Http/Http.Abstractions/src/HostString.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ public string Host
8080
{
8181
get
8282
{
83-
GetParts(_value, out var host, out var port);
83+
GetParts(_value, out var host, out _);
8484

8585
return host.ToString();
8686
}
@@ -94,7 +94,7 @@ public int? Port
9494
{
9595
get
9696
{
97-
GetParts(_value, out var host, out var port);
97+
GetParts(_value, out _, out var port);
9898

9999
if (!StringSegment.IsNullOrEmpty(port)
100100
&& int.TryParse(port.AsSpan(), NumberStyles.None, CultureInfo.InvariantCulture, out var p))

src/Http/Owin/src/OwinEnvironment.cs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -152,16 +152,14 @@ void IDictionary<string, object>.Add(string key, object value)
152152

153153
bool IDictionary<string, object>.ContainsKey(string key)
154154
{
155-
object value;
156-
return ((IDictionary<string, object>)this).TryGetValue(key, out value);
155+
return ((IDictionary<string, object>)this).TryGetValue(key, out _);
157156
}
158157

159158
ICollection<string> IDictionary<string, object>.Keys
160159
{
161160
get
162161
{
163-
object value;
164-
return _entries.Where(pair => pair.Value.TryGet(_context, out value))
162+
return _entries.Where(pair => pair.Value.TryGet(_context, out _))
165163
.Select(pair => pair.Key).Concat(_context.Items.Keys.Select(key => Convert.ToString(key, CultureInfo.InvariantCulture))).ToList();
166164
}
167165
}

src/Http/Owin/src/OwinFeatureCollection.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -304,8 +304,7 @@ bool IHttpWebSocketFeature.IsWebSocketRequest
304304
{
305305
get
306306
{
307-
object obj;
308-
return Environment.TryGetValue(OwinConstants.WebSocket.AcceptAlt, out obj);
307+
return Environment.TryGetValue(OwinConstants.WebSocket.AcceptAlt, out _);
309308
}
310309
}
311310

src/Http/Routing/src/Constraints/OptionalRouteConstraint.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ public bool Match(
4747
throw new ArgumentNullException(nameof(values));
4848
}
4949

50-
if (values.TryGetValue(routeKey, out var value))
50+
if (values.TryGetValue(routeKey, out _))
5151
{
5252
return InnerConstraint.Match(httpContext,
5353
route,

src/Http/Routing/src/Matching/DfaMatcherBuilder.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -447,9 +447,8 @@ private void AddRequiredLiteralValue(RouteEndpoint endpoint, List<DfaNode> nextP
447447

448448
private static void AddLiteralNode(bool includeLabel, List<DfaNode> nextParents, DfaNode parent, string literal)
449449
{
450-
DfaNode next = null;
451450
if (parent.Literals == null ||
452-
!parent.Literals.TryGetValue(literal, out next))
451+
!parent.Literals.TryGetValue(literal, out var next))
453452
{
454453
next = new DfaNode()
455454
{

src/Http/Routing/src/Matching/HttpMethodMatcherPolicy.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -291,11 +291,11 @@ public IReadOnlyList<PolicyNodeEdge> GetEdges(IReadOnlyList<Endpoint> endpoints)
291291
// We don't bother returning a 405 when the CORS preflight method doesn't exist.
292292
// The developer calling the API will see it as a CORS error, which is fine because
293293
// there isn't an endpoint to check for a CORS policy.
294-
if (!edges.TryGetValue(new EdgeKey(AnyMethod, false), out var matches))
294+
if (!edges.TryGetValue(new EdgeKey(AnyMethod, false), out _))
295295
{
296296
// Methods sorted for testability.
297297
var endpoint = CreateRejectionEndpoint(allHttpMethods);
298-
matches = new List<Endpoint>() { endpoint, };
298+
var matches = new List<Endpoint>() { endpoint, };
299299
edges[new EdgeKey(AnyMethod, false)] = matches;
300300
}
301301

0 commit comments

Comments
 (0)