diff --git a/.editorconfig b/.editorconfig
index ade15f781f50..1af9937fd6fd 100644
--- a/.editorconfig
+++ b/.editorconfig
@@ -195,6 +195,7 @@ dotnet_diagnostic.CA2208.severity = warning
dotnet_diagnostic.IDE0035.severity = warning
# IDE0036: Order modifiers
+csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:suggestion
dotnet_diagnostic.IDE0036.severity = warning
# IDE0043: Format string contains invalid placeholder
@@ -204,7 +205,7 @@ dotnet_diagnostic.IDE0043.severity = warning
dotnet_diagnostic.IDE0044.severity = warning
# IDE0073: File header
-dotnet_diagnostic.IDE0073.severity = warning
+dotnet_diagnostic.IDE0073.severity = suggestion
file_header_template = Copyright (c) .NET Foundation. All rights reserved.\nLicensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
[**/{test,samples,perf}/**.{cs,vb}]
diff --git a/eng/targets/CSharp.Common.targets b/eng/targets/CSharp.Common.targets
index 4ed6574931c8..1599eea3a292 100644
--- a/eng/targets/CSharp.Common.targets
+++ b/eng/targets/CSharp.Common.targets
@@ -27,6 +27,9 @@
'$(ISBenchmarkProject)' == 'true' OR
'$(IsSampleProject)' == 'true' OR
'$(IsMicrobenchmarksProject)' == 'true'">$(NoWarn);CA1416
+
+
+ true
diff --git a/src/Analyzers/Analyzers/src/StartupAnalysis.cs b/src/Analyzers/Analyzers/src/StartupAnalysis.cs
index 9ddc03e04e69..85e9ca0659c5 100644
--- a/src/Analyzers/Analyzers/src/StartupAnalysis.cs
+++ b/src/Analyzers/Analyzers/src/StartupAnalysis.cs
@@ -8,7 +8,7 @@ namespace Microsoft.AspNetCore.Analyzers
{
internal class StartupAnalysis
{
- private ImmutableDictionary> _analysesByType;
+ private readonly ImmutableDictionary> _analysesByType;
public StartupAnalysis(
StartupSymbols startupSymbols,
diff --git a/src/Analyzers/Analyzers/src/StartupAnalyzer.Diagnostics.cs b/src/Analyzers/Analyzers/src/StartupAnalyzer.Diagnostics.cs
index cb2f50997ee1..59b1ec5b2ac8 100644
--- a/src/Analyzers/Analyzers/src/StartupAnalyzer.Diagnostics.cs
+++ b/src/Analyzers/Analyzers/src/StartupAnalyzer.Diagnostics.cs
@@ -27,7 +27,7 @@ static Diagnostics()
});
}
- internal readonly static DiagnosticDescriptor BuildServiceProviderShouldNotCalledInConfigureServicesMethod = new DiagnosticDescriptor(
+ internal static readonly DiagnosticDescriptor BuildServiceProviderShouldNotCalledInConfigureServicesMethod = new DiagnosticDescriptor(
"ASP0000",
"Do not call 'IServiceCollection.BuildServiceProvider' in 'ConfigureServices'",
"Calling 'BuildServiceProvider' from application code results in an additional copy of singleton services being created. Consider alternatives such as dependency injecting services as parameters to 'Configure'.",
@@ -36,7 +36,7 @@ static Diagnostics()
isEnabledByDefault: true,
helpLinkUri: "https://aka.ms/AA5k895");
- internal readonly static DiagnosticDescriptor UnsupportedUseMvcWithEndpointRouting = new DiagnosticDescriptor(
+ internal static readonly DiagnosticDescriptor UnsupportedUseMvcWithEndpointRouting = new DiagnosticDescriptor(
"MVC1005",
"Cannot use UseMvc with Endpoint Routing.",
"Using '{0}' to configure MVC is not supported while using Endpoint Routing. To continue using '{0}', please set 'MvcOptions.EnableEndpointRouting = false' inside '{1}'.",
@@ -45,7 +45,7 @@ static Diagnostics()
isEnabledByDefault: true,
helpLinkUri: "https://aka.ms/YJggeFn");
- internal readonly static DiagnosticDescriptor IncorrectlyConfiguredAuthorizationMiddleware = new DiagnosticDescriptor(
+ internal static readonly DiagnosticDescriptor IncorrectlyConfiguredAuthorizationMiddleware = new DiagnosticDescriptor(
"ASP0001",
"Authorization middleware is incorrectly configured.",
"The call to UseAuthorization should appear between app.UseRouting() and app.UseEndpoints(..) for authorization to be correctly evaluated.",
diff --git a/src/Azure/AzureAD/Authentication.AzureADB2C.UI/src/AzureAdB2COpenIDConnectEventHandlers.cs b/src/Azure/AzureAD/Authentication.AzureADB2C.UI/src/AzureAdB2COpenIDConnectEventHandlers.cs
index 5c9a758db7c7..4726aace65dd 100644
--- a/src/Azure/AzureAD/Authentication.AzureADB2C.UI/src/AzureAdB2COpenIDConnectEventHandlers.cs
+++ b/src/Azure/AzureAD/Authentication.AzureADB2C.UI/src/AzureAdB2COpenIDConnectEventHandlers.cs
@@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Authentication.AzureADB2C.UI
[Obsolete("This is obsolete and will be removed in a future version. Use Microsoft.Identity.Web instead. See https://aka.ms/ms-identity-web.")]
internal class AzureADB2COpenIDConnectEventHandlers
{
- private IDictionary _policyToIssuerAddress =
+ private readonly IDictionary _policyToIssuerAddress =
new Dictionary(StringComparer.OrdinalIgnoreCase);
public AzureADB2COpenIDConnectEventHandlers(string schemeName, AzureADB2COptions options)
diff --git a/src/Caching/SqlServer/src/PlatformHelper.cs b/src/Caching/SqlServer/src/PlatformHelper.cs
index 380302431497..3bac348a2f42 100644
--- a/src/Caching/SqlServer/src/PlatformHelper.cs
+++ b/src/Caching/SqlServer/src/PlatformHelper.cs
@@ -7,7 +7,7 @@ namespace Microsoft.Extensions.Caching.SqlServer
{
internal static class PlatformHelper
{
- private static Lazy _isMono = new Lazy(() => Type.GetType("Mono.Runtime") != null);
+ private static readonly Lazy _isMono = new Lazy(() => Type.GetType("Mono.Runtime") != null);
public static bool IsMono
{
@@ -17,4 +17,4 @@ public static bool IsMono
}
}
}
-}
\ No newline at end of file
+}
diff --git a/src/Components/Analyzers/test/TestFiles/ComponentInternalUsageDiagnosticsAnalyzerTest/UsesRendererTypesInDeclarations.cs b/src/Components/Analyzers/test/TestFiles/ComponentInternalUsageDiagnosticsAnalyzerTest/UsesRendererTypesInDeclarations.cs
index 0a0bd11b7bee..82dcfdc508a8 100644
--- a/src/Components/Analyzers/test/TestFiles/ComponentInternalUsageDiagnosticsAnalyzerTest/UsesRendererTypesInDeclarations.cs
+++ b/src/Components/Analyzers/test/TestFiles/ComponentInternalUsageDiagnosticsAnalyzerTest/UsesRendererTypesInDeclarations.cs
@@ -6,7 +6,7 @@ namespace Microsoft.AspNetCore.Components.Analyzers.Tests.TestFiles.ComponentInt
{
/*MMBaseClass*/class UsesRendererTypesInDeclarations : Renderer
{
- private Renderer /*MMField*/_field = null;
+ private readonly Renderer /*MMField*/_field = null;
public UsesRendererTypesInDeclarations()
/*MMInvocation*/: base(null, null)
diff --git a/src/Components/Components/src/CascadingParameterState.cs b/src/Components/Components/src/CascadingParameterState.cs
index c755bac06df6..712efc9e7976 100644
--- a/src/Components/Components/src/CascadingParameterState.cs
+++ b/src/Components/Components/src/CascadingParameterState.cs
@@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Components
{
internal readonly struct CascadingParameterState
{
- private readonly static ConcurrentDictionary _cachedInfos = new();
+ private static readonly ConcurrentDictionary _cachedInfos = new();
public string LocalValueName { get; }
public ICascadingValueComponent ValueSupplier { get; }
diff --git a/src/Components/Components/src/DynamicComponent.cs b/src/Components/Components/src/DynamicComponent.cs
index 43182500b0da..db83925d5dee 100644
--- a/src/Components/Components/src/DynamicComponent.cs
+++ b/src/Components/Components/src/DynamicComponent.cs
@@ -16,7 +16,7 @@ namespace Microsoft.AspNetCore.Components
public class DynamicComponent : IComponent
{
private RenderHandle _renderHandle;
- private RenderFragment _cachedRenderFragment;
+ private readonly RenderFragment _cachedRenderFragment;
///
/// Constructs an instance of .
diff --git a/src/Components/Components/src/Lifetime/ComponentApplicationLifetime.cs b/src/Components/Components/src/Lifetime/ComponentApplicationLifetime.cs
index 0aa85ceefbda..2d5464e3952f 100644
--- a/src/Components/Components/src/Lifetime/ComponentApplicationLifetime.cs
+++ b/src/Components/Components/src/Lifetime/ComponentApplicationLifetime.cs
@@ -16,7 +16,7 @@ namespace Microsoft.AspNetCore.Components.Lifetime
public class ComponentApplicationLifetime
{
private bool _stateIsPersisted;
- private List _pauseCallbacks = new();
+ private readonly List _pauseCallbacks = new();
private readonly Dictionary _currentState = new();
private readonly ILogger _logger;
diff --git a/src/Components/Components/src/RenderTree/EventArgsTypeCache.cs b/src/Components/Components/src/RenderTree/EventArgsTypeCache.cs
index 314545941589..ffb6379612c9 100644
--- a/src/Components/Components/src/RenderTree/EventArgsTypeCache.cs
+++ b/src/Components/Components/src/RenderTree/EventArgsTypeCache.cs
@@ -9,7 +9,7 @@ namespace Microsoft.AspNetCore.Components.RenderTree
{
internal static class EventArgsTypeCache
{
- private static ConcurrentDictionary Cache = new ConcurrentDictionary();
+ private static readonly ConcurrentDictionary Cache = new ConcurrentDictionary();
public static Type GetEventArgsType(MethodInfo methodInfo)
{
diff --git a/src/Components/Components/src/Rendering/RenderTreeBuilder.cs b/src/Components/Components/src/Rendering/RenderTreeBuilder.cs
index 65397a9a93f1..57441c85b696 100644
--- a/src/Components/Components/src/Rendering/RenderTreeBuilder.cs
+++ b/src/Components/Components/src/Rendering/RenderTreeBuilder.cs
@@ -20,9 +20,9 @@ namespace Microsoft.AspNetCore.Components.Rendering
///
public sealed class RenderTreeBuilder : IDisposable
{
- private readonly static object BoxedTrue = true;
- private readonly static object BoxedFalse = false;
- private readonly static string ComponentReferenceCaptureInvalidParentMessage = $"Component reference captures may only be added as children of frames of type {RenderTreeFrameType.Component}";
+ private static readonly object BoxedTrue = true;
+ private static readonly object BoxedFalse = false;
+ private static readonly string ComponentReferenceCaptureInvalidParentMessage = $"Component reference captures may only be added as children of frames of type {RenderTreeFrameType.Component}";
private readonly RenderTreeFrameArrayBuilder _entries = new RenderTreeFrameArrayBuilder();
private readonly Stack _openElementIndices = new Stack();
diff --git a/src/Components/Components/src/Rendering/SimplifiedStringHashComparer.cs b/src/Components/Components/src/Rendering/SimplifiedStringHashComparer.cs
index ecdb7cc8dd2f..03af8db6e129 100644
--- a/src/Components/Components/src/Rendering/SimplifiedStringHashComparer.cs
+++ b/src/Components/Components/src/Rendering/SimplifiedStringHashComparer.cs
@@ -18,7 +18,7 @@ namespace Microsoft.AspNetCore.Components.Rendering
///
internal class SimplifiedStringHashComparer : IEqualityComparer
{
- public readonly static SimplifiedStringHashComparer Instance = new SimplifiedStringHashComparer();
+ public static readonly SimplifiedStringHashComparer Instance = new SimplifiedStringHashComparer();
public bool Equals(string? x, string? y)
{
diff --git a/src/Components/Components/test/Lifetime/ComponentApplicationLifetimeTest.cs b/src/Components/Components/test/Lifetime/ComponentApplicationLifetimeTest.cs
index 6ae7bbc8bccd..9781eb13144e 100644
--- a/src/Components/Components/test/Lifetime/ComponentApplicationLifetimeTest.cs
+++ b/src/Components/Components/test/Lifetime/ComponentApplicationLifetimeTest.cs
@@ -204,7 +204,7 @@ public TestRenderer() : base(new ServiceCollection().BuildServiceProvider(), Nul
{
}
- private Dispatcher _dispatcher = Dispatcher.CreateDefault();
+ private readonly Dispatcher _dispatcher = Dispatcher.CreateDefault();
public override Dispatcher Dispatcher => _dispatcher;
diff --git a/src/Components/Components/test/RendererTest.cs b/src/Components/Components/test/RendererTest.cs
index 85185a710e84..f4604a5eaec4 100644
--- a/src/Components/Components/test/RendererTest.cs
+++ b/src/Components/Components/test/RendererTest.cs
@@ -4443,7 +4443,7 @@ protected override Task UpdateDisplayAsync(in RenderBatch renderBatch)
private class TestComponent : IComponent, IDisposable
{
private RenderHandle _renderHandle;
- private RenderFragment _renderFragment;
+ private readonly RenderFragment _renderFragment;
public TestComponent(RenderFragment renderFragment)
{
@@ -5211,7 +5211,7 @@ public Task SetParametersAsync(ParameterView parameters)
private class TestErrorBoundary : AutoRenderComponent, IErrorBoundary
{
- private TaskCompletionSource receivedErrorTaskCompletionSource = new();
+ private readonly TaskCompletionSource receivedErrorTaskCompletionSource = new();
public Exception ReceivedException { get; private set; }
public Task ReceivedErrorTask => receivedErrorTaskCompletionSource.Task;
diff --git a/src/Components/Components/test/Routing/RouteTableFactoryTests.cs b/src/Components/Components/test/Routing/RouteTableFactoryTests.cs
index 29b1fd1ddd8f..c5475b138499 100644
--- a/src/Components/Components/test/Routing/RouteTableFactoryTests.cs
+++ b/src/Components/Components/test/Routing/RouteTableFactoryTests.cs
@@ -1013,8 +1013,8 @@ public void SuppliesNullForUnusedHandlerParameters()
private class TestRouteTableBuilder
{
- IList<(string Template, Type Handler)> _routeTemplates = new List<(string, Type)>();
- Type _handler = typeof(object);
+ readonly IList<(string Template, Type Handler)> _routeTemplates = new List<(string, Type)>();
+ readonly Type _handler = typeof(object);
public TestRouteTableBuilder AddRoute(string template, Type handler = null)
{
diff --git a/src/Components/Forms/src/ValidationStateChangedEventArgs.cs b/src/Components/Forms/src/ValidationStateChangedEventArgs.cs
index fd8dbb8d69c8..51fe8a2aca92 100644
--- a/src/Components/Forms/src/ValidationStateChangedEventArgs.cs
+++ b/src/Components/Forms/src/ValidationStateChangedEventArgs.cs
@@ -13,7 +13,7 @@ public sealed class ValidationStateChangedEventArgs : EventArgs
///
/// Gets a shared empty instance of .
///
- public new static readonly ValidationStateChangedEventArgs Empty = new ValidationStateChangedEventArgs();
+ public static new readonly ValidationStateChangedEventArgs Empty = new ValidationStateChangedEventArgs();
///
/// Creates a new instance of
diff --git a/src/Components/Ignitor/src/NodeSerializer.cs b/src/Components/Ignitor/src/NodeSerializer.cs
index c405bdd394fd..bc47d24f6b4e 100644
--- a/src/Components/Ignitor/src/NodeSerializer.cs
+++ b/src/Components/Ignitor/src/NodeSerializer.cs
@@ -37,7 +37,7 @@ private class Serializer
private readonly TextWriter _writer;
private int _depth;
private bool _atStartOfLine;
- private HashSet _visited = new HashSet();
+ private readonly HashSet _visited = new HashSet();
public Serializer(TextWriter writer)
{
diff --git a/src/Components/Server/test/Circuits/RemoteRendererTest.cs b/src/Components/Server/test/Circuits/RemoteRendererTest.cs
index 063685d80f17..f6e0d06da88f 100644
--- a/src/Components/Server/test/Circuits/RemoteRendererTest.cs
+++ b/src/Components/Server/test/Circuits/RemoteRendererTest.cs
@@ -452,7 +452,7 @@ public async Task RenderComponentAsync(ParameterView initialParamete
private class TestComponent : IComponent, IHandleAfterRender
{
private RenderHandle _renderHandle;
- private RenderFragment _renderFragment = (builder) =>
+ private readonly RenderFragment _renderFragment = (builder) =>
{
builder.OpenElement(0, "my element");
builder.AddContent(1, "some text");
diff --git a/src/Components/Server/test/Circuits/RenderBatchWriterTest.cs b/src/Components/Server/test/Circuits/RenderBatchWriterTest.cs
index 7fdf9231676e..dff7ab271852 100644
--- a/src/Components/Server/test/Circuits/RenderBatchWriterTest.cs
+++ b/src/Components/Server/test/Circuits/RenderBatchWriterTest.cs
@@ -20,7 +20,7 @@ namespace Microsoft.AspNetCore.Components.Server
{
public class RenderBatchWriterTest
{
- static object NullStringMarker = new object();
+ static readonly object NullStringMarker = new object();
[Fact]
public void CanSerializeEmptyRenderBatch()
diff --git a/src/Components/Web/src/Forms/EditContextFieldClassExtensions.cs b/src/Components/Web/src/Forms/EditContextFieldClassExtensions.cs
index fb8bac72bbf2..34acb704e39b 100644
--- a/src/Components/Web/src/Forms/EditContextFieldClassExtensions.cs
+++ b/src/Components/Web/src/Forms/EditContextFieldClassExtensions.cs
@@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.Components.Forms
///
public static class EditContextFieldClassExtensions
{
- private readonly static object FieldCssClassProviderKey = new object();
+ private static readonly object FieldCssClassProviderKey = new object();
///
/// Gets a string that indicates the status of the specified field as a CSS class. This will include
diff --git a/src/Components/Web/src/Forms/FieldCssClassProvider.cs b/src/Components/Web/src/Forms/FieldCssClassProvider.cs
index dd56db64aa9f..ea77dbb9ba03 100644
--- a/src/Components/Web/src/Forms/FieldCssClassProvider.cs
+++ b/src/Components/Web/src/Forms/FieldCssClassProvider.cs
@@ -11,7 +11,7 @@ namespace Microsoft.AspNetCore.Components.Forms
///
public class FieldCssClassProvider
{
- internal readonly static FieldCssClassProvider Instance = new FieldCssClassProvider();
+ internal static readonly FieldCssClassProvider Instance = new FieldCssClassProvider();
///
/// Gets a string that indicates the status of the specified field as a CSS class.
diff --git a/src/Components/WebAssembly/Server/src/TargetPickerUi.cs b/src/Components/WebAssembly/Server/src/TargetPickerUi.cs
index 553b9905f869..de2c036b46fb 100644
--- a/src/Components/WebAssembly/Server/src/TargetPickerUi.cs
+++ b/src/Components/WebAssembly/Server/src/TargetPickerUi.cs
@@ -27,8 +27,8 @@ public class TargetPickerUi
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
- private string _browserHost;
- private string _debugProxyUrl;
+ private readonly string _browserHost;
+ private readonly string _debugProxyUrl;
///
/// Initialize a new instance of .
diff --git a/src/Components/WebAssembly/WebAssembly.Authentication/test/RemoteAuthenticatorCoreTests.cs b/src/Components/WebAssembly/WebAssembly.Authentication/test/RemoteAuthenticatorCoreTests.cs
index 43a16047122d..578f18b2e210 100644
--- a/src/Components/WebAssembly/WebAssembly.Authentication/test/RemoteAuthenticatorCoreTests.cs
+++ b/src/Components/WebAssembly/WebAssembly.Authentication/test/RemoteAuthenticatorCoreTests.cs
@@ -752,7 +752,7 @@ public TestRemoteAuthenticationService(
public Func, Task>> CompleteSignOutCallback { get; set; }
public Func> GetAuthenticatedUserCallback { get; set; }
- public async override Task GetAuthenticationStateAsync() => new AuthenticationState(await GetAuthenticatedUserCallback());
+ public override async Task GetAuthenticationStateAsync() => new AuthenticationState(await GetAuthenticatedUserCallback());
public override Task> CompleteSignInAsync(RemoteAuthenticationContext context) => CompleteSignInCallback(context);
diff --git a/src/Components/WebAssembly/WebAssembly/src/HotReload/WebAssemblyHotReload.cs b/src/Components/WebAssembly/WebAssembly/src/HotReload/WebAssemblyHotReload.cs
index 6fe29c04872a..2c2c0f527428 100644
--- a/src/Components/WebAssembly/WebAssembly/src/HotReload/WebAssemblyHotReload.cs
+++ b/src/Components/WebAssembly/WebAssembly/src/HotReload/WebAssemblyHotReload.cs
@@ -20,7 +20,7 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.HotReload
public static class WebAssemblyHotReload
{
private static HotReloadAgent? _hotReloadAgent;
- private static UpdateDelta[] _updateDeltas = new[]
+ private static readonly UpdateDelta[] _updateDeltas = new[]
{
new UpdateDelta(),
};
diff --git a/src/Components/WebAssembly/testassets/HostedInAspNet.Server/BootResourceRequestLog.cs b/src/Components/WebAssembly/testassets/HostedInAspNet.Server/BootResourceRequestLog.cs
index fea623aa4224..b0c8181c4319 100644
--- a/src/Components/WebAssembly/testassets/HostedInAspNet.Server/BootResourceRequestLog.cs
+++ b/src/Components/WebAssembly/testassets/HostedInAspNet.Server/BootResourceRequestLog.cs
@@ -9,7 +9,7 @@ namespace HostedInAspNet.Server
{
public class BootResourceRequestLog
{
- private ConcurrentBag _requestPaths = new ConcurrentBag();
+ private readonly ConcurrentBag _requestPaths = new ConcurrentBag();
public IReadOnlyCollection RequestPaths => _requestPaths;
diff --git a/src/Components/WebAssembly/testassets/Wasm.Authentication.Client/PreferencesUserFactory.cs b/src/Components/WebAssembly/testassets/Wasm.Authentication.Client/PreferencesUserFactory.cs
index f9971712fc2f..9fcf56a1ee8c 100644
--- a/src/Components/WebAssembly/testassets/Wasm.Authentication.Client/PreferencesUserFactory.cs
+++ b/src/Components/WebAssembly/testassets/Wasm.Authentication.Client/PreferencesUserFactory.cs
@@ -21,7 +21,7 @@ public PreferencesUserFactory(NavigationManager navigationManager, IAccessTokenP
_httpClient = new HttpClient { BaseAddress = new Uri(navigationManager.BaseUri) };
}
- public async override ValueTask CreateUserAsync(
+ public override async ValueTask CreateUserAsync(
OidcAccount account,
RemoteAuthenticationUserOptions options)
{
diff --git a/src/Components/WebView/Samples/PhotinoPlatform/src/PhotinoWebViewManager.cs b/src/Components/WebView/Samples/PhotinoPlatform/src/PhotinoWebViewManager.cs
index 6a4bf4814d9a..81474838ae45 100644
--- a/src/Components/WebView/Samples/PhotinoPlatform/src/PhotinoWebViewManager.cs
+++ b/src/Components/WebView/Samples/PhotinoPlatform/src/PhotinoWebViewManager.cs
@@ -19,11 +19,11 @@ internal class PhotinoWebViewManager : WebViewManager
// because webview2 won't let you do top-level navigation to such a URL.
// On Linux/Mac, we must use a custom scheme, because their webviews
// don't have a way to intercept http:// scheme requests.
- internal readonly static string BlazorAppScheme = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
+ internal static readonly string BlazorAppScheme = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? "http"
: "app";
- internal readonly static string AppBaseUri
+ internal static readonly string AppBaseUri
= $"{BlazorAppScheme}://0.0.0.0/";
public PhotinoWebViewManager(PhotinoWindow window, IServiceProvider provider, Dispatcher dispatcher, Uri appBaseUri, IFileProvider fileProvider, string hostPageRelativePath)
diff --git a/src/Components/WebView/WebView/src/StaticContentProvider.cs b/src/Components/WebView/WebView/src/StaticContentProvider.cs
index d1df73709379..f3c729c93067 100644
--- a/src/Components/WebView/WebView/src/StaticContentProvider.cs
+++ b/src/Components/WebView/WebView/src/StaticContentProvider.cs
@@ -15,7 +15,7 @@ internal class StaticContentProvider
private readonly Uri _appBaseUri;
private readonly string _hostPageRelativePath;
private static readonly FileExtensionContentTypeProvider ContentTypeProvider = new();
- private static ManifestEmbeddedFileProvider _manifestProvider =
+ private static readonly ManifestEmbeddedFileProvider _manifestProvider =
new ManifestEmbeddedFileProvider(typeof(StaticContentProvider).Assembly);
public StaticContentProvider(IFileProvider fileProvider, Uri appBaseUri, string hostPageRelativePath)
diff --git a/src/Components/WebView/WebView/test/Infrastructure/TestWebViewManager.cs b/src/Components/WebView/WebView/test/Infrastructure/TestWebViewManager.cs
index e88a24f7f015..71fafbf0118f 100644
--- a/src/Components/WebView/WebView/test/Infrastructure/TestWebViewManager.cs
+++ b/src/Components/WebView/WebView/test/Infrastructure/TestWebViewManager.cs
@@ -9,8 +9,8 @@ namespace Microsoft.AspNetCore.Components.WebView
{
public class TestWebViewManager : WebViewManager
{
- private static Uri AppBaseUri = new Uri("app://testhost/");
- private List _sentIpcMessages = new();
+ private static readonly Uri AppBaseUri = new Uri("app://testhost/");
+ private readonly List _sentIpcMessages = new();
public TestWebViewManager(IServiceProvider provider, IFileProvider fileProvider)
: base(provider, Dispatcher.CreateDefault(), AppBaseUri, fileProvider, hostPageRelativePath: "index.html")
diff --git a/src/Components/benchmarkapps/Wasm.Performance/Driver/Selenium.cs b/src/Components/benchmarkapps/Wasm.Performance/Driver/Selenium.cs
index 666e1a0ea7fc..0752937771df 100644
--- a/src/Components/benchmarkapps/Wasm.Performance/Driver/Selenium.cs
+++ b/src/Components/benchmarkapps/Wasm.Performance/Driver/Selenium.cs
@@ -14,9 +14,9 @@ namespace Wasm.Performance.Driver
class Selenium
{
const int SeleniumPort = 4444;
- static bool RunHeadlessBrowser = true;
+ const bool RunHeadlessBrowser = true;
- static bool PoolForBrowserLogs = true;
+ const bool PoolForBrowserLogs = true;
private static async ValueTask WaitForServerAsync(int port, CancellationToken cancellationToken)
{
diff --git a/src/Components/test/E2ETest/ServerExecutionTests/IgnitorTest.cs b/src/Components/test/E2ETest/ServerExecutionTests/IgnitorTest.cs
index af7d29cff743..bb1a943fbb64 100644
--- a/src/Components/test/E2ETest/ServerExecutionTests/IgnitorTest.cs
+++ b/src/Components/test/E2ETest/ServerExecutionTests/IgnitorTest.cs
@@ -83,7 +83,7 @@ protected virtual Task InitializeAsync()
return Task.CompletedTask;
}
- protected async virtual Task DisposeAsync()
+ protected virtual async Task DisposeAsync()
{
if (TestSink != null)
{
diff --git a/src/Components/test/E2ETest/ServerExecutionTests/InteropReliabilityTests.cs b/src/Components/test/E2ETest/ServerExecutionTests/InteropReliabilityTests.cs
index 984998a7886d..3e68c7ee3fe9 100644
--- a/src/Components/test/E2ETest/ServerExecutionTests/InteropReliabilityTests.cs
+++ b/src/Components/test/E2ETest/ServerExecutionTests/InteropReliabilityTests.cs
@@ -27,7 +27,7 @@ public InteropReliabilityTests(BasicTestAppServerSiteFixture serv
{
}
- protected async override Task InitializeAsync()
+ protected override async Task InitializeAsync()
{
var rootUri = ServerFixture.RootUri;
await ConnectAutomaticallyAndWait(new Uri(rootUri, "/subdir"));
diff --git a/src/Components/test/E2ETestMigration/Infrastructure/PlaywrightTestBase.cs b/src/Components/test/E2ETestMigration/Infrastructure/PlaywrightTestBase.cs
index 967c720f4485..106d6b5c9941 100644
--- a/src/Components/test/E2ETestMigration/Infrastructure/PlaywrightTestBase.cs
+++ b/src/Components/test/E2ETestMigration/Infrastructure/PlaywrightTestBase.cs
@@ -25,7 +25,7 @@ public class PlaywrightTestBase : LoggedTest, IAsyncLifetime
public PlaywrightTestBase(ITestOutputHelper output) : base(output) { }
- protected async override Task InitializeCoreAsync(TestContext context)
+ protected override async Task InitializeCoreAsync(TestContext context)
{
BrowserManager = await BrowserManager.CreateAsync(CreateConfiguration(), LoggerFactory);
BrowserContextInfo = new ContextInformation(LoggerFactory);
diff --git a/src/Components/test/testassets/BasicTestApp/PrependMessageLoggerProvider.cs b/src/Components/test/testassets/BasicTestApp/PrependMessageLoggerProvider.cs
index 35d4fd72bb98..d339cde7915e 100644
--- a/src/Components/test/testassets/BasicTestApp/PrependMessageLoggerProvider.cs
+++ b/src/Components/test/testassets/BasicTestApp/PrependMessageLoggerProvider.cs
@@ -13,8 +13,8 @@ namespace BasicTestApp
internal class PrependMessageLoggerProvider : ILoggerProvider
{
ILogger _logger;
- string _message;
- ILogger _defaultLogger;
+ readonly string _message;
+ readonly ILogger _defaultLogger;
private bool _disposed = false;
public PrependMessageLoggerProvider(string message, IJSRuntime runtime)
diff --git a/src/Components/test/testassets/TestServer/Controllers/UserController.cs b/src/Components/test/testassets/TestServer/Controllers/UserController.cs
index d6e289c7279a..3d4f81d90f3f 100644
--- a/src/Components/test/testassets/TestServer/Controllers/UserController.cs
+++ b/src/Components/test/testassets/TestServer/Controllers/UserController.cs
@@ -13,7 +13,7 @@ public class UserController : Controller
// to the client. It's up to the developer to choose what kind of authentication state
// data is needed on the client so it can display suitable options in the UI.
// In this class, we inform the client only about certain roles and certain other claims.
- static string[] ExposedRoles = new[] { "IrrelevantRole", "TestRole" };
+ static readonly string[] ExposedRoles = new[] { "IrrelevantRole", "TestRole" };
// GET api/user
[HttpGet]
diff --git a/src/Components/test/testassets/TestServer/ResourceRequestLog.cs b/src/Components/test/testassets/TestServer/ResourceRequestLog.cs
index 0af9e34afae9..c411cbb39264 100644
--- a/src/Components/test/testassets/TestServer/ResourceRequestLog.cs
+++ b/src/Components/test/testassets/TestServer/ResourceRequestLog.cs
@@ -8,7 +8,7 @@ namespace TestServer
{
public class ResourceRequestLog
{
- private List _requestPaths = new List();
+ private readonly List _requestPaths = new List();
public IReadOnlyCollection RequestPaths => _requestPaths;
diff --git a/src/DataProtection/Cryptography.Internal/src/Cng/BCryptUtil.cs b/src/DataProtection/Cryptography.Internal/src/Cng/BCryptUtil.cs
index 86c86c64a8ba..de4b6c4e17fe 100644
--- a/src/DataProtection/Cryptography.Internal/src/Cng/BCryptUtil.cs
+++ b/src/DataProtection/Cryptography.Internal/src/Cng/BCryptUtil.cs
@@ -8,7 +8,7 @@ namespace Microsoft.AspNetCore.Cryptography.Cng
///
/// Wraps utility BCRYPT APIs that don't work directly with handles.
///
- internal unsafe static class BCryptUtil
+ internal static unsafe class BCryptUtil
{
///
/// Fills a buffer with cryptographically secure random data.
diff --git a/src/DataProtection/Cryptography.Internal/src/CryptoUtil.cs b/src/DataProtection/Cryptography.Internal/src/CryptoUtil.cs
index b51699912e0d..2e2f07d61a63 100644
--- a/src/DataProtection/Cryptography.Internal/src/CryptoUtil.cs
+++ b/src/DataProtection/Cryptography.Internal/src/CryptoUtil.cs
@@ -13,7 +13,7 @@
namespace Microsoft.AspNetCore.Cryptography
{
- internal unsafe static class CryptoUtil
+ internal static unsafe class CryptoUtil
{
// This isn't a typical Debug.Assert; the check is always performed, even in retail builds.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
diff --git a/src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptAlgorithmHandle.cs b/src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptAlgorithmHandle.cs
index 95efc7026541..2377754cc069 100644
--- a/src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptAlgorithmHandle.cs
+++ b/src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptAlgorithmHandle.cs
@@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Cryptography.SafeHandles
///
/// Represents a handle to a BCrypt algorithm provider from which keys and hashes can be created.
///
- internal unsafe sealed class BCryptAlgorithmHandle : BCryptHandle
+ internal sealed unsafe class BCryptAlgorithmHandle : BCryptHandle
{
// Called by P/Invoke when returning SafeHandles
private BCryptAlgorithmHandle() { }
diff --git a/src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptHandle.cs b/src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptHandle.cs
index 66b2c1dbd474..2f04fe9f443a 100644
--- a/src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptHandle.cs
+++ b/src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptHandle.cs
@@ -6,7 +6,7 @@
namespace Microsoft.AspNetCore.Cryptography.SafeHandles
{
- internal unsafe abstract class BCryptHandle : SafeHandleZeroOrMinusOneIsInvalid
+ internal abstract unsafe class BCryptHandle : SafeHandleZeroOrMinusOneIsInvalid
{
protected BCryptHandle()
: base(ownsHandle: true)
diff --git a/src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptHashHandle.cs b/src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptHashHandle.cs
index f997f1576db4..2e5c76dafc2b 100644
--- a/src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptHashHandle.cs
+++ b/src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptHashHandle.cs
@@ -6,7 +6,7 @@
namespace Microsoft.AspNetCore.Cryptography.SafeHandles
{
- internal unsafe sealed class BCryptHashHandle : BCryptHandle
+ internal sealed unsafe class BCryptHashHandle : BCryptHandle
{
private BCryptAlgorithmHandle? _algProviderHandle;
diff --git a/src/DataProtection/Cryptography.Internal/src/SafeHandles/NCryptDescriptorHandle.cs b/src/DataProtection/Cryptography.Internal/src/SafeHandles/NCryptDescriptorHandle.cs
index 3a181cf06b99..bd6bc0bc9f6e 100644
--- a/src/DataProtection/Cryptography.Internal/src/SafeHandles/NCryptDescriptorHandle.cs
+++ b/src/DataProtection/Cryptography.Internal/src/SafeHandles/NCryptDescriptorHandle.cs
@@ -6,7 +6,7 @@
namespace Microsoft.AspNetCore.Cryptography.SafeHandles
{
- internal unsafe sealed class NCryptDescriptorHandle : SafeHandleZeroOrMinusOneIsInvalid
+ internal sealed unsafe class NCryptDescriptorHandle : SafeHandleZeroOrMinusOneIsInvalid
{
private NCryptDescriptorHandle()
: base(ownsHandle: true)
diff --git a/src/DataProtection/Cryptography.Internal/src/SafeHandles/SafeLibraryHandle.cs b/src/DataProtection/Cryptography.Internal/src/SafeHandles/SafeLibraryHandle.cs
index 8a38bb4e0eda..5f721e92b2bb 100644
--- a/src/DataProtection/Cryptography.Internal/src/SafeHandles/SafeLibraryHandle.cs
+++ b/src/DataProtection/Cryptography.Internal/src/SafeHandles/SafeLibraryHandle.cs
@@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Cryptography.SafeHandles
///
/// Represents a handle to a Windows module (DLL).
///
- internal unsafe sealed class SafeLibraryHandle : SafeHandleZeroOrMinusOneIsInvalid
+ internal sealed unsafe class SafeLibraryHandle : SafeHandleZeroOrMinusOneIsInvalid
{
// Called by P/Invoke when returning SafeHandles
private SafeLibraryHandle()
diff --git a/src/DataProtection/Cryptography.Internal/src/SafeHandles/SecureLocalAllocHandle.cs b/src/DataProtection/Cryptography.Internal/src/SafeHandles/SecureLocalAllocHandle.cs
index 3e1c7a79bab5..8baa92113bae 100644
--- a/src/DataProtection/Cryptography.Internal/src/SafeHandles/SecureLocalAllocHandle.cs
+++ b/src/DataProtection/Cryptography.Internal/src/SafeHandles/SecureLocalAllocHandle.cs
@@ -11,7 +11,7 @@ namespace Microsoft.AspNetCore.Cryptography.SafeHandles
/// Represents a handle returned by LocalAlloc.
/// The memory will be zeroed out before it's freed.
///
- internal unsafe sealed class SecureLocalAllocHandle : LocalAllocHandle
+ internal sealed unsafe class SecureLocalAllocHandle : LocalAllocHandle
{
private readonly IntPtr _cb;
diff --git a/src/DataProtection/Cryptography.Internal/src/UnsafeBufferUtil.cs b/src/DataProtection/Cryptography.Internal/src/UnsafeBufferUtil.cs
index c0f5a7959d92..e41c558fd6e5 100644
--- a/src/DataProtection/Cryptography.Internal/src/UnsafeBufferUtil.cs
+++ b/src/DataProtection/Cryptography.Internal/src/UnsafeBufferUtil.cs
@@ -9,7 +9,7 @@
namespace Microsoft.AspNetCore.Cryptography
{
- internal unsafe static class UnsafeBufferUtil
+ internal static unsafe class UnsafeBufferUtil
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#if NETSTANDARD2_0
diff --git a/src/DataProtection/Cryptography.Internal/src/UnsafeNativeMethods.cs b/src/DataProtection/Cryptography.Internal/src/UnsafeNativeMethods.cs
index 840ca22daeac..93b3884d0afa 100644
--- a/src/DataProtection/Cryptography.Internal/src/UnsafeNativeMethods.cs
+++ b/src/DataProtection/Cryptography.Internal/src/UnsafeNativeMethods.cs
@@ -16,7 +16,7 @@
namespace Microsoft.AspNetCore.Cryptography
{
[SuppressUnmanagedCodeSecurity]
- internal unsafe static class UnsafeNativeMethods
+ internal static unsafe class UnsafeNativeMethods
{
private const string BCRYPT_LIB = "bcrypt.dll";
private static readonly Lazy _lazyBCryptLibHandle = GetLazyLibraryHandle(BCRYPT_LIB);
diff --git a/src/DataProtection/Cryptography.KeyDerivation/src/PBKDF2/Win7Pbkdf2Provider.cs b/src/DataProtection/Cryptography.KeyDerivation/src/PBKDF2/Win7Pbkdf2Provider.cs
index 4c359b80f40c..492d4024e0e4 100644
--- a/src/DataProtection/Cryptography.KeyDerivation/src/PBKDF2/Win7Pbkdf2Provider.cs
+++ b/src/DataProtection/Cryptography.KeyDerivation/src/PBKDF2/Win7Pbkdf2Provider.cs
@@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.Cryptography.KeyDerivation.PBKDF2
///
/// A PBKDF2 provider which utilizes the Win7 API BCryptDeriveKeyPBKDF2.
///
- internal unsafe sealed class Win7Pbkdf2Provider : IPbkdf2Provider
+ internal sealed unsafe class Win7Pbkdf2Provider : IPbkdf2Provider
{
public byte[] DeriveKey(string password, byte[] salt, KeyDerivationPrf prf, int iterationCount, int numBytesRequested)
{
diff --git a/src/DataProtection/Cryptography.KeyDerivation/src/PBKDF2/Win8Pbkdf2Provider.cs b/src/DataProtection/Cryptography.KeyDerivation/src/PBKDF2/Win8Pbkdf2Provider.cs
index 296e85b7dd48..e03dfa359adb 100644
--- a/src/DataProtection/Cryptography.KeyDerivation/src/PBKDF2/Win8Pbkdf2Provider.cs
+++ b/src/DataProtection/Cryptography.KeyDerivation/src/PBKDF2/Win8Pbkdf2Provider.cs
@@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Cryptography.KeyDerivation.PBKDF2
///
/// A PBKDF2 provider which utilizes the Win8 API BCryptKeyDerivation.
///
- internal unsafe sealed class Win8Pbkdf2Provider : IPbkdf2Provider
+ internal sealed unsafe class Win8Pbkdf2Provider : IPbkdf2Provider
{
public byte[] DeriveKey(string password, byte[] salt, KeyDerivationPrf prf, int iterationCount, int numBytesRequested)
{
diff --git a/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/SecretExtensions.cs b/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/SecretExtensions.cs
index 4876247762d2..d08e2918ec0e 100644
--- a/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/SecretExtensions.cs
+++ b/src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/SecretExtensions.cs
@@ -6,7 +6,7 @@
namespace Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel
{
- internal unsafe static class SecretExtensions
+ internal static unsafe class SecretExtensions
{
///
/// Converts an to an <masterKey> element which is marked
diff --git a/src/DataProtection/DataProtection/src/BitHelpers.cs b/src/DataProtection/DataProtection/src/BitHelpers.cs
index 65e74150087b..092807d8d86a 100644
--- a/src/DataProtection/DataProtection/src/BitHelpers.cs
+++ b/src/DataProtection/DataProtection/src/BitHelpers.cs
@@ -6,7 +6,7 @@
namespace Microsoft.AspNetCore.DataProtection
{
- internal unsafe static class BitHelpers
+ internal static unsafe class BitHelpers
{
///
/// Writes an unsigned 32-bit value to a memory address, big-endian.
diff --git a/src/DataProtection/DataProtection/src/Cng/BCryptGenRandomImpl.cs b/src/DataProtection/DataProtection/src/Cng/BCryptGenRandomImpl.cs
index 5bdceabb6dd9..0852218e21a1 100644
--- a/src/DataProtection/DataProtection/src/Cng/BCryptGenRandomImpl.cs
+++ b/src/DataProtection/DataProtection/src/Cng/BCryptGenRandomImpl.cs
@@ -6,7 +6,7 @@
namespace Microsoft.AspNetCore.DataProtection.Cng
{
- internal unsafe sealed class BCryptGenRandomImpl : IBCryptGenRandom
+ internal sealed unsafe class BCryptGenRandomImpl : IBCryptGenRandom
{
public static readonly BCryptGenRandomImpl Instance = new BCryptGenRandomImpl();
diff --git a/src/DataProtection/DataProtection/src/Cng/CbcAuthenticatedEncryptor.cs b/src/DataProtection/DataProtection/src/Cng/CbcAuthenticatedEncryptor.cs
index 72166edf0b42..c102afd884d0 100644
--- a/src/DataProtection/DataProtection/src/Cng/CbcAuthenticatedEncryptor.cs
+++ b/src/DataProtection/DataProtection/src/Cng/CbcAuthenticatedEncryptor.cs
@@ -14,7 +14,7 @@ namespace Microsoft.AspNetCore.DataProtection.Cng
// An encryptor which does Encrypt(CBC) + HMAC using the Windows CNG (BCrypt*) APIs.
// The payloads produced by this encryptor should be compatible with the payloads
// produced by the managed Encrypt(CBC) + HMAC encryptor.
- internal unsafe sealed class CbcAuthenticatedEncryptor : CngAuthenticatedEncryptorBase
+ internal sealed unsafe class CbcAuthenticatedEncryptor : CngAuthenticatedEncryptorBase
{
// Even when IVs are chosen randomly, CBC is susceptible to IV collisions within a single
// key. For a 64-bit block cipher (like 3DES), we'd expect a collision after 2^32 block
diff --git a/src/DataProtection/DataProtection/src/Cng/CngGcmAuthenticatedEncryptor.cs b/src/DataProtection/DataProtection/src/Cng/CngGcmAuthenticatedEncryptor.cs
index 1566fabba4f4..af510ac00b64 100644
--- a/src/DataProtection/DataProtection/src/Cng/CngGcmAuthenticatedEncryptor.cs
+++ b/src/DataProtection/DataProtection/src/Cng/CngGcmAuthenticatedEncryptor.cs
@@ -20,7 +20,7 @@ namespace Microsoft.AspNetCore.DataProtection.Cng
// going to the IV. This means that we'll only hit the 2^-32 probability limit after 2^96 encryption
// operations, which will realistically never happen. (At the absurd rate of one encryption operation
// per nanosecond, it would still take 180 times the age of the universe to hit 2^96 operations.)
- internal unsafe sealed class CngGcmAuthenticatedEncryptor : CngAuthenticatedEncryptorBase
+ internal sealed unsafe class CngGcmAuthenticatedEncryptor : CngAuthenticatedEncryptorBase
{
// Having a key modifier ensures with overwhelming probability that no two encryption operations
// will ever derive the same (encryption subkey, MAC subkey) pair. This limits an attacker's
diff --git a/src/DataProtection/DataProtection/src/Cng/DpapiSecretSerializerHelper.cs b/src/DataProtection/DataProtection/src/Cng/DpapiSecretSerializerHelper.cs
index 2fa693851fe6..b59f812186c9 100644
--- a/src/DataProtection/DataProtection/src/Cng/DpapiSecretSerializerHelper.cs
+++ b/src/DataProtection/DataProtection/src/Cng/DpapiSecretSerializerHelper.cs
@@ -12,7 +12,7 @@
namespace Microsoft.AspNetCore.DataProtection.Cng
{
- internal unsafe static class DpapiSecretSerializerHelper
+ internal static unsafe class DpapiSecretSerializerHelper
{
// from ncrypt.h
private const uint NCRYPT_SILENT_FLAG = 0x00000040;
diff --git a/src/DataProtection/DataProtection/src/Cng/Internal/CngAuthenticatedEncryptorBase.cs b/src/DataProtection/DataProtection/src/Cng/Internal/CngAuthenticatedEncryptorBase.cs
index a6f9bef9eb25..9093b92aa25d 100644
--- a/src/DataProtection/DataProtection/src/Cng/Internal/CngAuthenticatedEncryptorBase.cs
+++ b/src/DataProtection/DataProtection/src/Cng/Internal/CngAuthenticatedEncryptorBase.cs
@@ -9,7 +9,7 @@ namespace Microsoft.AspNetCore.DataProtection.Cng.Internal
///
/// Base class used for all CNG-related authentication encryption operations.
///
- internal unsafe abstract class CngAuthenticatedEncryptorBase : IOptimizedAuthenticatedEncryptor, IDisposable
+ internal abstract unsafe class CngAuthenticatedEncryptorBase : IOptimizedAuthenticatedEncryptor, IDisposable
{
public byte[] Decrypt(ArraySegment ciphertext, ArraySegment additionalAuthenticatedData)
{
diff --git a/src/DataProtection/DataProtection/src/Internal/ContainerUtils.cs b/src/DataProtection/DataProtection/src/Internal/ContainerUtils.cs
index 6b366686a7a5..2b263bfef36e 100644
--- a/src/DataProtection/DataProtection/src/Internal/ContainerUtils.cs
+++ b/src/DataProtection/DataProtection/src/Internal/ContainerUtils.cs
@@ -11,7 +11,7 @@ namespace Microsoft.AspNetCore.DataProtection.Internal
{
internal static class ContainerUtils
{
- private static Lazy _isContainer = new Lazy(IsProcessRunningInContainer);
+ private static readonly Lazy _isContainer = new Lazy(IsProcessRunningInContainer);
private const string RunningInContainerVariableName = "DOTNET_RUNNING_IN_CONTAINER";
private const string DeprecatedRunningInContainerVariableName = "DOTNET_RUNNING_IN_CONTAINERS";
diff --git a/src/DataProtection/DataProtection/src/KeyManagement/KeyRingBasedDataProtectionProvider.cs b/src/DataProtection/DataProtection/src/KeyManagement/KeyRingBasedDataProtectionProvider.cs
index f7f785cc3bce..76c66e57f526 100644
--- a/src/DataProtection/DataProtection/src/KeyManagement/KeyRingBasedDataProtectionProvider.cs
+++ b/src/DataProtection/DataProtection/src/KeyManagement/KeyRingBasedDataProtectionProvider.cs
@@ -7,7 +7,7 @@
namespace Microsoft.AspNetCore.DataProtection.KeyManagement
{
- internal unsafe sealed class KeyRingBasedDataProtectionProvider : IDataProtectionProvider
+ internal sealed unsafe class KeyRingBasedDataProtectionProvider : IDataProtectionProvider
{
private readonly IKeyRingProvider _keyRingProvider;
private readonly ILogger _logger;
diff --git a/src/DataProtection/DataProtection/src/KeyManagement/KeyRingBasedDataProtector.cs b/src/DataProtection/DataProtection/src/KeyManagement/KeyRingBasedDataProtector.cs
index a5ce5e593a4a..2a9d64a82ab8 100644
--- a/src/DataProtection/DataProtection/src/KeyManagement/KeyRingBasedDataProtector.cs
+++ b/src/DataProtection/DataProtection/src/KeyManagement/KeyRingBasedDataProtector.cs
@@ -14,7 +14,7 @@
namespace Microsoft.AspNetCore.DataProtection.KeyManagement
{
- internal unsafe sealed class KeyRingBasedDataProtector : IDataProtector, IPersistedDataProtector
+ internal sealed unsafe class KeyRingBasedDataProtector : IDataProtector, IPersistedDataProtector
{
// This magic header identifies a v0 protected data blob. It's the high 28 bits of the SHA1 hash of
// "Microsoft.AspNet.DataProtection.KeyManagement.KeyRingBasedDataProtector" [US-ASCII], big-endian.
diff --git a/src/DataProtection/DataProtection/src/LoggingExtensions.cs b/src/DataProtection/DataProtection/src/LoggingExtensions.cs
index 909d05008dc3..15866671c11b 100644
--- a/src/DataProtection/DataProtection/src/LoggingExtensions.cs
+++ b/src/DataProtection/DataProtection/src/LoggingExtensions.cs
@@ -17,137 +17,137 @@ namespace Microsoft.Extensions.Logging
///
internal static class LoggingExtensions
{
- private static Action _usingFallbackKeyWithExpirationAsDefaultKey;
+ private static readonly Action _usingFallbackKeyWithExpirationAsDefaultKey;
- private static Action _usingKeyAsDefaultKey;
+ private static readonly Action _usingKeyAsDefaultKey;
- private static Action _openingCNGAlgorithmFromProviderWithHMAC;
+ private static readonly Action _openingCNGAlgorithmFromProviderWithHMAC;
- private static Action _openingCNGAlgorithmFromProviderWithChainingModeCBC;
+ private static readonly Action _openingCNGAlgorithmFromProviderWithChainingModeCBC;
- private static Action _performingUnprotectOperationToKeyWithPurposes;
+ private static readonly Action _performingUnprotectOperationToKeyWithPurposes;
- private static Action _keyWasNotFoundInTheKeyRingUnprotectOperationCannotProceed;
+ private static readonly Action _keyWasNotFoundInTheKeyRingUnprotectOperationCannotProceed;
- private static Action _keyWasRevokedCallerRequestedUnprotectOperationProceedRegardless;
+ private static readonly Action _keyWasRevokedCallerRequestedUnprotectOperationProceedRegardless;
- private static Action _keyWasRevokedUnprotectOperationCannotProceed;
+ private static readonly Action _keyWasRevokedUnprotectOperationCannotProceed;
- private static Action _openingCNGAlgorithmFromProviderWithChainingModeGCM;
+ private static readonly Action _openingCNGAlgorithmFromProviderWithChainingModeGCM;
- private static Action _usingManagedKeyedHashAlgorithm;
+ private static readonly Action _usingManagedKeyedHashAlgorithm;
- private static Action _usingManagedSymmetricAlgorithm;
+ private static readonly Action _usingManagedSymmetricAlgorithm;
- private static Action _keyIsIneligibleToBeTheDefaultKeyBecauseItsMethodFailed;
+ private static readonly Action _keyIsIneligibleToBeTheDefaultKeyBecauseItsMethodFailed;
- private static Action _consideringKeyWithExpirationDateAsDefaultKey;
+ private static readonly Action _consideringKeyWithExpirationDateAsDefaultKey;
- private static Action _keyIsNoLongerUnderConsiderationAsDefault;
+ private static readonly Action _keyIsNoLongerUnderConsiderationAsDefault;
- private static Action _unknownElementWithNameFoundInKeyringSkipping;
+ private static readonly Action _unknownElementWithNameFoundInKeyringSkipping;
- private static Action _markedKeyAsRevokedInTheKeyring;
+ private static readonly Action _markedKeyAsRevokedInTheKeyring;
- private static Action _triedToProcessRevocationOfKeyButNoSuchKeyWasFound;
+ private static readonly Action _triedToProcessRevocationOfKeyButNoSuchKeyWasFound;
- private static Action _foundKey;
+ private static readonly Action _foundKey;
- private static Action _foundRevocationOfAllKeysCreatedPriorTo;
+ private static readonly Action _foundRevocationOfAllKeysCreatedPriorTo;
- private static Action _foundRevocationOfKey;
+ private static readonly Action _foundRevocationOfKey;
- private static Action _exceptionWhileProcessingRevocationElement;
+ private static readonly Action _exceptionWhileProcessingRevocationElement;
- private static Action _revokingAllKeysAsOfForReason;
+ private static readonly Action _revokingAllKeysAsOfForReason;
- private static Action _keyCacheExpirationTokenTriggeredByOperation;
+ private static readonly Action _keyCacheExpirationTokenTriggeredByOperation;
- private static Action _anExceptionOccurredWhileProcessingTheKeyElement;
+ private static readonly Action _anExceptionOccurredWhileProcessingTheKeyElement;
- private static Action _anExceptionOccurredWhileProcessingTheKeyElementDebug;
+ private static readonly Action _anExceptionOccurredWhileProcessingTheKeyElementDebug;
- private static Action _encryptingToWindowsDPAPIForCurrentUserAccount;
+ private static readonly Action _encryptingToWindowsDPAPIForCurrentUserAccount;
- private static Action _encryptingToWindowsDPAPINGUsingProtectionDescriptorRule;
+ private static readonly Action _encryptingToWindowsDPAPINGUsingProtectionDescriptorRule;
- private static Action _anErrorOccurredWhileEncryptingToX509CertificateWithThumbprint;
+ private static readonly Action _anErrorOccurredWhileEncryptingToX509CertificateWithThumbprint;
- private static Action _encryptingToX509CertificateWithThumbprint;
+ private static readonly Action _encryptingToX509CertificateWithThumbprint;
- private static Action _exceptionOccurredWhileTryingToResolveCertificateWithThumbprint;
+ private static readonly Action _exceptionOccurredWhileTryingToResolveCertificateWithThumbprint;
- private static Action _performingProtectOperationToKeyWithPurposes;
+ private static readonly Action _performingProtectOperationToKeyWithPurposes;
- private static Action _creatingKey;
+ private static readonly Action _creatingKey;
- private static Action _descriptorDeserializerTypeForKeyIs;
+ private static readonly Action _descriptorDeserializerTypeForKeyIs;
- private static Action _keyEscrowSinkFoundWritingKeyToEscrow;
+ private static readonly Action _keyEscrowSinkFoundWritingKeyToEscrow;
- private static Action _noKeyEscrowSinkFoundNotWritingKeyToEscrow;
+ private static readonly Action _noKeyEscrowSinkFoundNotWritingKeyToEscrow;
- private static Action _noXMLEncryptorConfiguredKeyMayBePersistedToStorageInUnencryptedForm;
+ private static readonly Action _noXMLEncryptorConfiguredKeyMayBePersistedToStorageInUnencryptedForm;
- private static Action _revokingKeyForReason;
+ private static readonly Action _revokingKeyForReason;
- private static Action _readingDataFromFile;
+ private static readonly Action _readingDataFromFile;
- private static Action _nameIsNotSafeFileName;
+ private static readonly Action _nameIsNotSafeFileName;
- private static Action _writingDataToFile;
+ private static readonly Action _writingDataToFile;
- private static Action? _readingDataFromRegistryKeyValue;
+ private static readonly Action? _readingDataFromRegistryKeyValue;
- private static Action _nameIsNotSafeRegistryValueName;
+ private static readonly Action _nameIsNotSafeRegistryValueName;
- private static Action _decryptingSecretElementUsingWindowsDPAPING;
+ private static readonly Action _decryptingSecretElementUsingWindowsDPAPING;
- private static Action _exceptionOccurredTryingToDecryptElement;
+ private static readonly Action _exceptionOccurredTryingToDecryptElement;
- private static Action _encryptingUsingNullEncryptor;
+ private static readonly Action _encryptingUsingNullEncryptor;
- private static Action _usingEphemeralDataProtectionProvider;
+ private static readonly Action _usingEphemeralDataProtectionProvider;
- private static Action _existingCachedKeyRingIsExpiredRefreshing;
+ private static readonly Action _existingCachedKeyRingIsExpiredRefreshing;
- private static Action _errorOccurredWhileRefreshingKeyRing;
+ private static readonly Action _errorOccurredWhileRefreshingKeyRing;
- private static Action _errorOccurredWhileReadingKeyRing;
+ private static readonly Action _errorOccurredWhileReadingKeyRing;
- private static Action _keyRingDoesNotContainValidDefaultKey;
+ private static readonly Action _keyRingDoesNotContainValidDefaultKey;
- private static Action _usingInmemoryRepository;
+ private static readonly Action _usingInmemoryRepository;
- private static Action _decryptingSecretElementUsingWindowsDPAPI;
+ private static readonly Action _decryptingSecretElementUsingWindowsDPAPI;
- private static Action _defaultKeyExpirationImminentAndRepository;
+ private static readonly Action _defaultKeyExpirationImminentAndRepository;
- private static Action _repositoryContainsNoViableDefaultKey;
+ private static readonly Action _repositoryContainsNoViableDefaultKey;
- private static Action _errorOccurredWhileEncryptingToWindowsDPAPI;
+ private static readonly Action _errorOccurredWhileEncryptingToWindowsDPAPI;
- private static Action _encryptingToWindowsDPAPIForLocalMachineAccount;
+ private static readonly Action _encryptingToWindowsDPAPIForLocalMachineAccount;
- private static Action _errorOccurredWhileEncryptingToWindowsDPAPING;
+ private static readonly Action _errorOccurredWhileEncryptingToWindowsDPAPING;
- private static Action _policyResolutionStatesThatANewKeyShouldBeAddedToTheKeyRing;
+ private static readonly Action _policyResolutionStatesThatANewKeyShouldBeAddedToTheKeyRing;
- private static Action _keyRingWasLoadedOnStartup;
+ private static readonly Action _keyRingWasLoadedOnStartup;
- private static Action _keyRingFailedToLoadOnStartup;
+ private static readonly Action _keyRingFailedToLoadOnStartup;
- private static Action _usingEphemeralKeyRepository;
+ private static readonly Action _usingEphemeralKeyRepository;
- private static Action _usingRegistryAsKeyRepositoryWithDPAPI;
+ private static readonly Action _usingRegistryAsKeyRepositoryWithDPAPI;
- private static Action _usingProfileAsKeyRepository;
+ private static readonly Action _usingProfileAsKeyRepository;
- private static Action _usingProfileAsKeyRepositoryWithDPAPI;
+ private static readonly Action _usingProfileAsKeyRepositoryWithDPAPI;
- private static Action _usingAzureAsKeyRepository;
+ private static readonly Action _usingAzureAsKeyRepository;
- private static Action _usingEphemeralFileSystemLocationInContainer;
+ private static readonly Action _usingEphemeralFileSystemLocationInContainer;
static LoggingExtensions()
{
diff --git a/src/DataProtection/DataProtection/src/Managed/AesGcmAuthenticatedEncryptor.cs b/src/DataProtection/DataProtection/src/Managed/AesGcmAuthenticatedEncryptor.cs
index d883dfeaaaed..b4a9a92e94b0 100644
--- a/src/DataProtection/DataProtection/src/Managed/AesGcmAuthenticatedEncryptor.cs
+++ b/src/DataProtection/DataProtection/src/Managed/AesGcmAuthenticatedEncryptor.cs
@@ -13,7 +13,7 @@
namespace Microsoft.AspNetCore.DataProtection.Managed
{
// An encryptor that uses AesGcm to do encryption
- internal unsafe sealed class AesGcmAuthenticatedEncryptor : IOptimizedAuthenticatedEncryptor, IDisposable
+ internal sealed unsafe class AesGcmAuthenticatedEncryptor : IOptimizedAuthenticatedEncryptor, IDisposable
{
// Having a key modifier ensures with overwhelming probability that no two encryption operations
// will ever derive the same (encryption subkey, MAC subkey) pair. This limits an attacker's
diff --git a/src/DataProtection/DataProtection/src/Managed/ManagedAuthenticatedEncryptor.cs b/src/DataProtection/DataProtection/src/Managed/ManagedAuthenticatedEncryptor.cs
index c00ff06fcaf6..02d437940cda 100644
--- a/src/DataProtection/DataProtection/src/Managed/ManagedAuthenticatedEncryptor.cs
+++ b/src/DataProtection/DataProtection/src/Managed/ManagedAuthenticatedEncryptor.cs
@@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.DataProtection.Managed
// An encryptor which does Encrypt(CBC) + HMAC using SymmetricAlgorithm and HashAlgorithm.
// The payloads produced by this encryptor should be compatible with the payloads
// produced by the CNG-based Encrypt(CBC) + HMAC authenticated encryptor.
- internal unsafe sealed class ManagedAuthenticatedEncryptor : IAuthenticatedEncryptor, IDisposable
+ internal sealed unsafe class ManagedAuthenticatedEncryptor : IAuthenticatedEncryptor, IDisposable
{
// Even when IVs are chosen randomly, CBC is susceptible to IV collisions within a single
// key. For a 64-bit block cipher (like 3DES), we'd expect a collision after 2^32 block
diff --git a/src/DataProtection/DataProtection/src/Managed/ManagedGenRandomImpl.cs b/src/DataProtection/DataProtection/src/Managed/ManagedGenRandomImpl.cs
index c94c2f21f51a..34712759becc 100644
--- a/src/DataProtection/DataProtection/src/Managed/ManagedGenRandomImpl.cs
+++ b/src/DataProtection/DataProtection/src/Managed/ManagedGenRandomImpl.cs
@@ -6,7 +6,7 @@
namespace Microsoft.AspNetCore.DataProtection.Managed
{
- internal unsafe sealed class ManagedGenRandomImpl : IManagedGenRandom
+ internal sealed unsafe class ManagedGenRandomImpl : IManagedGenRandom
{
#if NETSTANDARD2_0 || NET461
private static readonly RandomNumberGenerator _rng = RandomNumberGenerator.Create();
diff --git a/src/DataProtection/DataProtection/src/MemoryProtection.cs b/src/DataProtection/DataProtection/src/MemoryProtection.cs
index be87e3cde512..cb3f08853681 100644
--- a/src/DataProtection/DataProtection/src/MemoryProtection.cs
+++ b/src/DataProtection/DataProtection/src/MemoryProtection.cs
@@ -10,7 +10,7 @@ namespace Microsoft.AspNetCore.DataProtection
///
/// Wrappers around CryptProtectMemory / CryptUnprotectMemory.
///
- internal unsafe static class MemoryProtection
+ internal static unsafe class MemoryProtection
{
// from dpapi.h
private const uint CRYPTPROTECTMEMORY_SAME_PROCESS = 0x00;
diff --git a/src/DataProtection/DataProtection/src/SP800_108/SP800_108_CTR_HMACSHA512Extensions.cs b/src/DataProtection/DataProtection/src/SP800_108/SP800_108_CTR_HMACSHA512Extensions.cs
index 900ff8e658cb..d4fd290116ea 100644
--- a/src/DataProtection/DataProtection/src/SP800_108/SP800_108_CTR_HMACSHA512Extensions.cs
+++ b/src/DataProtection/DataProtection/src/SP800_108/SP800_108_CTR_HMACSHA512Extensions.cs
@@ -6,7 +6,7 @@
namespace Microsoft.AspNetCore.DataProtection.SP800_108
{
- internal unsafe static class SP800_108_CTR_HMACSHA512Extensions
+ internal static unsafe class SP800_108_CTR_HMACSHA512Extensions
{
public static void DeriveKeyWithContextHeader(this ISP800_108_CTR_HMACSHA512Provider provider, byte* pbLabel, uint cbLabel, byte[] contextHeader, byte* pbContext, uint cbContext, byte* pbDerivedKey, uint cbDerivedKey)
{
diff --git a/src/DataProtection/DataProtection/src/SP800_108/SP800_108_CTR_HMACSHA512Util.cs b/src/DataProtection/DataProtection/src/SP800_108/SP800_108_CTR_HMACSHA512Util.cs
index c28af6f0a335..41205af1c4b4 100644
--- a/src/DataProtection/DataProtection/src/SP800_108/SP800_108_CTR_HMACSHA512Util.cs
+++ b/src/DataProtection/DataProtection/src/SP800_108/SP800_108_CTR_HMACSHA512Util.cs
@@ -14,7 +14,7 @@ namespace Microsoft.AspNetCore.DataProtection.SP800_108
///
/// More info at http://csrc.nist.gov/publications/nistpubs/800-108/sp800-108.pdf, Sec. 5.1.
///
- internal unsafe static class SP800_108_CTR_HMACSHA512Util
+ internal static unsafe class SP800_108_CTR_HMACSHA512Util
{
// Creates a provider with an empty key.
public static ISP800_108_CTR_HMACSHA512Provider CreateEmptyProvider()
diff --git a/src/DataProtection/DataProtection/src/SP800_108/Win7SP800_108_CTR_HMACSHA512Provider.cs b/src/DataProtection/DataProtection/src/SP800_108/Win7SP800_108_CTR_HMACSHA512Provider.cs
index a2143ff8720d..3cbf45cbd9f8 100644
--- a/src/DataProtection/DataProtection/src/SP800_108/Win7SP800_108_CTR_HMACSHA512Provider.cs
+++ b/src/DataProtection/DataProtection/src/SP800_108/Win7SP800_108_CTR_HMACSHA512Provider.cs
@@ -8,7 +8,7 @@
namespace Microsoft.AspNetCore.DataProtection.SP800_108
{
- internal unsafe sealed class Win7SP800_108_CTR_HMACSHA512Provider : ISP800_108_CTR_HMACSHA512Provider
+ internal sealed unsafe class Win7SP800_108_CTR_HMACSHA512Provider : ISP800_108_CTR_HMACSHA512Provider
{
private readonly BCryptHashHandle _hashHandle;
diff --git a/src/DataProtection/DataProtection/src/SP800_108/Win8SP800_108_CTR_HMACSHA512Provider.cs b/src/DataProtection/DataProtection/src/SP800_108/Win8SP800_108_CTR_HMACSHA512Provider.cs
index be7fe7c91710..7e4f0babc396 100644
--- a/src/DataProtection/DataProtection/src/SP800_108/Win8SP800_108_CTR_HMACSHA512Provider.cs
+++ b/src/DataProtection/DataProtection/src/SP800_108/Win8SP800_108_CTR_HMACSHA512Provider.cs
@@ -8,7 +8,7 @@
namespace Microsoft.AspNetCore.DataProtection.SP800_108
{
- internal unsafe sealed class Win8SP800_108_CTR_HMACSHA512Provider : ISP800_108_CTR_HMACSHA512Provider
+ internal sealed unsafe class Win8SP800_108_CTR_HMACSHA512Provider : ISP800_108_CTR_HMACSHA512Provider
{
private readonly BCryptKeyHandle _keyHandle;
diff --git a/src/DataProtection/DataProtection/src/Secret.cs b/src/DataProtection/DataProtection/src/Secret.cs
index ac3f71dc5553..dd5e330ac9cf 100644
--- a/src/DataProtection/DataProtection/src/Secret.cs
+++ b/src/DataProtection/DataProtection/src/Secret.cs
@@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.DataProtection
///
/// Represents a secret value stored in memory.
///
- public unsafe sealed class Secret : IDisposable, ISecret
+ public sealed unsafe class Secret : IDisposable, ISecret
{
// from wincrypt.h
private const uint CRYPTPROTECTMEMORY_BLOCK_SIZE = 16;
diff --git a/src/DataProtection/DataProtection/src/XmlEncryption/XmlEncryptionExtensions.cs b/src/DataProtection/DataProtection/src/XmlEncryption/XmlEncryptionExtensions.cs
index 64dc4747afd9..567efab4e9e5 100644
--- a/src/DataProtection/DataProtection/src/XmlEncryption/XmlEncryptionExtensions.cs
+++ b/src/DataProtection/DataProtection/src/XmlEncryption/XmlEncryptionExtensions.cs
@@ -13,7 +13,7 @@
namespace Microsoft.AspNetCore.DataProtection.XmlEncryption
{
- internal unsafe static class XmlEncryptionExtensions
+ internal static unsafe class XmlEncryptionExtensions
{
public static XElement DecryptElement(this XElement element, IActivator activator)
{
diff --git a/src/DataProtection/DataProtection/test/Cng/CngAuthenticatedEncryptorBaseTests.cs b/src/DataProtection/DataProtection/test/Cng/CngAuthenticatedEncryptorBaseTests.cs
index ef0b405dab9b..da29deb155f9 100644
--- a/src/DataProtection/DataProtection/test/Cng/CngAuthenticatedEncryptorBaseTests.cs
+++ b/src/DataProtection/DataProtection/test/Cng/CngAuthenticatedEncryptorBaseTests.cs
@@ -94,14 +94,14 @@ public override void Dispose()
public abstract byte[] DecryptHook(IntPtr pbCiphertext, uint cbCiphertext, IntPtr pbAdditionalAuthenticatedData, uint cbAdditionalAuthenticatedData);
- protected override sealed unsafe byte[] DecryptImpl(byte* pbCiphertext, uint cbCiphertext, byte* pbAdditionalAuthenticatedData, uint cbAdditionalAuthenticatedData)
+ protected sealed override unsafe byte[] DecryptImpl(byte* pbCiphertext, uint cbCiphertext, byte* pbAdditionalAuthenticatedData, uint cbAdditionalAuthenticatedData)
{
return DecryptHook((IntPtr)pbCiphertext, cbCiphertext, (IntPtr)pbAdditionalAuthenticatedData, cbAdditionalAuthenticatedData);
}
public abstract byte[] EncryptHook(IntPtr pbPlaintext, uint cbPlaintext, IntPtr pbAdditionalAuthenticatedData, uint cbAdditionalAuthenticatedData, uint cbPreBuffer, uint cbPostBuffer);
- protected override sealed unsafe byte[] EncryptImpl(byte* pbPlaintext, uint cbPlaintext, byte* pbAdditionalAuthenticatedData, uint cbAdditionalAuthenticatedData, uint cbPreBuffer, uint cbPostBuffer)
+ protected sealed override unsafe byte[] EncryptImpl(byte* pbPlaintext, uint cbPlaintext, byte* pbAdditionalAuthenticatedData, uint cbAdditionalAuthenticatedData, uint cbPreBuffer, uint cbPostBuffer)
{
return EncryptHook((IntPtr)pbPlaintext, cbPlaintext, (IntPtr)pbAdditionalAuthenticatedData, cbAdditionalAuthenticatedData, cbPreBuffer, cbPostBuffer);
}
diff --git a/src/Hosting/Hosting/src/Internal/HostingApplication.cs b/src/Hosting/Hosting/src/Internal/HostingApplication.cs
index 9bb72ac668b4..7e7e934511f2 100644
--- a/src/Hosting/Hosting/src/Internal/HostingApplication.cs
+++ b/src/Hosting/Hosting/src/Internal/HostingApplication.cs
@@ -17,7 +17,7 @@ internal class HostingApplication : IHttpApplication
private readonly RequestDelegate _application;
private readonly IHttpContextFactory? _httpContextFactory;
private readonly DefaultHttpContextFactory? _defaultHttpContextFactory;
- private HostingApplicationDiagnostics _diagnostics;
+ private readonly HostingApplicationDiagnostics _diagnostics;
public HostingApplication(
RequestDelegate application,
diff --git a/src/Hosting/Hosting/src/Startup/DelegateStartup.cs b/src/Hosting/Hosting/src/Startup/DelegateStartup.cs
index c71f54c52e99..dfc1317ece00 100644
--- a/src/Hosting/Hosting/src/Startup/DelegateStartup.cs
+++ b/src/Hosting/Hosting/src/Startup/DelegateStartup.cs
@@ -14,7 +14,7 @@ namespace Microsoft.AspNetCore.Hosting
///
public class DelegateStartup : StartupBase
{
- private Action _configureApp;
+ private readonly Action _configureApp;
///
/// Creates a new instance.
diff --git a/src/Hosting/Server.IntegrationTesting/src/Common/LoggingHandler.cs b/src/Hosting/Server.IntegrationTesting/src/Common/LoggingHandler.cs
index a1dc7e24dbd3..002e5c78bb20 100644
--- a/src/Hosting/Server.IntegrationTesting/src/Common/LoggingHandler.cs
+++ b/src/Hosting/Server.IntegrationTesting/src/Common/LoggingHandler.cs
@@ -8,7 +8,7 @@ namespace Microsoft.AspNetCore.Server.IntegrationTesting
{
internal class LoggingHandler : DelegatingHandler
{
- private ILogger _logger;
+ private readonly ILogger _logger;
public LoggingHandler(ILoggerFactory loggerFactory, HttpMessageHandler innerHandler) : base(innerHandler)
{
diff --git a/src/Hosting/TestHost/src/ResponseBodyReaderStream.cs b/src/Hosting/TestHost/src/ResponseBodyReaderStream.cs
index 01a8ee748b10..c4799a1690b4 100644
--- a/src/Hosting/TestHost/src/ResponseBodyReaderStream.cs
+++ b/src/Hosting/TestHost/src/ResponseBodyReaderStream.cs
@@ -68,7 +68,7 @@ public override int Read(byte[] buffer, int offset, int count)
return ReadAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult();
}
- public async override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
+ public override async Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
VerifyBuffer(buffer, offset, count);
CheckAborted();
diff --git a/src/Hosting/TestHost/src/TestServer.cs b/src/Hosting/TestHost/src/TestServer.cs
index fdc43e3f9437..cd4898af1ee0 100644
--- a/src/Hosting/TestHost/src/TestServer.cs
+++ b/src/Hosting/TestHost/src/TestServer.cs
@@ -18,7 +18,7 @@ namespace Microsoft.AspNetCore.TestHost
///
public class TestServer : IServer
{
- private IWebHost? _hostInstance;
+ private readonly IWebHost? _hostInstance;
private bool _disposed;
private ApplicationWrapper? _application;
diff --git a/src/Hosting/TestHost/src/TestWebSocket.cs b/src/Hosting/TestHost/src/TestWebSocket.cs
index e6ede4ec429e..3d17b24be64f 100644
--- a/src/Hosting/TestHost/src/TestWebSocket.cs
+++ b/src/Hosting/TestHost/src/TestWebSocket.cs
@@ -48,7 +48,7 @@ public override string? SubProtocol
get { return _subProtocol; }
}
- public async override Task CloseAsync(WebSocketCloseStatus closeStatus, string? statusDescription, CancellationToken cancellationToken)
+ public override async Task CloseAsync(WebSocketCloseStatus closeStatus, string? statusDescription, CancellationToken cancellationToken)
{
ThrowIfDisposed();
@@ -71,7 +71,7 @@ public async override Task CloseAsync(WebSocketCloseStatus closeStatus, string?
}
}
- public async override Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string? statusDescription, CancellationToken cancellationToken)
+ public override async Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string? statusDescription, CancellationToken cancellationToken)
{
ThrowIfDisposed();
ThrowIfOutputClosed();
@@ -264,7 +264,7 @@ public ReceiverSenderBuffer()
_messageQueue = new Queue();
}
- public async virtual Task ReceiveAsync(CancellationToken cancellationToken)
+ public virtual async Task ReceiveAsync(CancellationToken cancellationToken)
{
if (_disposed)
{
diff --git a/src/Http/Headers/src/GenericHeaderParser.cs b/src/Http/Headers/src/GenericHeaderParser.cs
index 1d4499e0b6fc..c2231b4e0ced 100644
--- a/src/Http/Headers/src/GenericHeaderParser.cs
+++ b/src/Http/Headers/src/GenericHeaderParser.cs
@@ -10,7 +10,7 @@ internal sealed class GenericHeaderParser : BaseHeaderParser
{
internal delegate int GetParsedValueLengthDelegate(StringSegment value, int startIndex, out T? parsedValue);
- private GetParsedValueLengthDelegate _getParsedValueLength;
+ private readonly GetParsedValueLengthDelegate _getParsedValueLength;
internal GenericHeaderParser(bool supportsMultipleValues, GetParsedValueLengthDelegate getParsedValueLength)
: base(supportsMultipleValues)
diff --git a/src/Http/Http.Abstractions/src/Internal/HostStringHelper.cs b/src/Http/Http.Abstractions/src/Internal/HostStringHelper.cs
index 7644b1a06c6d..9e42e1294458 100644
--- a/src/Http/Http.Abstractions/src/Internal/HostStringHelper.cs
+++ b/src/Http/Http.Abstractions/src/Internal/HostStringHelper.cs
@@ -9,7 +9,7 @@ internal class HostStringHelper
// A-Z, a-z, 0-9, .,
// -, %, [, ], :
// Above for IPV6
- private static bool[] SafeHostStringChars = {
+ private static readonly bool[] SafeHostStringChars = {
false, false, false, false, false, false, false, false, // 0x00 - 0x07
false, false, false, false, false, false, false, false, // 0x08 - 0x0F
false, false, false, false, false, false, false, false, // 0x10 - 0x17
diff --git a/src/Http/Http.Abstractions/src/Routing/EndpointMetadataCollection.cs b/src/Http/Http.Abstractions/src/Routing/EndpointMetadataCollection.cs
index 6051068e527c..f7a60d4043e4 100644
--- a/src/Http/Http.Abstractions/src/Routing/EndpointMetadataCollection.cs
+++ b/src/Http/Http.Abstractions/src/Routing/EndpointMetadataCollection.cs
@@ -152,7 +152,7 @@ private T[] GetOrderedMetadataSlow() where T : class
public struct Enumerator : IEnumerator
public class QueryBuilder : IEnumerable>
{
- private IList> _params;
+ private readonly IList> _params;
///
/// Initializes a new instance of .
diff --git a/src/Http/Http/src/Features/RequestBodyPipeFeature.cs b/src/Http/Http/src/Features/RequestBodyPipeFeature.cs
index 994a813a7623..08db861a862a 100644
--- a/src/Http/Http/src/Features/RequestBodyPipeFeature.cs
+++ b/src/Http/Http/src/Features/RequestBodyPipeFeature.cs
@@ -15,7 +15,7 @@ public class RequestBodyPipeFeature : IRequestBodyPipeFeature
{
private PipeReader? _internalPipeReader;
private Stream? _streamInstanceWhenWrapped;
- private HttpContext _context;
+ private readonly HttpContext _context;
///
/// Initializes a new instance of .
diff --git a/src/Http/Http/src/Features/RequestCookiesFeature.cs b/src/Http/Http/src/Features/RequestCookiesFeature.cs
index e5d36d3bf8dd..c3458fd94db7 100644
--- a/src/Http/Http/src/Features/RequestCookiesFeature.cs
+++ b/src/Http/Http/src/Features/RequestCookiesFeature.cs
@@ -14,7 +14,7 @@ namespace Microsoft.AspNetCore.Http.Features
public class RequestCookiesFeature : IRequestCookiesFeature
{
// Lambda hoisted to static readonly field to improve inlining https://github.com/dotnet/roslyn/issues/13624
- private readonly static Func _nullRequestFeature = f => null;
+ private static readonly Func _nullRequestFeature = f => null;
private FeatureReferences _features;
private StringValues _original;
diff --git a/src/Http/Http/src/FormCollection.cs b/src/Http/Http/src/FormCollection.cs
index e937dbd5eb4d..8dec9be3ab6e 100644
--- a/src/Http/Http/src/FormCollection.cs
+++ b/src/Http/Http/src/FormCollection.cs
@@ -23,7 +23,7 @@ public class FormCollection : IFormCollection
private static readonly IEnumerator> EmptyIEnumeratorType = default(Enumerator);
private static readonly IEnumerator EmptyIEnumerator = default(Enumerator);
- private static IFormFileCollection EmptyFiles = new FormFileCollection();
+ private static readonly IFormFileCollection EmptyFiles = new FormFileCollection();
private IFormFileCollection? _files;
@@ -174,7 +174,7 @@ public struct Enumerator : IEnumerator>
{
// Do NOT make this readonly, or MoveNext will not work
private Dictionary.Enumerator _dictionaryEnumerator;
- private bool _notEmpty;
+ private readonly bool _notEmpty;
internal Enumerator(Dictionary.Enumerator dictionaryEnumerator)
{
diff --git a/src/Http/Http/src/HeaderDictionary.cs b/src/Http/Http/src/HeaderDictionary.cs
index 620d4fc207e1..3664e748bf04 100644
--- a/src/Http/Http/src/HeaderDictionary.cs
+++ b/src/Http/Http/src/HeaderDictionary.cs
@@ -376,7 +376,7 @@ public struct Enumerator : IEnumerator>
{
// Do NOT make this readonly, or MoveNext will not work
private Dictionary.Enumerator _dictionaryEnumerator;
- private bool _notEmpty;
+ private readonly bool _notEmpty;
internal Enumerator(Dictionary.Enumerator dictionaryEnumerator)
{
diff --git a/src/Http/Http/src/HttpContextAccessor.cs b/src/Http/Http/src/HttpContextAccessor.cs
index 553b512dbb23..6bdb99f30b53 100644
--- a/src/Http/Http/src/HttpContextAccessor.cs
+++ b/src/Http/Http/src/HttpContextAccessor.cs
@@ -10,7 +10,7 @@ namespace Microsoft.AspNetCore.Http
///
public class HttpContextAccessor : IHttpContextAccessor
{
- private static AsyncLocal _httpContextCurrent = new AsyncLocal();
+ private static readonly AsyncLocal _httpContextCurrent = new AsyncLocal();
///
public HttpContext? HttpContext
diff --git a/src/Http/Http/src/Internal/DefaultConnectionInfo.cs b/src/Http/Http/src/Internal/DefaultConnectionInfo.cs
index 12f4ff2175f0..32cc822beead 100644
--- a/src/Http/Http/src/Internal/DefaultConnectionInfo.cs
+++ b/src/Http/Http/src/Internal/DefaultConnectionInfo.cs
@@ -14,9 +14,9 @@ namespace Microsoft.AspNetCore.Http
internal sealed class DefaultConnectionInfo : ConnectionInfo
{
// Lambdas hoisted to static readonly fields to improve inlining https://github.com/dotnet/roslyn/issues/13624
- private readonly static Func _newHttpConnectionFeature = f => new HttpConnectionFeature();
- private readonly static Func _newTlsConnectionFeature = f => new TlsConnectionFeature();
- private readonly static Func _newConnectionLifetime = f => new DefaultConnectionLifetimeNotificationFeature(f.Get());
+ private static readonly Func _newHttpConnectionFeature = f => new HttpConnectionFeature();
+ private static readonly Func _newTlsConnectionFeature = f => new TlsConnectionFeature();
+ private static readonly Func _newConnectionLifetime = f => new DefaultConnectionLifetimeNotificationFeature(f.Get());
private FeatureReferences _features;
diff --git a/src/Http/Http/src/Internal/DefaultHttpRequest.cs b/src/Http/Http/src/Internal/DefaultHttpRequest.cs
index 9c54c0883d58..2dd5468fc453 100644
--- a/src/Http/Http/src/Internal/DefaultHttpRequest.cs
+++ b/src/Http/Http/src/Internal/DefaultHttpRequest.cs
@@ -18,12 +18,12 @@ internal sealed class DefaultHttpRequest : HttpRequest
private const string Https = "https";
// Lambdas hoisted to static readonly fields to improve inlining https://github.com/dotnet/roslyn/issues/13624
- private readonly static Func _nullRequestFeature = f => null;
- private readonly static Func _newQueryFeature = f => new QueryFeature(f);
- private readonly static Func _newFormFeature = r => new FormFeature(r, r._context.FormOptions ?? FormOptions.Default);
- private readonly static Func _newRequestCookiesFeature = f => new RequestCookiesFeature(f);
- private readonly static Func _newRouteValuesFeature = f => new RouteValuesFeature();
- private readonly static Func _newRequestBodyPipeFeature = context => new RequestBodyPipeFeature(context);
+ private static readonly Func _nullRequestFeature = f => null;
+ private static readonly Func _newQueryFeature = f => new QueryFeature(f);
+ private static readonly Func _newFormFeature = r => new FormFeature(r, r._context.FormOptions ?? FormOptions.Default);
+ private static readonly Func _newRequestCookiesFeature = f => new RequestCookiesFeature(f);
+ private static readonly Func _newRouteValuesFeature = f => new RouteValuesFeature();
+ private static readonly Func _newRequestBodyPipeFeature = context => new RequestBodyPipeFeature(context);
private readonly DefaultHttpContext _context;
private FeatureReferences _features;
diff --git a/src/Http/Http/src/Internal/DefaultWebSocketManager.cs b/src/Http/Http/src/Internal/DefaultWebSocketManager.cs
index 8697904b952c..51bbd84bf353 100644
--- a/src/Http/Http/src/Internal/DefaultWebSocketManager.cs
+++ b/src/Http/Http/src/Internal/DefaultWebSocketManager.cs
@@ -13,11 +13,11 @@ namespace Microsoft.AspNetCore.Http
internal sealed class DefaultWebSocketManager : WebSocketManager
{
// Lambdas hoisted to static readonly fields to improve inlining https://github.com/dotnet/roslyn/issues/13624
- private readonly static Func _nullRequestFeature = f => null;
- private readonly static Func _nullWebSocketFeature = f => null;
+ private static readonly Func _nullRequestFeature = f => null;
+ private static readonly Func _nullWebSocketFeature = f => null;
private FeatureReferences _features;
- private readonly static WebSocketAcceptContext _defaultWebSocketAcceptContext = new WebSocketAcceptContext();
+ private static readonly WebSocketAcceptContext _defaultWebSocketAcceptContext = new WebSocketAcceptContext();
public DefaultWebSocketManager(IFeatureCollection features)
{
diff --git a/src/Http/Http/src/Internal/ItemsDictionary.cs b/src/Http/Http/src/Internal/ItemsDictionary.cs
index 0ea54f92c1cd..eda357038e21 100644
--- a/src/Http/Http/src/Internal/ItemsDictionary.cs
+++ b/src/Http/Http/src/Internal/ItemsDictionary.cs
@@ -140,7 +140,7 @@ private void EnsureDictionary()
private class EmptyEnumerator : IEnumerator>
{
// In own class so only initalized if GetEnumerator is called on an empty ItemsDictionary
- public readonly static IEnumerator> Instance = new EmptyEnumerator();
+ public static readonly IEnumerator> Instance = new EmptyEnumerator();
public KeyValuePair
public class StringRouteConstraint : IRouteConstraint
{
- private string _value;
+ private readonly string _value;
///
/// Initializes a new instance of the class.
diff --git a/src/Http/Routing/src/Matching/EndpointMetadataComparer.cs b/src/Http/Routing/src/Matching/EndpointMetadataComparer.cs
index 620e63571689..d04ba767d2c4 100644
--- a/src/Http/Routing/src/Matching/EndpointMetadataComparer.cs
+++ b/src/Http/Routing/src/Matching/EndpointMetadataComparer.cs
@@ -18,7 +18,7 @@ namespace Microsoft.AspNetCore.Routing.Matching
///
public sealed class EndpointMetadataComparer : IComparer
{
- private IServiceProvider _services;
+ private readonly IServiceProvider _services;
private IComparer[]? _comparers;
// This type is **INTENDED** for use in MatcherPolicy instances yet is also needs the MatcherPolicy instances.
diff --git a/src/Http/Routing/src/Matching/HostMatcherPolicy.cs b/src/Http/Routing/src/Matching/HostMatcherPolicy.cs
index 7e39d449b428..8b580d5e3a66 100644
--- a/src/Http/Routing/src/Matching/HostMatcherPolicy.cs
+++ b/src/Http/Routing/src/Matching/HostMatcherPolicy.cs
@@ -359,8 +359,8 @@ protected override int CompareMetadata(IHostMetadata? x, IHostMetadata? y)
private class HostPolicyJumpTable : PolicyJumpTable
{
- private (EdgeKey host, int destination)[] _destinations;
- private int _exitDestination;
+ private readonly (EdgeKey host, int destination)[] _destinations;
+ private readonly int _exitDestination;
public HostPolicyJumpTable(int exitDestination, (EdgeKey host, int destination)[] destinations)
{
diff --git a/src/Http/Routing/src/RouteCollection.cs b/src/Http/Routing/src/RouteCollection.cs
index 2f644cbfb37c..1426abfc8089 100644
--- a/src/Http/Routing/src/RouteCollection.cs
+++ b/src/Http/Routing/src/RouteCollection.cs
@@ -19,7 +19,7 @@ namespace Microsoft.AspNetCore.Routing
///
public class RouteCollection : IRouteCollection
{
- private readonly static char[] UrlQueryDelimiters = new char[] { '?', '#' };
+ private static readonly char[] UrlQueryDelimiters = new char[] { '?', '#' };
private readonly List _routes = new List();
private readonly List _unnamedRoutes = new List();
private readonly Dictionary _namedRoutes =
@@ -69,7 +69,7 @@ public void Add(IRouter router)
}
///
- public async virtual Task RouteAsync(RouteContext context)
+ public virtual async Task RouteAsync(RouteContext context)
{
// Perf: We want to avoid allocating a new RouteData for each route we need to process.
// We can do this by snapshotting the state at the beginning and then restoring it
diff --git a/src/Http/Routing/src/Template/TemplateMatcher.cs b/src/Http/Routing/src/Template/TemplateMatcher.cs
index 1cffb0d42c47..a6657aeaf6e2 100644
--- a/src/Http/Routing/src/Template/TemplateMatcher.cs
+++ b/src/Http/Routing/src/Template/TemplateMatcher.cs
@@ -18,7 +18,7 @@ public class TemplateMatcher
private readonly bool[] _hasDefaultValue;
private readonly object?[] _defaultValues;
- private RoutePatternMatcher _routePatternMatcher;
+ private readonly RoutePatternMatcher _routePatternMatcher;
///
/// Creates a new instance given a and .
diff --git a/src/Http/Routing/src/UriBuildingContext.cs b/src/Http/Routing/src/UriBuildingContext.cs
index bf68a9449cd5..d85e5970f97d 100644
--- a/src/Http/Routing/src/UriBuildingContext.cs
+++ b/src/Http/Routing/src/UriBuildingContext.cs
@@ -16,7 +16,7 @@ internal class UriBuildingContext
{
// Holds the 'accepted' parts of the path.
private readonly StringBuilder _path;
- private StringBuilder _query;
+ private readonly StringBuilder _query;
// Holds the 'optional' parts of the path. We need a secondary buffer to handle cases where an optional
// segment is in the middle of the uri. We don't know if we need to write it out - if it's
diff --git a/src/Http/Routing/test/UnitTests/Builder/RoutingEndpointConventionBuilderExtensionsTest.cs b/src/Http/Routing/test/UnitTests/Builder/RoutingEndpointConventionBuilderExtensionsTest.cs
index e2957e54704e..4ce27b93992d 100644
--- a/src/Http/Routing/test/UnitTests/Builder/RoutingEndpointConventionBuilderExtensionsTest.cs
+++ b/src/Http/Routing/test/UnitTests/Builder/RoutingEndpointConventionBuilderExtensionsTest.cs
@@ -127,7 +127,7 @@ private TestEndpointConventionBuilder CreateBuilder()
private class TestEndpointConventionBuilder : IEndpointConventionBuilder
{
- private DefaultEndpointConventionBuilder _endpointConventionBuilder;
+ private readonly DefaultEndpointConventionBuilder _endpointConventionBuilder;
public bool TestProperty { get; } = true;
public TestEndpointConventionBuilder(DefaultEndpointConventionBuilder endpointConventionBuilder)
diff --git a/src/Http/Routing/test/UnitTests/Constraints/CompositeRouteConstraintTests.cs b/src/Http/Routing/test/UnitTests/Constraints/CompositeRouteConstraintTests.cs
index b4df74c26287..ece4da2c9c86 100644
--- a/src/Http/Routing/test/UnitTests/Constraints/CompositeRouteConstraintTests.cs
+++ b/src/Http/Routing/test/UnitTests/Constraints/CompositeRouteConstraintTests.cs
@@ -34,7 +34,7 @@ public void CompositeRouteConstraint_Match_CallsMatchOnInnerConstraints(
Assert.Equal(expected, actual);
}
- static Expression> ConstraintMatchMethodExpression =
+ static readonly Expression> ConstraintMatchMethodExpression =
c => c.Match(
It.IsAny(),
It.IsAny(),
diff --git a/src/Http/Routing/test/UnitTests/DefaultInlineConstraintResolverTest.cs b/src/Http/Routing/test/UnitTests/DefaultInlineConstraintResolverTest.cs
index da4cf39c0957..a50c8aa6d9b7 100644
--- a/src/Http/Routing/test/UnitTests/DefaultInlineConstraintResolverTest.cs
+++ b/src/Http/Routing/test/UnitTests/DefaultInlineConstraintResolverTest.cs
@@ -15,7 +15,7 @@ namespace Microsoft.AspNetCore.Routing.Tests
{
public class DefaultInlineConstraintResolverTest
{
- private IInlineConstraintResolver _constraintResolver;
+ private readonly IInlineConstraintResolver _constraintResolver;
public DefaultInlineConstraintResolverTest()
{
diff --git a/src/Http/Routing/test/UnitTests/MatcherPolicyTest.cs b/src/Http/Routing/test/UnitTests/MatcherPolicyTest.cs
index 3c62aa1eccdc..ee618241f6c7 100644
--- a/src/Http/Routing/test/UnitTests/MatcherPolicyTest.cs
+++ b/src/Http/Routing/test/UnitTests/MatcherPolicyTest.cs
@@ -83,7 +83,7 @@ private class TestMatcherPolicy : MatcherPolicy
{
public override int Order => throw new System.NotImplementedException();
- public new static bool ContainsDynamicEndpoints(IReadOnlyList endpoints)
+ public static new bool ContainsDynamicEndpoints(IReadOnlyList endpoints)
{
return MatcherPolicy.ContainsDynamicEndpoints(endpoints);
}
diff --git a/src/Http/Routing/test/UnitTests/Matching/BarebonesMatcherBuilder.cs b/src/Http/Routing/test/UnitTests/Matching/BarebonesMatcherBuilder.cs
index d55d0dcdf096..9259cdac8f15 100644
--- a/src/Http/Routing/test/UnitTests/Matching/BarebonesMatcherBuilder.cs
+++ b/src/Http/Routing/test/UnitTests/Matching/BarebonesMatcherBuilder.cs
@@ -11,7 +11,7 @@ namespace Microsoft.AspNetCore.Routing.Matching
{
internal class BarebonesMatcherBuilder : MatcherBuilder
{
- private List _endpoints = new List();
+ private readonly List _endpoints = new List();
public override void AddEndpoint(RouteEndpoint endpoint)
{
diff --git a/src/Http/Routing/test/UnitTests/Matching/RouteMatcher.cs b/src/Http/Routing/test/UnitTests/Matching/RouteMatcher.cs
index 540fc2e07b5d..e18035d718ad 100644
--- a/src/Http/Routing/test/UnitTests/Matching/RouteMatcher.cs
+++ b/src/Http/Routing/test/UnitTests/Matching/RouteMatcher.cs
@@ -17,7 +17,7 @@ internal RouteMatcher(RouteCollection inner)
_inner = inner;
}
- public async override Task MatchAsync(HttpContext httpContext)
+ public override async Task MatchAsync(HttpContext httpContext)
{
if (httpContext == null)
{
diff --git a/src/Http/Routing/test/UnitTests/Matching/TreeRouterMatcher.cs b/src/Http/Routing/test/UnitTests/Matching/TreeRouterMatcher.cs
index 6145013c8039..3d9112274baf 100644
--- a/src/Http/Routing/test/UnitTests/Matching/TreeRouterMatcher.cs
+++ b/src/Http/Routing/test/UnitTests/Matching/TreeRouterMatcher.cs
@@ -19,7 +19,7 @@ internal TreeRouterMatcher(TreeRouter inner)
_inner = inner;
}
- public async override Task MatchAsync(HttpContext httpContext)
+ public override async Task MatchAsync(HttpContext httpContext)
{
if (httpContext == null)
{
diff --git a/src/Http/Routing/test/UnitTests/RouteTest.cs b/src/Http/Routing/test/UnitTests/RouteTest.cs
index 16e7571e2e55..f83d50c5e1e2 100644
--- a/src/Http/Routing/test/UnitTests/RouteTest.cs
+++ b/src/Http/Routing/test/UnitTests/RouteTest.cs
@@ -23,7 +23,7 @@ namespace Microsoft.AspNetCore.Routing
public class RouteTest
{
private static readonly RequestDelegate NullHandler = (c) => Task.CompletedTask;
- private static IInlineConstraintResolver _inlineConstraintResolver = GetInlineConstraintResolver();
+ private static readonly IInlineConstraintResolver _inlineConstraintResolver = GetInlineConstraintResolver();
[Fact]
public void CreateTemplate_InlineConstraint_Regex_Malformed()
diff --git a/src/Http/Routing/test/UnitTests/RouterMiddlewareTest.cs b/src/Http/Routing/test/UnitTests/RouterMiddlewareTest.cs
index 29a03c7e0831..41d4bf0ba1e7 100644
--- a/src/Http/Routing/test/UnitTests/RouterMiddlewareTest.cs
+++ b/src/Http/Routing/test/UnitTests/RouterMiddlewareTest.cs
@@ -128,7 +128,7 @@ public async Task Invoke_DoesNotLog_WhenHandled()
private class TestRouter : IRouter
{
- private bool _isHandled;
+ private readonly bool _isHandled;
public TestRouter(bool isHandled)
{
diff --git a/src/Http/Routing/test/UnitTests/TemplateParserDefaultValuesTests.cs b/src/Http/Routing/test/UnitTests/TemplateParserDefaultValuesTests.cs
index 2a5ae1f91849..6cd29194a541 100644
--- a/src/Http/Routing/test/UnitTests/TemplateParserDefaultValuesTests.cs
+++ b/src/Http/Routing/test/UnitTests/TemplateParserDefaultValuesTests.cs
@@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.Routing.Tests
{
public class TemplateParserDefaultValuesTests
{
- private static IInlineConstraintResolver _inlineConstraintResolver = GetInlineConstraintResolver();
+ private static readonly IInlineConstraintResolver _inlineConstraintResolver = GetInlineConstraintResolver();
[Fact]
public void InlineDefaultValueSpecified_InlineValueIsUsed()
diff --git a/src/Http/WebUtilities/perf/Microbenchmarks/FormPipeReaderInternalsBenchmark.cs b/src/Http/WebUtilities/perf/Microbenchmarks/FormPipeReaderInternalsBenchmark.cs
index e82e96da1438..b56afb9f9c9d 100644
--- a/src/Http/WebUtilities/perf/Microbenchmarks/FormPipeReaderInternalsBenchmark.cs
+++ b/src/Http/WebUtilities/perf/Microbenchmarks/FormPipeReaderInternalsBenchmark.cs
@@ -12,9 +12,9 @@ namespace Microsoft.AspNetCore.WebUtilities.Microbenchmarks
///
public class FormPipeReaderInternalsBenchmark
{
- private byte[] _singleUtf8 = Encoding.UTF8.GetBytes("foo=bar&baz=boo&haha=hehe&lol=temp");
- private byte[] _firstUtf8 = Encoding.UTF8.GetBytes("foo=bar&baz=bo");
- private byte[] _secondUtf8 = Encoding.UTF8.GetBytes("o&haha=hehe&lol=temp");
+ private readonly byte[] _singleUtf8 = Encoding.UTF8.GetBytes("foo=bar&baz=boo&haha=hehe&lol=temp");
+ private readonly byte[] _firstUtf8 = Encoding.UTF8.GetBytes("foo=bar&baz=bo");
+ private readonly byte[] _secondUtf8 = Encoding.UTF8.GetBytes("o&haha=hehe&lol=temp");
private FormPipeReader _formPipeReader;
[IterationSetup]
diff --git a/src/Http/WebUtilities/src/FileMultipartSection.cs b/src/Http/WebUtilities/src/FileMultipartSection.cs
index daf7b3d0e918..2cd8ef6c3e35 100644
--- a/src/Http/WebUtilities/src/FileMultipartSection.cs
+++ b/src/Http/WebUtilities/src/FileMultipartSection.cs
@@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.WebUtilities
///
public class FileMultipartSection
{
- private ContentDispositionHeaderValue _contentDispositionHeader;
+ private readonly ContentDispositionHeaderValue _contentDispositionHeader;
///
/// Creates a new instance of the class
diff --git a/src/Http/WebUtilities/src/FormMultipartSection.cs b/src/Http/WebUtilities/src/FormMultipartSection.cs
index 520c67112cef..170e45728d73 100644
--- a/src/Http/WebUtilities/src/FormMultipartSection.cs
+++ b/src/Http/WebUtilities/src/FormMultipartSection.cs
@@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.WebUtilities
///
public class FormMultipartSection
{
- private ContentDispositionHeaderValue _contentDispositionHeader;
+ private readonly ContentDispositionHeaderValue _contentDispositionHeader;
///
/// Creates a new instance of the class
diff --git a/src/Http/WebUtilities/src/FormPipeReader.cs b/src/Http/WebUtilities/src/FormPipeReader.cs
index 92c340f973ae..49fcdafbf557 100644
--- a/src/Http/WebUtilities/src/FormPipeReader.cs
+++ b/src/Http/WebUtilities/src/FormPipeReader.cs
@@ -34,8 +34,8 @@ public class FormPipeReader
private static ReadOnlySpan UTF8AndEncoded => new byte[] { (byte)'&' };
// Used for other encodings
- private byte[]? _otherEqualEncoding;
- private byte[]? _otherAndEncoding;
+ private readonly byte[]? _otherEqualEncoding;
+ private readonly byte[]? _otherAndEncoding;
private readonly PipeReader _pipeReader;
private readonly Encoding _encoding;
diff --git a/src/Http/WebUtilities/src/HttpRequestStreamReader.cs b/src/Http/WebUtilities/src/HttpRequestStreamReader.cs
index 338d14491012..6ef2fb430b85 100644
--- a/src/Http/WebUtilities/src/HttpRequestStreamReader.cs
+++ b/src/Http/WebUtilities/src/HttpRequestStreamReader.cs
@@ -19,7 +19,7 @@ public class HttpRequestStreamReader : TextReader
{
private const int DefaultBufferSize = 1024;
- private Stream _stream;
+ private readonly Stream _stream;
private readonly Encoding _encoding;
private readonly Decoder _decoder;
@@ -27,8 +27,8 @@ public class HttpRequestStreamReader : TextReader
private readonly ArrayPool _charPool;
private readonly int _byteBufferSize;
- private byte[] _byteBuffer;
- private char[] _charBuffer;
+ private readonly byte[] _byteBuffer;
+ private readonly char[] _charBuffer;
private int _charBufferIndex;
private int _charsRead;
diff --git a/src/Http/WebUtilities/src/HttpResponseStreamWriter.cs b/src/Http/WebUtilities/src/HttpResponseStreamWriter.cs
index 252c535c8701..3eab97915948 100644
--- a/src/Http/WebUtilities/src/HttpResponseStreamWriter.cs
+++ b/src/Http/WebUtilities/src/HttpResponseStreamWriter.cs
@@ -21,14 +21,14 @@ public class HttpResponseStreamWriter : TextWriter
{
internal const int DefaultBufferSize = 16 * 1024;
- private Stream _stream;
+ private readonly Stream _stream;
private readonly Encoder _encoder;
private readonly ArrayPool _bytePool;
private readonly ArrayPool _charPool;
private readonly int _charBufferSize;
- private byte[] _byteBuffer;
- private char[] _charBuffer;
+ private readonly byte[] _byteBuffer;
+ private readonly char[] _charBuffer;
private int _charBufferCount;
private bool _disposed;
diff --git a/src/Http/WebUtilities/test/HttpRequestStreamReaderTest.cs b/src/Http/WebUtilities/test/HttpRequestStreamReaderTest.cs
index 87b2408d1508..426f2edb2129 100644
--- a/src/Http/WebUtilities/test/HttpRequestStreamReaderTest.cs
+++ b/src/Http/WebUtilities/test/HttpRequestStreamReaderTest.cs
@@ -309,7 +309,7 @@ public static void Read_Span_WithMoreDataThanInternalBufferSize()
}
[Fact]
- public async static Task ReadAsync_Memory_ReadAllCharactersAtOnce()
+ public static async Task ReadAsync_Memory_ReadAllCharactersAtOnce()
{
// Arrange
var reader = CreateReader();
@@ -328,7 +328,7 @@ public async static Task ReadAsync_Memory_ReadAllCharactersAtOnce()
}
[Fact]
- public async static Task ReadAsync_Memory_WithMoreDataThanInternalBufferSize()
+ public static async Task ReadAsync_Memory_WithMoreDataThanInternalBufferSize()
{
// Arrange
var reader = CreateReader(10);
diff --git a/src/Http/WebUtilities/test/NonSeekableReadStream.cs b/src/Http/WebUtilities/test/NonSeekableReadStream.cs
index f3c77abb3852..faadac69f7af 100644
--- a/src/Http/WebUtilities/test/NonSeekableReadStream.cs
+++ b/src/Http/WebUtilities/test/NonSeekableReadStream.cs
@@ -10,7 +10,7 @@ namespace Microsoft.AspNetCore.WebUtilities
{
public class NonSeekableReadStream : Stream
{
- private Stream _inner;
+ private readonly Stream _inner;
public NonSeekableReadStream(byte[] data)
: this(new MemoryStream(data))
diff --git a/src/Identity/ApiAuthorization.IdentityServer/src/Options/ApiResourceBuilder.cs b/src/Identity/ApiAuthorization.IdentityServer/src/Options/ApiResourceBuilder.cs
index 0f51c08de702..bff201bcba1f 100644
--- a/src/Identity/ApiAuthorization.IdentityServer/src/Options/ApiResourceBuilder.cs
+++ b/src/Identity/ApiAuthorization.IdentityServer/src/Options/ApiResourceBuilder.cs
@@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.ApiAuthorization.IdentityServer
///
public class ApiResourceBuilder
{
- private ApiResource _apiResource;
+ private readonly ApiResource _apiResource;
private bool _built;
///
diff --git a/src/Identity/ApiAuthorization.IdentityServer/src/Options/ClientBuilder.cs b/src/Identity/ApiAuthorization.IdentityServer/src/Options/ClientBuilder.cs
index a2bc51e943de..2e66158f0d08 100644
--- a/src/Identity/ApiAuthorization.IdentityServer/src/Options/ClientBuilder.cs
+++ b/src/Identity/ApiAuthorization.IdentityServer/src/Options/ClientBuilder.cs
@@ -14,8 +14,7 @@ namespace Microsoft.AspNetCore.ApiAuthorization.IdentityServer
public class ClientBuilder
{
private const string NativeAppClientRedirectUri = "urn:ietf:wg:oauth:2.0:oob";
-
- Client _client;
+ readonly Client _client;
private bool _built;
///
diff --git a/src/Identity/ApiAuthorization.IdentityServer/src/Options/IdentityResourceBuilder.cs b/src/Identity/ApiAuthorization.IdentityServer/src/Options/IdentityResourceBuilder.cs
index 623777afb45a..6a04a6640ee4 100644
--- a/src/Identity/ApiAuthorization.IdentityServer/src/Options/IdentityResourceBuilder.cs
+++ b/src/Identity/ApiAuthorization.IdentityServer/src/Options/IdentityResourceBuilder.cs
@@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.ApiAuthorization.IdentityServer
///
public class IdentityResourceBuilder
{
- private IdentityResource _identityResource;
+ private readonly IdentityResource _identityResource;
private bool _built;
///
diff --git a/src/Identity/Core/src/SignInManager.cs b/src/Identity/Core/src/SignInManager.cs
index b08078d8a23d..838a90319c2b 100644
--- a/src/Identity/Core/src/SignInManager.cs
+++ b/src/Identity/Core/src/SignInManager.cs
@@ -65,8 +65,8 @@ public SignInManager(UserManager userManager,
private readonly IHttpContextAccessor _contextAccessor;
private HttpContext _context;
- private IAuthenticationSchemeProvider _schemes;
- private IUserConfirmation _confirmation;
+ private readonly IAuthenticationSchemeProvider _schemes;
+ private readonly IUserConfirmation _confirmation;
///
/// Gets the used to log messages from the manager.
diff --git a/src/Identity/EntityFrameworkCore/src/RoleStore.cs b/src/Identity/EntityFrameworkCore/src/RoleStore.cs
index 8cacb89b5f28..f221c9f29c4d 100644
--- a/src/Identity/EntityFrameworkCore/src/RoleStore.cs
+++ b/src/Identity/EntityFrameworkCore/src/RoleStore.cs
@@ -135,7 +135,7 @@ private async Task SaveChanges(CancellationToken cancellationToken)
/// The role to create in the store.
/// The used to propagate notifications that the operation should be canceled.
/// A that represents the of the asynchronous query.
- public async virtual Task CreateAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken))
+ public virtual async Task CreateAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
@@ -154,7 +154,7 @@ private async Task SaveChanges(CancellationToken cancellationToken)
/// The role to update in the store.
/// The used to propagate notifications that the operation should be canceled.
/// A that represents the of the asynchronous query.
- public async virtual Task UpdateAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken))
+ public virtual async Task UpdateAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
@@ -182,7 +182,7 @@ private async Task SaveChanges(CancellationToken cancellationToken)
/// The role to delete from the store.
/// The used to propagate notifications that the operation should be canceled.
/// A that represents the of the asynchronous query.
- public async virtual Task DeleteAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken))
+ public virtual async Task DeleteAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
@@ -368,7 +368,7 @@ protected void ThrowIfDisposed()
/// The role whose claims should be retrieved.
/// The used to propagate notifications that the operation should be canceled.
/// A that contains the claims granted to a role.
- public async virtual Task> GetClaimsAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken))
+ public virtual async Task> GetClaimsAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
if (role == null)
@@ -409,7 +409,7 @@ protected void ThrowIfDisposed()
/// The claim to remove from the role.
/// The used to propagate notifications that the operation should be canceled.
/// The that represents the asynchronous operation.
- public async virtual Task RemoveClaimAsync(TRole role, Claim claim, CancellationToken cancellationToken = default(CancellationToken))
+ public virtual async Task RemoveClaimAsync(TRole role, Claim claim, CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
if (role == null)
diff --git a/src/Identity/EntityFrameworkCore/src/UserOnlyStore.cs b/src/Identity/EntityFrameworkCore/src/UserOnlyStore.cs
index ec77780b83b7..0e54aee3ea1d 100644
--- a/src/Identity/EntityFrameworkCore/src/UserOnlyStore.cs
+++ b/src/Identity/EntityFrameworkCore/src/UserOnlyStore.cs
@@ -153,7 +153,7 @@ protected Task SaveChanges(CancellationToken cancellationToken)
/// The user to create.
/// The used to propagate notifications that the operation should be canceled.
/// The that represents the asynchronous operation, containing the of the creation operation.
- public async override Task CreateAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
+ public override async Task CreateAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
@@ -172,7 +172,7 @@ protected Task SaveChanges(CancellationToken cancellationToken)
/// The user to update.
/// The used to propagate notifications that the operation should be canceled.
/// The that represents the asynchronous operation, containing the of the update operation.
- public async override Task UpdateAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
+ public override async Task UpdateAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
@@ -201,7 +201,7 @@ protected Task SaveChanges(CancellationToken cancellationToken)
/// The user to delete.
/// The used to propagate notifications that the operation should be canceled.
/// The that represents the asynchronous operation, containing the of the update operation.
- public async override Task DeleteAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
+ public override async Task DeleteAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
@@ -304,7 +304,7 @@ protected override Task FindUserLoginAsync(string loginProvider, str
/// The user whose claims should be retrieved.
/// The used to propagate notifications that the operation should be canceled.
/// A that contains the claims granted to a user.
- public async override Task> GetClaimsAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
+ public override async Task> GetClaimsAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
if (user == null)
@@ -348,7 +348,7 @@ protected override Task FindUserLoginAsync(string loginProvider, str
/// The new claim replacing the .
/// The used to propagate notifications that the operation should be canceled.
/// The that represents the asynchronous operation.
- public async override Task ReplaceClaimAsync(TUser user, Claim claim, Claim newClaim, CancellationToken cancellationToken = default(CancellationToken))
+ public override async Task ReplaceClaimAsync(TUser user, Claim claim, Claim newClaim, CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
if (user == null)
@@ -379,7 +379,7 @@ protected override Task FindUserLoginAsync(string loginProvider, str
/// The claim to remove.
/// The used to propagate notifications that the operation should be canceled.
/// The that represents the asynchronous operation.
- public async override Task RemoveClaimsAsync(TUser user, IEnumerable claims, CancellationToken cancellationToken = default(CancellationToken))
+ public override async Task RemoveClaimsAsync(TUser user, IEnumerable claims, CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
if (user == null)
@@ -456,7 +456,7 @@ public override async Task RemoveLoginAsync(TUser user, string loginProvider, st
///
/// The for the asynchronous operation, containing a list of for the specified , if any.
///
- public async override Task> GetLoginsAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
+ public override async Task> GetLoginsAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
@@ -478,7 +478,7 @@ public override async Task RemoveLoginAsync(TUser user, string loginProvider, st
///
/// The for the asynchronous operation, containing the user, if any which matched the specified login provider and key.
///
- public async override Task FindByLoginAsync(string loginProvider, string providerKey,
+ public override async Task FindByLoginAsync(string loginProvider, string providerKey,
CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
@@ -515,7 +515,7 @@ public async override Task FindByLoginAsync(string loginProvider, string
///
/// The contains a list of users, if any, that contain the specified claim.
///
- public async override Task> GetUsersForClaimAsync(Claim claim, CancellationToken cancellationToken = default(CancellationToken))
+ public override async Task> GetUsersForClaimAsync(Claim claim, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
diff --git a/src/Identity/EntityFrameworkCore/src/UserStore.cs b/src/Identity/EntityFrameworkCore/src/UserStore.cs
index e1133ddc7d2d..7220db5e86af 100644
--- a/src/Identity/EntityFrameworkCore/src/UserStore.cs
+++ b/src/Identity/EntityFrameworkCore/src/UserStore.cs
@@ -154,7 +154,7 @@ protected Task SaveChanges(CancellationToken cancellationToken)
/// The user to create.
/// The used to propagate notifications that the operation should be canceled.
/// The that represents the asynchronous operation, containing the of the creation operation.
- public async override Task CreateAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
+ public override async Task CreateAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
@@ -173,7 +173,7 @@ protected Task SaveChanges(CancellationToken cancellationToken)
/// The user to update.
/// The used to propagate notifications that the operation should be canceled.
/// The that represents the asynchronous operation, containing the of the update operation.
- public async override Task UpdateAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
+ public override async Task UpdateAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
@@ -202,7 +202,7 @@ protected Task SaveChanges(CancellationToken cancellationToken)
/// The user to delete.
/// The used to propagate notifications that the operation should be canceled.
/// The that represents the asynchronous operation, containing the of the update operation.
- public async override Task DeleteAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
+ public override async Task DeleteAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
@@ -329,7 +329,7 @@ protected override Task FindUserLoginAsync(string loginProvider, str
/// The role to add.
/// The used to propagate notifications that the operation should be canceled.
/// The that represents the asynchronous operation.
- public async override Task AddToRoleAsync(TUser user, string normalizedRoleName, CancellationToken cancellationToken = default(CancellationToken))
+ public override async Task AddToRoleAsync(TUser user, string normalizedRoleName, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
@@ -356,7 +356,7 @@ protected override Task FindUserLoginAsync(string loginProvider, str
/// The role to remove.
/// The used to propagate notifications that the operation should be canceled.
/// The that represents the asynchronous operation.
- public async override Task RemoveFromRoleAsync(TUser user, string normalizedRoleName, CancellationToken cancellationToken = default(CancellationToken))
+ public override async Task RemoveFromRoleAsync(TUser user, string normalizedRoleName, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
@@ -436,7 +436,7 @@ where userRole.UserId.Equals(userId)
/// The user whose claims should be retrieved.
/// The used to propagate notifications that the operation should be canceled.
/// A that contains the claims granted to a user.
- public async override Task> GetClaimsAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
+ public override async Task> GetClaimsAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
if (user == null)
@@ -480,7 +480,7 @@ where userRole.UserId.Equals(userId)
/// The new claim replacing the .
/// The used to propagate notifications that the operation should be canceled.
/// The that represents the asynchronous operation.
- public async override Task ReplaceClaimAsync(TUser user, Claim claim, Claim newClaim, CancellationToken cancellationToken = default(CancellationToken))
+ public override async Task ReplaceClaimAsync(TUser user, Claim claim, Claim newClaim, CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
if (user == null)
@@ -511,7 +511,7 @@ where userRole.UserId.Equals(userId)
/// The claim to remove.
/// The used to propagate notifications that the operation should be canceled.
/// The that represents the asynchronous operation.
- public async override Task RemoveClaimsAsync(TUser user, IEnumerable claims, CancellationToken cancellationToken = default(CancellationToken))
+ public override async Task RemoveClaimsAsync(TUser user, IEnumerable claims, CancellationToken cancellationToken = default(CancellationToken))
{
ThrowIfDisposed();
if (user == null)
@@ -588,7 +588,7 @@ public override async Task RemoveLoginAsync(TUser user, string loginProvider, st
///
/// The for the asynchronous operation, containing a list of for the specified , if any.
///
- public async override Task> GetLoginsAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
+ public override async Task> GetLoginsAsync(TUser user, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
@@ -610,7 +610,7 @@ public override async Task RemoveLoginAsync(TUser user, string loginProvider, st
///
/// The for the asynchronous operation, containing the user, if any which matched the specified login provider and key.
///
- public async override Task FindByLoginAsync(string loginProvider, string providerKey,
+ public override async Task FindByLoginAsync(string loginProvider, string providerKey,
CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
@@ -647,7 +647,7 @@ public async override Task FindByLoginAsync(string loginProvider, string
///
/// The contains a list of users, if any, that contain the specified claim.
///
- public async override Task> GetUsersForClaimAsync(Claim claim, CancellationToken cancellationToken = default(CancellationToken))
+ public override async Task> GetUsersForClaimAsync(Claim claim, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
@@ -673,7 +673,7 @@ join user in Users on userclaims.UserId equals user.Id
///
/// The contains a list of users, if any, that are in the specified role.
///
- public async override Task> GetUsersInRoleAsync(string normalizedRoleName, CancellationToken cancellationToken = default(CancellationToken))
+ public override async Task> GetUsersInRoleAsync(string normalizedRoleName, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
diff --git a/src/Identity/EntityFrameworkCore/test/EF.InMemory.Test/InMemoryContext.cs b/src/Identity/EntityFrameworkCore/test/EF.InMemory.Test/InMemoryContext.cs
index 04d58d31bf56..b24e71993114 100644
--- a/src/Identity/EntityFrameworkCore/test/EF.InMemory.Test/InMemoryContext.cs
+++ b/src/Identity/EntityFrameworkCore/test/EF.InMemory.Test/InMemoryContext.cs
@@ -14,7 +14,7 @@ public class InMemoryContext :
private InMemoryContext(DbConnection connection) : base(connection)
{ }
- public new static InMemoryContext Create(DbConnection connection)
+ public static new InMemoryContext Create(DbConnection connection)
=> Initialize(new InMemoryContext(connection));
public static TContext Initialize(TContext context) where TContext : DbContext
diff --git a/src/Identity/Extensions.Core/src/AuthenticatorTokenProvider.cs b/src/Identity/Extensions.Core/src/AuthenticatorTokenProvider.cs
index 5e7d850f012e..c58ec9fcb8c6 100644
--- a/src/Identity/Extensions.Core/src/AuthenticatorTokenProvider.cs
+++ b/src/Identity/Extensions.Core/src/AuthenticatorTokenProvider.cs
@@ -18,7 +18,7 @@ public class AuthenticatorTokenProvider : IUserTwoFactorTokenProviderThe to retrieve the from.
/// The to check for the possibility of generating a two-factor authentication token.
/// True if the user has an authenticator key set, otherwise false.
- public async virtual Task CanGenerateTwoFactorTokenAsync(UserManager manager, TUser user)
+ public virtual async Task CanGenerateTwoFactorTokenAsync(UserManager manager, TUser user)
{
var key = await manager.GetAuthenticatorKeyAsync(user);
diff --git a/src/Identity/Extensions.Core/src/DefaultUserConfirmation.cs b/src/Identity/Extensions.Core/src/DefaultUserConfirmation.cs
index 925c5e745228..c3b344965b81 100644
--- a/src/Identity/Extensions.Core/src/DefaultUserConfirmation.cs
+++ b/src/Identity/Extensions.Core/src/DefaultUserConfirmation.cs
@@ -17,7 +17,7 @@ public class DefaultUserConfirmation : IUserConfirmation where TUs
/// The that can be used to retrieve user properties.
/// The user.
/// The that represents the asynchronous operation, containing the of the confirmation operation.
- public async virtual Task IsConfirmedAsync(UserManager manager, TUser user)
+ public virtual async Task IsConfirmedAsync(UserManager manager, TUser user)
{
return await manager.IsEmailConfirmedAsync(user);
}
diff --git a/src/Identity/Extensions.Core/src/IdentityResult.cs b/src/Identity/Extensions.Core/src/IdentityResult.cs
index e137dcd4283a..17a23ee56c07 100644
--- a/src/Identity/Extensions.Core/src/IdentityResult.cs
+++ b/src/Identity/Extensions.Core/src/IdentityResult.cs
@@ -14,7 +14,7 @@ namespace Microsoft.AspNetCore.Identity
public class IdentityResult
{
private static readonly IdentityResult _success = new IdentityResult { Succeeded = true };
- private List _errors = new List();
+ private readonly List _errors = new List();
///
/// Flag indicating whether if the operation succeeded or not.
diff --git a/src/Identity/Extensions.Core/src/UserManager.cs b/src/Identity/Extensions.Core/src/UserManager.cs
index 778a35900d07..374c5646a046 100644
--- a/src/Identity/Extensions.Core/src/UserManager.cs
+++ b/src/Identity/Extensions.Core/src/UserManager.cs
@@ -45,7 +45,7 @@ public class UserManager : IDisposable where TUser : class
#if NETSTANDARD2_0 || NET461
private static readonly RandomNumberGenerator _rng = RandomNumberGenerator.Create();
#endif
- private IServiceProvider _services;
+ private readonly IServiceProvider _services;
///
/// The cancellation token used to cancel operations.
diff --git a/src/Identity/Extensions.Stores/src/UserStoreBase.cs b/src/Identity/Extensions.Stores/src/UserStoreBase.cs
index 4031f2d35294..5eea2d16f729 100644
--- a/src/Identity/Extensions.Stores/src/UserStoreBase.cs
+++ b/src/Identity/Extensions.Stores/src/UserStoreBase.cs
@@ -446,7 +446,7 @@ public void Dispose()
///
/// The for the asynchronous operation, containing the user, if any which matched the specified login provider and key.
///
- public async virtual Task FindByLoginAsync(string loginProvider, string providerKey,
+ public virtual async Task FindByLoginAsync(string loginProvider, string providerKey,
CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
diff --git a/src/Identity/Specification.Tests/src/UserManagerSpecificationTests.cs b/src/Identity/Specification.Tests/src/UserManagerSpecificationTests.cs
index a0749b0f366b..60e039eb4ee0 100644
--- a/src/Identity/Specification.Tests/src/UserManagerSpecificationTests.cs
+++ b/src/Identity/Specification.Tests/src/UserManagerSpecificationTests.cs
@@ -932,7 +932,7 @@ public async Task CanFindByEmail()
///
/// Task
[Fact]
- public async virtual Task CanFindUsersViaUserQuerable()
+ public virtual async Task CanFindUsersViaUserQuerable()
{
var mgr = CreateManager();
if (mgr.SupportsQueryableUsers)
diff --git a/src/Identity/UI/src/Areas/Identity/Pages/V4/Account/Manage/ResetAuthenticator.cshtml.cs b/src/Identity/UI/src/Areas/Identity/Pages/V4/Account/Manage/ResetAuthenticator.cshtml.cs
index 52d1c38e0a92..dfced82d0d71 100644
--- a/src/Identity/UI/src/Areas/Identity/Pages/V4/Account/Manage/ResetAuthenticator.cshtml.cs
+++ b/src/Identity/UI/src/Areas/Identity/Pages/V4/Account/Manage/ResetAuthenticator.cshtml.cs
@@ -38,9 +38,9 @@ public abstract class ResetAuthenticatorModel : PageModel
internal class ResetAuthenticatorModel : ResetAuthenticatorModel where TUser : class
{
- UserManager _userManager;
+ readonly UserManager _userManager;
private readonly SignInManager _signInManager;
- ILogger _logger;
+ readonly ILogger _logger;
public ResetAuthenticatorModel(
UserManager userManager,
diff --git a/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/TaskGenericsUtil.cs b/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/TaskGenericsUtil.cs
index b5bf93724b77..2bf3aa092f0a 100644
--- a/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/TaskGenericsUtil.cs
+++ b/src/JSInterop/Microsoft.JSInterop/src/Infrastructure/TaskGenericsUtil.cs
@@ -10,10 +10,10 @@ namespace Microsoft.JSInterop.Infrastructure
{
internal static class TaskGenericsUtil
{
- private static ConcurrentDictionary _cachedResultGetters
+ private static readonly ConcurrentDictionary _cachedResultGetters
= new ConcurrentDictionary();
- private static ConcurrentDictionary _cachedResultSetters
+ private static readonly ConcurrentDictionary _cachedResultSetters
= new ConcurrentDictionary();
public static void SetTaskCompletionSourceResult(object taskCompletionSource, object? result)
diff --git a/src/JSInterop/Microsoft.JSInterop/test/Infrastructure/DotNetDispatcherTest.cs b/src/JSInterop/Microsoft.JSInterop/test/Infrastructure/DotNetDispatcherTest.cs
index 4ed6c12438a8..1e32fdac70a7 100644
--- a/src/JSInterop/Microsoft.JSInterop/test/Infrastructure/DotNetDispatcherTest.cs
+++ b/src/JSInterop/Microsoft.JSInterop/test/Infrastructure/DotNetDispatcherTest.cs
@@ -12,7 +12,7 @@ namespace Microsoft.JSInterop.Infrastructure
{
public class DotNetDispatcherTest
{
- private readonly static string thisAssemblyName = typeof(DotNetDispatcherTest).Assembly.GetName().Name;
+ private static readonly string thisAssemblyName = typeof(DotNetDispatcherTest).Assembly.GetName().Name;
[Fact]
public void CannotInvokeWithEmptyAssemblyName()
diff --git a/src/Localization/Abstractions/src/StringLocalizerOfT.cs b/src/Localization/Abstractions/src/StringLocalizerOfT.cs
index 0f30ca6c877e..2db647a2c2fd 100644
--- a/src/Localization/Abstractions/src/StringLocalizerOfT.cs
+++ b/src/Localization/Abstractions/src/StringLocalizerOfT.cs
@@ -13,7 +13,7 @@ namespace Microsoft.Extensions.Localization
/// The to provide strings for.
public class StringLocalizer : IStringLocalizer
{
- private IStringLocalizer _localizer;
+ private readonly IStringLocalizer _localizer;
///
/// Creates a new .
diff --git a/src/Middleware/ConcurrencyLimiter/perf/Microbenchmarks/QueueFullOverhead.cs b/src/Middleware/ConcurrencyLimiter/perf/Microbenchmarks/QueueFullOverhead.cs
index 64be1430641c..45c372582549 100644
--- a/src/Middleware/ConcurrencyLimiter/perf/Microbenchmarks/QueueFullOverhead.cs
+++ b/src/Middleware/ConcurrencyLimiter/perf/Microbenchmarks/QueueFullOverhead.cs
@@ -13,7 +13,7 @@ public class QueueFullOverhead
{
private const int _numRequests = 2000;
private int _requestCount = 0;
- private ManualResetEventSlim _mres = new ManualResetEventSlim();
+ private readonly ManualResetEventSlim _mres = new ManualResetEventSlim();
private ConcurrencyLimiterMiddleware _middlewareQueue;
private ConcurrencyLimiterMiddleware _middlewareStack;
diff --git a/src/Middleware/ConcurrencyLimiter/perf/Microbenchmarks/QueueRequestsOverwritten.cs b/src/Middleware/ConcurrencyLimiter/perf/Microbenchmarks/QueueRequestsOverwritten.cs
index 9d16fe0739b5..eadc0ab7ff30 100644
--- a/src/Middleware/ConcurrencyLimiter/perf/Microbenchmarks/QueueRequestsOverwritten.cs
+++ b/src/Middleware/ConcurrencyLimiter/perf/Microbenchmarks/QueueRequestsOverwritten.cs
@@ -12,9 +12,9 @@ namespace Microsoft.AspNetCore.ConcurrencyLimiter.Microbenchmarks
public class QueueRequestsOverwritten
{
private const int _numRejects = 5000;
- private int _queueLength = 20;
+ private readonly int _queueLength = 20;
private int _rejectionCount = 0;
- private ManualResetEventSlim _mres = new ManualResetEventSlim();
+ private readonly ManualResetEventSlim _mres = new ManualResetEventSlim();
private ConcurrencyLimiterMiddleware _middlewareQueue;
private ConcurrencyLimiterMiddleware _middlewareStack;
diff --git a/src/Middleware/ConcurrencyLimiter/test/PolicyTests/ResettableBooleanCompletionSourceTests.cs b/src/Middleware/ConcurrencyLimiter/test/PolicyTests/ResettableBooleanCompletionSourceTests.cs
index 79d36edfc4ca..5051549db9a6 100644
--- a/src/Middleware/ConcurrencyLimiter/test/PolicyTests/ResettableBooleanCompletionSourceTests.cs
+++ b/src/Middleware/ConcurrencyLimiter/test/PolicyTests/ResettableBooleanCompletionSourceTests.cs
@@ -11,10 +11,10 @@ namespace Microsoft.AspNetCore.ConcurrencyLimiter.Tests.PolicyTests
{
public static class ResettableBooleanCompletionSourceTests
{
- private static StackPolicy _testQueue = TestUtils.CreateStackPolicy(8);
+ private static readonly StackPolicy _testQueue = TestUtils.CreateStackPolicy(8);
[Fact]
- public async static void CanBeAwaitedMultipleTimes()
+ public static async Task CanBeAwaitedMultipleTimes()
{
var tcs = new ResettableBooleanCompletionSource(_testQueue);
@@ -32,7 +32,7 @@ public async static void CanBeAwaitedMultipleTimes()
}
[Fact]
- public async static void CanSetResultToTrue()
+ public static async Task CanSetResultToTrue()
{
var tcs = new ResettableBooleanCompletionSource(_testQueue);
@@ -46,7 +46,7 @@ public async static void CanSetResultToTrue()
}
[Fact]
- public async static void CanSetResultToFalse()
+ public static async Task CanSetResultToFalse()
{
var tcs = new ResettableBooleanCompletionSource(_testQueue);
diff --git a/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/DatabaseErrorPageMiddlewareTest.cs b/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/DatabaseErrorPageMiddlewareTest.cs
index 549240cfc853..f6d72a6d1c77 100644
--- a/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/DatabaseErrorPageMiddlewareTest.cs
+++ b/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/DatabaseErrorPageMiddlewareTest.cs
@@ -553,13 +553,13 @@ private static async Task SetupServer(SqlTestStore
return host;
}
- private static UrlEncoder _urlEncoder = UrlEncoder.Default;
+ private static readonly UrlEncoder _urlEncoder = UrlEncoder.Default;
private static string UrlEncode(string content)
{
return _urlEncoder.Encode(content);
}
- private static JavaScriptEncoder _javaScriptEncoder = JavaScriptEncoder.Default;
+ private static readonly JavaScriptEncoder _javaScriptEncoder = JavaScriptEncoder.Default;
private static string JavaScriptEncode(string content)
{
return _javaScriptEncoder.Encode(content);
diff --git a/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/Helpers/TestLoggerProvider.cs b/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/Helpers/TestLoggerProvider.cs
index 1abb3989cddc..0044360b21f7 100644
--- a/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/Helpers/TestLoggerProvider.cs
+++ b/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/Helpers/TestLoggerProvider.cs
@@ -27,9 +27,9 @@ public void Dispose()
public class TestLogger : ILogger
{
- private List _messages = new List();
+ private readonly List _messages = new List();
- private object _sync = new object();
+ private readonly object _sync = new object();
public IEnumerable Messages
{
diff --git a/src/Middleware/HeaderPropagation/src/HeaderPropagationValues.cs b/src/Middleware/HeaderPropagation/src/HeaderPropagationValues.cs
index 6be18702edae..a13eb65ee734 100644
--- a/src/Middleware/HeaderPropagation/src/HeaderPropagationValues.cs
+++ b/src/Middleware/HeaderPropagation/src/HeaderPropagationValues.cs
@@ -14,7 +14,7 @@ namespace Microsoft.AspNetCore.HeaderPropagation
///
public class HeaderPropagationValues
{
- private readonly static AsyncLocal?> _headers = new AsyncLocal?>();
+ private static readonly AsyncLocal?> _headers = new AsyncLocal?>();
///
/// Gets or sets the headers values collected by the from the current request
diff --git a/src/Middleware/HttpLogging/src/RequestBufferingStream.cs b/src/Middleware/HttpLogging/src/RequestBufferingStream.cs
index 7165f355a278..07b5688c9f99 100644
--- a/src/Middleware/HttpLogging/src/RequestBufferingStream.cs
+++ b/src/Middleware/HttpLogging/src/RequestBufferingStream.cs
@@ -16,7 +16,7 @@ namespace Microsoft.AspNetCore.HttpLogging
{
internal sealed class RequestBufferingStream : BufferingStream
{
- private Encoding _encoding;
+ private readonly Encoding _encoding;
private readonly int _limit;
public bool HasLogged { get; private set; }
diff --git a/src/Middleware/HttpLogging/test/W3CLoggerTests.cs b/src/Middleware/HttpLogging/test/W3CLoggerTests.cs
index 5e8539e71896..6d6d2b329ceb 100644
--- a/src/Middleware/HttpLogging/test/W3CLoggerTests.cs
+++ b/src/Middleware/HttpLogging/test/W3CLoggerTests.cs
@@ -19,8 +19,7 @@ namespace Microsoft.AspNetCore.HttpLogging
{
public class W3CLoggerTests
{
-
- DateTime _timestampOne = new DateTime(2021, 01, 02, 03, 04, 05);
+ readonly DateTime _timestampOne = new DateTime(2021, 01, 02, 03, 04, 05);
[Fact]
public async Task WritesDateTime()
diff --git a/src/Middleware/HttpOverrides/src/CertificateForwardingFeature.cs b/src/Middleware/HttpOverrides/src/CertificateForwardingFeature.cs
index f5abc1e59c41..280177d8deb7 100644
--- a/src/Middleware/HttpOverrides/src/CertificateForwardingFeature.cs
+++ b/src/Middleware/HttpOverrides/src/CertificateForwardingFeature.cs
@@ -13,9 +13,9 @@ namespace Microsoft.AspNetCore.HttpOverrides
{
internal class CertificateForwardingFeature : ITlsConnectionFeature
{
- private ILogger _logger;
- private StringValues _header;
- private CertificateForwardingOptions _options;
+ private readonly ILogger _logger;
+ private readonly StringValues _header;
+ private readonly CertificateForwardingOptions _options;
private X509Certificate2? _certificate;
public CertificateForwardingFeature(ILogger logger, StringValues header, CertificateForwardingOptions options)
diff --git a/src/Middleware/HttpOverrides/src/LoggingExtensions.cs b/src/Middleware/HttpOverrides/src/LoggingExtensions.cs
index 61f2f1b51fe9..e713f7e7ece7 100644
--- a/src/Middleware/HttpOverrides/src/LoggingExtensions.cs
+++ b/src/Middleware/HttpOverrides/src/LoggingExtensions.cs
@@ -7,7 +7,7 @@ namespace Microsoft.Extensions.Logging
{
internal static class LoggingExtensions
{
- private static Action _noCertificate;
+ private static readonly Action _noCertificate;
static LoggingExtensions()
{
diff --git a/src/Middleware/ResponseCaching/test/SegmentWriteStreamTests.cs b/src/Middleware/ResponseCaching/test/SegmentWriteStreamTests.cs
index 251b7e8777d6..03706ab121c3 100644
--- a/src/Middleware/ResponseCaching/test/SegmentWriteStreamTests.cs
+++ b/src/Middleware/ResponseCaching/test/SegmentWriteStreamTests.cs
@@ -10,7 +10,7 @@ namespace Microsoft.AspNetCore.ResponseCaching.Tests
{
public class SegmentWriteStreamTests
{
- private static byte[] WriteData = new byte[]
+ private static readonly byte[] WriteData = new byte[]
{
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14
};
diff --git a/src/Middleware/ResponseCompression/test/ResponseCompressionMiddlewareTest.cs b/src/Middleware/ResponseCompression/test/ResponseCompressionMiddlewareTest.cs
index 1632d16c6524..8c60d8540f84 100644
--- a/src/Middleware/ResponseCompression/test/ResponseCompressionMiddlewareTest.cs
+++ b/src/Middleware/ResponseCompression/test/ResponseCompressionMiddlewareTest.cs
@@ -1326,7 +1326,7 @@ public EncodingTestData(string encodingName, int expectedBodyLength)
private class NoSyncWrapperStream : Stream
{
- private Stream _body;
+ private readonly Stream _body;
public NoSyncWrapperStream(Stream body)
{
diff --git a/src/Middleware/Rewrite/src/ApacheModRewrite/RuleBuilder.cs b/src/Middleware/Rewrite/src/ApacheModRewrite/RuleBuilder.cs
index ab7e50d681f9..b09b82d641a2 100644
--- a/src/Middleware/Rewrite/src/ApacheModRewrite/RuleBuilder.cs
+++ b/src/Middleware/Rewrite/src/ApacheModRewrite/RuleBuilder.cs
@@ -17,7 +17,7 @@ internal class RuleBuilder
private IList? _conditions;
internal IList _actions = new List();
private UrlMatch? _match;
- private CookieActionFactory _cookieActionFactory = new CookieActionFactory();
+ private readonly CookieActionFactory _cookieActionFactory = new CookieActionFactory();
private readonly TimeSpan _regexTimeout = TimeSpan.FromSeconds(1);
diff --git a/src/Middleware/Rewrite/src/BackReferenceCollection.cs b/src/Middleware/Rewrite/src/BackReferenceCollection.cs
index 439946129b4b..602942de752e 100644
--- a/src/Middleware/Rewrite/src/BackReferenceCollection.cs
+++ b/src/Middleware/Rewrite/src/BackReferenceCollection.cs
@@ -9,7 +9,7 @@ namespace Microsoft.AspNetCore.Rewrite
{
internal class BackReferenceCollection
{
- private List _backReferences = new List();
+ private readonly List _backReferences = new List();
public BackReferenceCollection(GroupCollection references)
{
diff --git a/src/Middleware/Session/src/DistributedSession.cs b/src/Middleware/Session/src/DistributedSession.cs
index 356fb4464695..f3839f009e8f 100644
--- a/src/Middleware/Session/src/DistributedSession.cs
+++ b/src/Middleware/Session/src/DistributedSession.cs
@@ -35,7 +35,7 @@ public class DistributedSession : ISession
private bool _isModified;
private bool _loaded;
private bool _isAvailable;
- private bool _isNewSessionKey;
+ private readonly bool _isNewSessionKey;
private string? _sessionId;
private byte[]? _sessionIdBytes;
diff --git a/src/Middleware/Session/src/LoggingExtensions.cs b/src/Middleware/Session/src/LoggingExtensions.cs
index 2d36b21c129c..b103ba37a4c0 100644
--- a/src/Middleware/Session/src/LoggingExtensions.cs
+++ b/src/Middleware/Session/src/LoggingExtensions.cs
@@ -7,19 +7,19 @@ namespace Microsoft.Extensions.Logging
{
internal static class LoggingExtensions
{
- private static Action _errorClosingTheSession;
- private static Action _accessingExpiredSession;
- private static Action _sessionStarted;
- private static Action _sessionLoaded;
- private static Action _sessionStored;
- private static Action _sessionCacheReadException;
- private static Action _errorUnprotectingCookie;
- private static Action _sessionLoadingTimeout;
- private static Action _sessionCommitTimeout;
- private static Action _sessionCommitCanceled;
- private static Action _sessionRefreshTimeout;
- private static Action _sessionRefreshCanceled;
- private static Action _sessionNotAvailable;
+ private static readonly Action _errorClosingTheSession;
+ private static readonly Action _accessingExpiredSession;
+ private static readonly Action _sessionStarted;
+ private static readonly Action _sessionLoaded;
+ private static readonly Action _sessionStored;
+ private static readonly Action _sessionCacheReadException;
+ private static readonly Action _errorUnprotectingCookie;
+ private static readonly Action _sessionLoadingTimeout;
+ private static readonly Action _sessionCommitTimeout;
+ private static readonly Action _sessionCommitCanceled;
+ private static readonly Action _sessionRefreshTimeout;
+ private static readonly Action _sessionRefreshCanceled;
+ private static readonly Action _sessionNotAvailable;
static LoggingExtensions()
{
diff --git a/src/Middleware/Spa/SpaServices.Extensions/src/AngularCli/AngularCliBuilder.cs b/src/Middleware/Spa/SpaServices.Extensions/src/AngularCli/AngularCliBuilder.cs
index f23382691f1a..8be7bbfa2267 100644
--- a/src/Middleware/Spa/SpaServices.Extensions/src/AngularCli/AngularCliBuilder.cs
+++ b/src/Middleware/Spa/SpaServices.Extensions/src/AngularCli/AngularCliBuilder.cs
@@ -23,7 +23,7 @@ namespace Microsoft.AspNetCore.SpaServices.AngularCli
[Obsolete("Prerendering is no longer supported out of box")]
public class AngularCliBuilder : ISpaPrerendererBuilder
{
- private static TimeSpan RegexMatchTimeout = TimeSpan.FromSeconds(5); // This is a development-time only feature, so a very long timeout is fine
+ private static readonly TimeSpan RegexMatchTimeout = TimeSpan.FromSeconds(5); // This is a development-time only feature, so a very long timeout is fine
private readonly string _scriptName;
diff --git a/src/Middleware/Spa/SpaServices.Extensions/src/AngularCli/AngularCliMiddleware.cs b/src/Middleware/Spa/SpaServices.Extensions/src/AngularCli/AngularCliMiddleware.cs
index 159531b6c7b6..cc89d6b492a2 100644
--- a/src/Middleware/Spa/SpaServices.Extensions/src/AngularCli/AngularCliMiddleware.cs
+++ b/src/Middleware/Spa/SpaServices.Extensions/src/AngularCli/AngularCliMiddleware.cs
@@ -22,7 +22,7 @@ namespace Microsoft.AspNetCore.SpaServices.AngularCli
internal static class AngularCliMiddleware
{
private const string LogCategoryName = "Microsoft.AspNetCore.SpaServices";
- private static TimeSpan RegexMatchTimeout = TimeSpan.FromSeconds(5); // This is a development-time only feature, so a very long timeout is fine
+ private static readonly TimeSpan RegexMatchTimeout = TimeSpan.FromSeconds(5); // This is a development-time only feature, so a very long timeout is fine
public static void Attach(
ISpaBuilder spaBuilder,
diff --git a/src/Middleware/Spa/SpaServices.Extensions/src/Npm/NodeScriptRunner.cs b/src/Middleware/Spa/SpaServices.Extensions/src/Npm/NodeScriptRunner.cs
index 60a4ae6f96b3..49766eaf9ae8 100644
--- a/src/Middleware/Spa/SpaServices.Extensions/src/Npm/NodeScriptRunner.cs
+++ b/src/Middleware/Spa/SpaServices.Extensions/src/Npm/NodeScriptRunner.cs
@@ -22,7 +22,7 @@ internal class NodeScriptRunner : IDisposable
public EventedStreamReader StdOut { get; }
public EventedStreamReader StdErr { get; }
- private static Regex AnsiColorRegex = new Regex("\x001b\\[[0-9;]*m", RegexOptions.None, TimeSpan.FromSeconds(1));
+ private static readonly Regex AnsiColorRegex = new Regex("\x001b\\[[0-9;]*m", RegexOptions.None, TimeSpan.FromSeconds(1));
public NodeScriptRunner(string workingDirectory, string scriptName, string? arguments, IDictionary? envVars, string pkgManagerCommand, DiagnosticSource diagnosticSource, CancellationToken applicationStoppingToken)
{
diff --git a/src/Middleware/Spa/SpaServices.Extensions/src/ReactDevelopmentServer/ReactDevelopmentServerMiddleware.cs b/src/Middleware/Spa/SpaServices.Extensions/src/ReactDevelopmentServer/ReactDevelopmentServerMiddleware.cs
index 59248e271ebb..ecb6fc7e4ac8 100644
--- a/src/Middleware/Spa/SpaServices.Extensions/src/ReactDevelopmentServer/ReactDevelopmentServerMiddleware.cs
+++ b/src/Middleware/Spa/SpaServices.Extensions/src/ReactDevelopmentServer/ReactDevelopmentServerMiddleware.cs
@@ -23,7 +23,7 @@ namespace Microsoft.AspNetCore.SpaServices.ReactDevelopmentServer
internal static class ReactDevelopmentServerMiddleware
{
private const string LogCategoryName = "Microsoft.AspNetCore.SpaServices";
- private static TimeSpan RegexMatchTimeout = TimeSpan.FromSeconds(5); // This is a development-time only feature, so a very long timeout is fine
+ private static readonly TimeSpan RegexMatchTimeout = TimeSpan.FromSeconds(5); // This is a development-time only feature, so a very long timeout is fine
public static void Attach(
ISpaBuilder spaBuilder,
diff --git a/src/Middleware/Spa/SpaServices.Extensions/src/StaticFiles/DefaultSpaStaticFileProvider.cs b/src/Middleware/Spa/SpaServices.Extensions/src/StaticFiles/DefaultSpaStaticFileProvider.cs
index b28dac6fa575..cdd2ac8c3cfa 100644
--- a/src/Middleware/Spa/SpaServices.Extensions/src/StaticFiles/DefaultSpaStaticFileProvider.cs
+++ b/src/Middleware/Spa/SpaServices.Extensions/src/StaticFiles/DefaultSpaStaticFileProvider.cs
@@ -15,7 +15,7 @@ namespace Microsoft.AspNetCore.SpaServices.StaticFiles
///
internal class DefaultSpaStaticFileProvider : ISpaStaticFileProvider
{
- private IFileProvider? _fileProvider;
+ private readonly IFileProvider? _fileProvider;
public DefaultSpaStaticFileProvider(
IServiceProvider serviceProvider,
diff --git a/src/Middleware/Spa/SpaServices.Extensions/src/Util/EventedStreamStringReader.cs b/src/Middleware/Spa/SpaServices.Extensions/src/Util/EventedStreamStringReader.cs
index efe7c72efa26..d69d236ad853 100644
--- a/src/Middleware/Spa/SpaServices.Extensions/src/Util/EventedStreamStringReader.cs
+++ b/src/Middleware/Spa/SpaServices.Extensions/src/Util/EventedStreamStringReader.cs
@@ -12,9 +12,9 @@ namespace Microsoft.AspNetCore.NodeServices.Util
///
internal class EventedStreamStringReader : IDisposable
{
- private EventedStreamReader _eventedStreamReader;
+ private readonly EventedStreamReader _eventedStreamReader;
private bool _isDisposed;
- private StringBuilder _stringBuilder = new StringBuilder();
+ private readonly StringBuilder _stringBuilder = new StringBuilder();
public EventedStreamStringReader(EventedStreamReader eventedStreamReader)
{
diff --git a/src/Middleware/WebSockets/test/ConformanceTests/Autobahn/AutobahnExpectations.cs b/src/Middleware/WebSockets/test/ConformanceTests/Autobahn/AutobahnExpectations.cs
index ea0667cf7783..f1dbf67495a3 100644
--- a/src/Middleware/WebSockets/test/ConformanceTests/Autobahn/AutobahnExpectations.cs
+++ b/src/Middleware/WebSockets/test/ConformanceTests/Autobahn/AutobahnExpectations.cs
@@ -7,7 +7,7 @@ namespace Microsoft.AspNetCore.WebSockets.ConformanceTest.Autobahn
{
public class AutobahnExpectations
{
- private Dictionary _expectations = new Dictionary();
+ private readonly Dictionary _expectations = new Dictionary();
public bool Ssl { get; }
public ServerType Server { get; }
public string Environment { get; }
diff --git a/src/Middleware/WebSockets/test/ConformanceTests/Autobahn/Wstest.cs b/src/Middleware/WebSockets/test/ConformanceTests/Autobahn/Wstest.cs
index 775b00d4ab17..f02f23b231d4 100644
--- a/src/Middleware/WebSockets/test/ConformanceTests/Autobahn/Wstest.cs
+++ b/src/Middleware/WebSockets/test/ConformanceTests/Autobahn/Wstest.cs
@@ -8,7 +8,7 @@ namespace Microsoft.AspNetCore.WebSockets.ConformanceTest.Autobahn
///
public class Wstest : Executable
{
- private static Lazy _instance = new Lazy(Create);
+ private static readonly Lazy _instance = new Lazy(Create);
public static readonly string DefaultLocation = LocateWstest();
diff --git a/src/Middleware/WebSockets/test/UnitTests/BufferStream.cs b/src/Middleware/WebSockets/test/UnitTests/BufferStream.cs
index ce7fd2f411b1..5f18539bdf1f 100644
--- a/src/Middleware/WebSockets/test/UnitTests/BufferStream.cs
+++ b/src/Middleware/WebSockets/test/UnitTests/BufferStream.cs
@@ -18,10 +18,10 @@ public class BufferStream : Stream
private bool _aborted;
private bool _terminated;
private Exception _abortException;
- private ConcurrentQueue _bufferedData;
+ private readonly ConcurrentQueue _bufferedData;
private ArraySegment _topBuffer;
- private SemaphoreSlim _readLock;
- private SemaphoreSlim _writeLock;
+ private readonly SemaphoreSlim _readLock;
+ private readonly SemaphoreSlim _writeLock;
private TaskCompletionSource _readWaitingForData;
internal BufferStream()
@@ -165,7 +165,7 @@ public override int EndRead(IAsyncResult asyncResult)
return base.EndRead(asyncResult);
}
- public async override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
+ public override async Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (_terminated)
{
diff --git a/src/Middleware/perf/Microbenchmarks/HandshakeBenchmark.cs b/src/Middleware/perf/Microbenchmarks/HandshakeBenchmark.cs
index ba736578b090..9e2872475553 100644
--- a/src/Middleware/perf/Microbenchmarks/HandshakeBenchmark.cs
+++ b/src/Middleware/perf/Microbenchmarks/HandshakeBenchmark.cs
@@ -7,7 +7,7 @@ namespace Microsoft.AspNetCore.WebSockets.Microbenchmarks
{
public class HandshakeBenchmark
{
- private string[] _requestKeys = {
+ private readonly string[] _requestKeys = {
"F8/qpj9RYr2/sIymdDvlmw==",
"PyQi8nyMkKnI7JKiAJ/IrA==",
"CUe0z8ItSBRtgJlPqP1+SQ==",
diff --git a/src/Mvc/Mvc.Analyzers/test/AvoidHtmlPartialAnalyzerTest.cs b/src/Mvc/Mvc.Analyzers/test/AvoidHtmlPartialAnalyzerTest.cs
index cac606e97cde..98bc7807155c 100644
--- a/src/Mvc/Mvc.Analyzers/test/AvoidHtmlPartialAnalyzerTest.cs
+++ b/src/Mvc/Mvc.Analyzers/test/AvoidHtmlPartialAnalyzerTest.cs
@@ -1,4 +1,4 @@
-// Copyright (c) .NET Foundation. All rights reserved.
+// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Runtime.CompilerServices;
@@ -11,7 +11,7 @@ namespace Microsoft.AspNetCore.Mvc.Analyzers
{
public class AvoidHtmlPartialAnalyzerTest
{
- private static DiagnosticDescriptor DiagnosticDescriptor = DiagnosticDescriptors.MVC1000_HtmlHelperPartialShouldBeAvoided;
+ private static readonly DiagnosticDescriptor DiagnosticDescriptor = DiagnosticDescriptors.MVC1000_HtmlHelperPartialShouldBeAvoided;
private MvcDiagnosticAnalyzerRunner Executor { get; } = new MvcDiagnosticAnalyzerRunner(new AvoidHtmlPartialAnalyzer());
diff --git a/src/Mvc/Mvc.Analyzers/test/Mvc.Analyzers.Test.csproj b/src/Mvc/Mvc.Analyzers/test/Mvc.Analyzers.Test.csproj
index 0d2fecc2724b..f6b53b9ce7e4 100644
--- a/src/Mvc/Mvc.Analyzers/test/Mvc.Analyzers.Test.csproj
+++ b/src/Mvc/Mvc.Analyzers/test/Mvc.Analyzers.Test.csproj
@@ -1,9 +1,10 @@
-
+
$(DefaultNetCoreTargetFramework)
true
Microsoft.AspNetCore.Mvc.Analyzers
+ false
diff --git a/src/Mvc/Mvc.Core/test/ApplicationModels/ControllerActionDescriptorProviderTests.cs b/src/Mvc/Mvc.Core/test/ApplicationModels/ControllerActionDescriptorProviderTests.cs
index 1b4b93e2686f..14c92815126c 100644
--- a/src/Mvc/Mvc.Core/test/ApplicationModels/ControllerActionDescriptorProviderTests.cs
+++ b/src/Mvc/Mvc.Core/test/ApplicationModels/ControllerActionDescriptorProviderTests.cs
@@ -1953,7 +1953,7 @@ public void A()
private class ApiExplorerIsVisibleConvention : IApplicationModelConvention
{
- private bool _isVisible;
+ private readonly bool _isVisible;
public ApiExplorerIsVisibleConvention(bool isVisible)
{
diff --git a/src/Mvc/Mvc.Core/test/Filters/MiddlewareFilterTest.cs b/src/Mvc/Mvc.Core/test/Filters/MiddlewareFilterTest.cs
index 0ddfbe40e5ae..ce90ff26bcdb 100644
--- a/src/Mvc/Mvc.Core/test/Filters/MiddlewareFilterTest.cs
+++ b/src/Mvc/Mvc.Core/test/Filters/MiddlewareFilterTest.cs
@@ -345,7 +345,7 @@ private static IServiceCollection CreateServices()
private class MockControllerFactory
{
- private object _controller;
+ private readonly object _controller;
public MockControllerFactory(object controller)
{
@@ -415,7 +415,7 @@ public TestControllerActionInvoker(
public MockControllerFactory ControllerFactory { get; }
- public async override Task InvokeAsync()
+ public override async Task InvokeAsync()
{
await base.InvokeAsync();
diff --git a/src/Mvc/Mvc.Core/test/ModelBinding/Validation/DefaultComplexObjectValidationStrategyTest.cs b/src/Mvc/Mvc.Core/test/ModelBinding/Validation/DefaultComplexObjectValidationStrategyTest.cs
index ed4cb6ad4280..bf565f90ad9e 100644
--- a/src/Mvc/Mvc.Core/test/ModelBinding/Validation/DefaultComplexObjectValidationStrategyTest.cs
+++ b/src/Mvc/Mvc.Core/test/ModelBinding/Validation/DefaultComplexObjectValidationStrategyTest.cs
@@ -141,7 +141,7 @@ private class Person
private class LazyPerson
{
- private string _string;
+ private readonly string _string;
public LazyPerson(string input)
{
diff --git a/src/Mvc/Mvc.Core/test/Routing/ActionEndpointDataSourceBaseTest.cs b/src/Mvc/Mvc.Core/test/Routing/ActionEndpointDataSourceBaseTest.cs
index c620abf1612c..9371c6592e41 100644
--- a/src/Mvc/Mvc.Core/test/Routing/ActionEndpointDataSourceBaseTest.cs
+++ b/src/Mvc/Mvc.Core/test/Routing/ActionEndpointDataSourceBaseTest.cs
@@ -128,7 +128,7 @@ public void Endpoints_ChangeTokenTriggered_EndpointsRecreated()
});
}
- protected private ActionEndpointDataSourceBase CreateDataSource(IActionDescriptorCollectionProvider actions = null)
+ private protected ActionEndpointDataSourceBase CreateDataSource(IActionDescriptorCollectionProvider actions = null)
{
if (actions == null)
{
@@ -154,7 +154,7 @@ protected private ActionEndpointDataSourceBase CreateDataSource(IActionDescripto
return CreateDataSource(actions, endpointFactory);
}
- protected private abstract ActionEndpointDataSourceBase CreateDataSource(IActionDescriptorCollectionProvider actions, ActionEndpointFactory endpointFactory);
+ private protected abstract ActionEndpointDataSourceBase CreateDataSource(IActionDescriptorCollectionProvider actions, ActionEndpointFactory endpointFactory);
private class UpperCaseParameterTransform : IOutboundParameterTransformer
{
diff --git a/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonPatchInputFormatter.cs b/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonPatchInputFormatter.cs
index 793bbe014e59..2238175d8939 100644
--- a/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonPatchInputFormatter.cs
+++ b/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonPatchInputFormatter.cs
@@ -61,7 +61,7 @@ public override InputFormatterExceptionPolicy ExceptionPolicy
}
///
- public async override Task ReadRequestBodyAsync(
+ public override async Task ReadRequestBodyAsync(
InputFormatterContext context,
Encoding encoding)
{
diff --git a/src/Mvc/Mvc.Razor.RuntimeCompilation/src/FileProviderRazorProjectItem.cs b/src/Mvc/Mvc.Razor.RuntimeCompilation/src/FileProviderRazorProjectItem.cs
index 935921c90c8a..506e8c8f74de 100644
--- a/src/Mvc/Mvc.Razor.RuntimeCompilation/src/FileProviderRazorProjectItem.cs
+++ b/src/Mvc/Mvc.Razor.RuntimeCompilation/src/FileProviderRazorProjectItem.cs
@@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation
///
public class FileProviderRazorProjectItem : RazorProjectItem
{
- private string _root;
+ private readonly string _root;
private string? _relativePhysicalPath;
private bool _isRelativePhysicalPathSet;
diff --git a/src/Mvc/Mvc.Razor/test/TagHelpers/TagHelperComponentTagHelperTest.cs b/src/Mvc/Mvc.Razor/test/TagHelpers/TagHelperComponentTagHelperTest.cs
index 80741ef6cd7b..66bca4062fa4 100644
--- a/src/Mvc/Mvc.Razor/test/TagHelpers/TagHelperComponentTagHelperTest.cs
+++ b/src/Mvc/Mvc.Razor/test/TagHelpers/TagHelperComponentTagHelperTest.cs
@@ -368,7 +368,7 @@ public Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
private class TestAddTagHelperComponent : ITagHelperComponent
{
- private int _order;
+ private readonly int _order;
public TestAddTagHelperComponent(int order)
{
diff --git a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageRouteTransformerConvention.cs b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageRouteTransformerConvention.cs
index 2bec75388751..f16a8b18fa0f 100644
--- a/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageRouteTransformerConvention.cs
+++ b/src/Mvc/Mvc.RazorPages/src/ApplicationModels/PageRouteTransformerConvention.cs
@@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Mvc.ApplicationModels
///
public class PageRouteTransformerConvention : IPageRouteModelConvention
{
- private IOutboundParameterTransformer _parameterTransformer;
+ private readonly IOutboundParameterTransformer _parameterTransformer;
///
/// Creates a new instance of with the specified .
diff --git a/src/Mvc/Mvc.RazorPages/src/PageContext.cs b/src/Mvc/Mvc.RazorPages/src/PageContext.cs
index 2ca4ad8280ba..3f6f827bd828 100644
--- a/src/Mvc/Mvc.RazorPages/src/PageContext.cs
+++ b/src/Mvc/Mvc.RazorPages/src/PageContext.cs
@@ -41,7 +41,7 @@ public PageContext(ActionContext actionContext)
///
/// Gets or sets the .
///
- public virtual new CompiledPageActionDescriptor ActionDescriptor
+ public new virtual CompiledPageActionDescriptor ActionDescriptor
{
get => _actionDescriptor!;
set
diff --git a/src/Mvc/Mvc.TagHelpers/src/ComponentTagHelper.cs b/src/Mvc/Mvc.TagHelpers/src/ComponentTagHelper.cs
index d9cebc65dfec..c8ae79793756 100644
--- a/src/Mvc/Mvc.TagHelpers/src/ComponentTagHelper.cs
+++ b/src/Mvc/Mvc.TagHelpers/src/ComponentTagHelper.cs
@@ -83,7 +83,7 @@ public RenderMode RenderMode
}
///
- public async override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
+ public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
if (context == null)
{
diff --git a/src/Mvc/Mvc.TagHelpers/test/TestableHtmlGenerator.cs b/src/Mvc/Mvc.TagHelpers/test/TestableHtmlGenerator.cs
index 174240d203f6..ade416916a8f 100644
--- a/src/Mvc/Mvc.TagHelpers/test/TestableHtmlGenerator.cs
+++ b/src/Mvc/Mvc.TagHelpers/test/TestableHtmlGenerator.cs
@@ -23,7 +23,7 @@ namespace Microsoft.AspNetCore.Mvc.TagHelpers
{
public class TestableHtmlGenerator : DefaultHtmlGenerator
{
- private IDictionary _validationAttributes;
+ private readonly IDictionary _validationAttributes;
public TestableHtmlGenerator(IModelMetadataProvider metadataProvider)
: this(metadataProvider, Mock.Of())
diff --git a/src/Mvc/Mvc.TagHelpers/test/ValidationSummaryTagHelperTest.cs b/src/Mvc/Mvc.TagHelpers/test/ValidationSummaryTagHelperTest.cs
index cba2243af436..194633d8f7d2 100644
--- a/src/Mvc/Mvc.TagHelpers/test/ValidationSummaryTagHelperTest.cs
+++ b/src/Mvc/Mvc.TagHelpers/test/ValidationSummaryTagHelperTest.cs
@@ -694,7 +694,7 @@ private class Model
private class FormMetadata : IEnumerable
{
- private List _fields = new List();
+ private readonly List _fields = new List();
public int ID { get; set; }
diff --git a/src/Mvc/Mvc.ViewFeatures/src/RazorComponents/StaticComponentRenderer.cs b/src/Mvc/Mvc.ViewFeatures/src/RazorComponents/StaticComponentRenderer.cs
index 8f620d4c5487..b256bb4cc00d 100644
--- a/src/Mvc/Mvc.ViewFeatures/src/RazorComponents/StaticComponentRenderer.cs
+++ b/src/Mvc/Mvc.ViewFeatures/src/RazorComponents/StaticComponentRenderer.cs
@@ -18,8 +18,8 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures
internal class StaticComponentRenderer
{
private Task _initialized;
- private HtmlRenderer _renderer;
- private object _lock = new();
+ private readonly HtmlRenderer _renderer;
+ private readonly object _lock = new();
public StaticComponentRenderer(HtmlRenderer renderer)
{
diff --git a/src/Mvc/Mvc.ViewFeatures/test/CookieTempDataProviderTest.cs b/src/Mvc/Mvc.ViewFeatures/test/CookieTempDataProviderTest.cs
index db0d0e3a8a25..8cfd3dbe88e5 100644
--- a/src/Mvc/Mvc.ViewFeatures/test/CookieTempDataProviderTest.cs
+++ b/src/Mvc/Mvc.ViewFeatures/test/CookieTempDataProviderTest.cs
@@ -370,7 +370,7 @@ private void UpdateRequestWithCookies(HttpContext httpContext)
private class MockResponseCookieCollection : IResponseCookies, IEnumerable
{
- private Dictionary _cookies = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ private readonly Dictionary _cookies = new Dictionary(StringComparer.OrdinalIgnoreCase);
public int Count
{
diff --git a/src/Mvc/Mvc.ViewFeatures/test/RazorComponents/ComponentRendererTest.cs b/src/Mvc/Mvc.ViewFeatures/test/RazorComponents/ComponentRendererTest.cs
index b7b364fc29a7..ad98ad233585 100644
--- a/src/Mvc/Mvc.ViewFeatures/test/RazorComponents/ComponentRendererTest.cs
+++ b/src/Mvc/Mvc.ViewFeatures/test/RazorComponents/ComponentRendererTest.cs
@@ -1012,7 +1012,7 @@ protected override void BuildRenderTree(RenderTreeBuilder builder)
private class AsyncComponent : ComponentBase
{
- private static WeatherRow[] _weatherData = new[]
+ private static readonly WeatherRow[] _weatherData = new[]
{
new WeatherRow
{
diff --git a/src/Mvc/Mvc.ViewFeatures/test/Rendering/HtmlHelperNameExtensionsTest.cs b/src/Mvc/Mvc.ViewFeatures/test/Rendering/HtmlHelperNameExtensionsTest.cs
index 25d43e0fe039..e419a43cfb92 100644
--- a/src/Mvc/Mvc.ViewFeatures/test/Rendering/HtmlHelperNameExtensionsTest.cs
+++ b/src/Mvc/Mvc.ViewFeatures/test/Rendering/HtmlHelperNameExtensionsTest.cs
@@ -18,13 +18,13 @@ namespace Microsoft.AspNetCore.Mvc.Core
///
public class HtmlHelperNameExtensionsTest
{
- private static List _staticCollection = new List();
- private static int _staticIndex = 6;
+ private static readonly List _staticCollection = new List();
+ private static readonly int _staticIndex = 6;
- private List _collection = new List();
- private int _index = 7;
- private List _nestedCollection = new List();
- private string _string = string.Empty;
+ private readonly List _collection = new List();
+ private readonly int _index = 7;
+ private readonly List _nestedCollection = new List();
+ private readonly string _string = string.Empty;
private static List StaticCollection { get; }
diff --git a/src/Mvc/Mvc.ViewFeatures/test/SessionStateTempDataProviderTest.cs b/src/Mvc/Mvc.ViewFeatures/test/SessionStateTempDataProviderTest.cs
index 47db8ef2bc1e..778b225e9b25 100644
--- a/src/Mvc/Mvc.ViewFeatures/test/SessionStateTempDataProviderTest.cs
+++ b/src/Mvc/Mvc.ViewFeatures/test/SessionStateTempDataProviderTest.cs
@@ -104,7 +104,7 @@ private class SessionFeature : ISessionFeature
private class TestSession : ISession
{
- private Dictionary _innerDictionary = new Dictionary();
+ private readonly Dictionary _innerDictionary = new Dictionary();
public IEnumerable Keys { get { return _innerDictionary.Keys; } }
diff --git a/src/Mvc/Mvc.ViewFeatures/test/TempDataDictionaryTest.cs b/src/Mvc/Mvc.ViewFeatures/test/TempDataDictionaryTest.cs
index cf16b46aac4e..efaf67473018 100644
--- a/src/Mvc/Mvc.ViewFeatures/test/TempDataDictionaryTest.cs
+++ b/src/Mvc/Mvc.ViewFeatures/test/TempDataDictionaryTest.cs
@@ -194,7 +194,7 @@ public void SaveTempData(HttpContext context, IDictionary values
private class TestTempDataProvider : ITempDataProvider
{
- private IDictionary _data;
+ private readonly IDictionary _data;
public TestTempDataProvider(IDictionary data)
{
diff --git a/src/Mvc/Mvc.ViewFeatures/test/ViewComponentTests.cs b/src/Mvc/Mvc.ViewFeatures/test/ViewComponentTests.cs
index 05a99dbb164b..8c91ab5e0516 100644
--- a/src/Mvc/Mvc.ViewFeatures/test/ViewComponentTests.cs
+++ b/src/Mvc/Mvc.ViewFeatures/test/ViewComponentTests.cs
@@ -270,7 +270,7 @@ private class SessionFeature : ISessionFeature
private class TestSession : ISession
{
- private Dictionary _innerDictionary = new Dictionary();
+ private readonly Dictionary _innerDictionary = new Dictionary();
public IEnumerable Keys { get { return _innerDictionary.Keys; } }
diff --git a/src/Mvc/shared/Mvc.Core.TestCommon/NonSeekableReadableStream.cs b/src/Mvc/shared/Mvc.Core.TestCommon/NonSeekableReadableStream.cs
index 62be4fc02b7b..8dcb8043bf27 100644
--- a/src/Mvc/shared/Mvc.Core.TestCommon/NonSeekableReadableStream.cs
+++ b/src/Mvc/shared/Mvc.Core.TestCommon/NonSeekableReadableStream.cs
@@ -10,7 +10,7 @@ namespace Microsoft.AspNetCore.Mvc
{
public class NonSeekableReadStream : Stream
{
- private Stream _inner;
+ private readonly Stream _inner;
private readonly bool _allowSyncReads;
public NonSeekableReadStream(byte[] data, bool allowSyncReads = true)
diff --git a/src/Mvc/shared/Mvc.Core.TestCommon/TestModelMetadataProvider.cs b/src/Mvc/shared/Mvc.Core.TestCommon/TestModelMetadataProvider.cs
index 43aa7e1d2817..636c2234f601 100644
--- a/src/Mvc/shared/Mvc.Core.TestCommon/TestModelMetadataProvider.cs
+++ b/src/Mvc/shared/Mvc.Core.TestCommon/TestModelMetadataProvider.cs
@@ -186,9 +186,9 @@ public interface IMetadataBuilder
private class MetadataBuilder : IMetadataBuilder
{
- private List> _bindingActions = new List>();
- private List> _displayActions = new List>();
- private List> _validationActions = new List>();
+ private readonly List> _bindingActions = new List>();
+ private readonly List> _displayActions = new List>();
+ private readonly List> _validationActions = new List>();
private readonly ModelMetadataIdentity _key;
diff --git a/src/Mvc/test/Mvc.FunctionalTests/ConsumesAttributeEndpointRoutingTests.cs b/src/Mvc/test/Mvc.FunctionalTests/ConsumesAttributeEndpointRoutingTests.cs
index 2165e03f8338..b1fbc55077a0 100644
--- a/src/Mvc/test/Mvc.FunctionalTests/ConsumesAttributeEndpointRoutingTests.cs
+++ b/src/Mvc/test/Mvc.FunctionalTests/ConsumesAttributeEndpointRoutingTests.cs
@@ -16,7 +16,7 @@ public ConsumesAttributeEndpointRoutingTests(MvcTestFixture
public static readonly bool GenerateBaselines = false;
- private static object writeLock = new object();
+ private static readonly object writeLock = new object();
public static void UpdateOrVerify(Assembly assembly, string outputFile, string expectedContent, string responseContent, string token = null)
{
diff --git a/src/Mvc/test/Mvc.FunctionalTests/RequestServicesEndpointRoutingTest.cs b/src/Mvc/test/Mvc.FunctionalTests/RequestServicesEndpointRoutingTest.cs
index e386705bc060..e61ce738458d 100644
--- a/src/Mvc/test/Mvc.FunctionalTests/RequestServicesEndpointRoutingTest.cs
+++ b/src/Mvc/test/Mvc.FunctionalTests/RequestServicesEndpointRoutingTest.cs
@@ -17,7 +17,7 @@ public RequestServicesEndpointRoutingTest(MvcTestFixture f
}
[Fact]
- public async override Task HasEndpointMatch()
+ public override async Task HasEndpointMatch()
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/Routing/HasEndpointMatch");
diff --git a/src/Mvc/test/Mvc.FunctionalTests/RequestServicesTest.cs b/src/Mvc/test/Mvc.FunctionalTests/RequestServicesTest.cs
index 31f2843fb490..dbb89b33c552 100644
--- a/src/Mvc/test/Mvc.FunctionalTests/RequestServicesTest.cs
+++ b/src/Mvc/test/Mvc.FunctionalTests/RequestServicesTest.cs
@@ -16,7 +16,7 @@ public RequestServicesTest(MvcTestFixture
}
[Fact]
- public async override Task HasEndpointMatch()
+ public override async Task HasEndpointMatch()
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/Routing/HasEndpointMatch");
@@ -47,7 +47,7 @@ public override async Task AttributeRoutedAction_MultipleRouteAttributes_RouteAt
}
[Fact]
- public async override Task RouteData_Routers_ConventionalRoute()
+ public override async Task RouteData_Routers_ConventionalRoute()
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/RouteData/Conventional");
@@ -69,7 +69,7 @@ public async override Task RouteData_Routers_ConventionalRoute()
}
[Fact]
- public async override Task RouteData_Routers_AttributeRoute()
+ public override async Task RouteData_Routers_AttributeRoute()
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/RouteData/Attribute");
diff --git a/src/Mvc/test/Mvc.FunctionalTests/VersioningEndpointRoutingTests.cs b/src/Mvc/test/Mvc.FunctionalTests/VersioningEndpointRoutingTests.cs
index 890fcce2fc83..50564a05ad89 100644
--- a/src/Mvc/test/Mvc.FunctionalTests/VersioningEndpointRoutingTests.cs
+++ b/src/Mvc/test/Mvc.FunctionalTests/VersioningEndpointRoutingTests.cs
@@ -17,7 +17,7 @@ public VersioningEndpointRoutingTests(MvcTestFixture
}
[Fact]
- public async override Task HasEndpointMatch()
+ public override async Task HasEndpointMatch()
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/Routing/HasEndpointMatch");
diff --git a/src/Mvc/test/Mvc.FunctionalTests/VersioningTests.cs b/src/Mvc/test/Mvc.FunctionalTests/VersioningTests.cs
index 4efc0561a4c8..94d3b075d37f 100644
--- a/src/Mvc/test/Mvc.FunctionalTests/VersioningTests.cs
+++ b/src/Mvc/test/Mvc.FunctionalTests/VersioningTests.cs
@@ -16,7 +16,7 @@ public VersioningTests(MvcTestFixture : ICollection
{
- private ICollection _original;
+ private readonly ICollection _original;
public CustomReadOnlyCollection()
: this(new List())
diff --git a/src/Mvc/test/Mvc.IntegrationTests/ComplexRecordIntegrationTest.cs b/src/Mvc/test/Mvc.IntegrationTests/ComplexRecordIntegrationTest.cs
index f533be281214..14448ce988d9 100644
--- a/src/Mvc/test/Mvc.IntegrationTests/ComplexRecordIntegrationTest.cs
+++ b/src/Mvc/test/Mvc.IntegrationTests/ComplexRecordIntegrationTest.cs
@@ -3028,7 +3028,7 @@ private record TestInnerModel([ModelBinder(BinderType = typeof(NumberModelBinder
private class NumberModelBinder : IModelBinder
{
private readonly NumberStyles _supportedStyles = NumberStyles.Float | NumberStyles.AllowThousands;
- private DecimalModelBinder _innerBinder;
+ private readonly DecimalModelBinder _innerBinder;
public NumberModelBinder(ILoggerFactory loggerFactory)
{
diff --git a/src/Mvc/test/Mvc.IntegrationTests/ComplexTypeIntegrationTestBase.cs b/src/Mvc/test/Mvc.IntegrationTests/ComplexTypeIntegrationTestBase.cs
index b2ffbcc4c4e2..ed18ca10a706 100644
--- a/src/Mvc/test/Mvc.IntegrationTests/ComplexTypeIntegrationTestBase.cs
+++ b/src/Mvc/test/Mvc.IntegrationTests/ComplexTypeIntegrationTestBase.cs
@@ -3243,7 +3243,7 @@ private class TestInnerModel
private class NumberModelBinder : IModelBinder
{
private readonly NumberStyles _supportedStyles = NumberStyles.Float | NumberStyles.AllowThousands;
- private DecimalModelBinder _innerBinder;
+ private readonly DecimalModelBinder _innerBinder;
public NumberModelBinder(ILoggerFactory loggerFactory)
{
diff --git a/src/Mvc/test/Mvc.IntegrationTests/TryUpdateModelIntegrationTest.cs b/src/Mvc/test/Mvc.IntegrationTests/TryUpdateModelIntegrationTest.cs
index 1e5ebffeaf87..64c13b17e2f2 100644
--- a/src/Mvc/test/Mvc.IntegrationTests/TryUpdateModelIntegrationTest.cs
+++ b/src/Mvc/test/Mvc.IntegrationTests/TryUpdateModelIntegrationTest.cs
@@ -1296,7 +1296,7 @@ private void UpdateRequest(HttpRequest request, string data, string name)
private class CustomReadOnlyCollection : ICollection
{
- private ICollection _original;
+ private readonly ICollection _original;
public CustomReadOnlyCollection()
: this(new List())
diff --git a/src/Mvc/test/WebSites/ApplicationModelWebSite/Conventions/ActionDescriptionAttribute.cs b/src/Mvc/test/WebSites/ApplicationModelWebSite/Conventions/ActionDescriptionAttribute.cs
index 1056bddb1eaa..07df2be3ec04 100644
--- a/src/Mvc/test/WebSites/ApplicationModelWebSite/Conventions/ActionDescriptionAttribute.cs
+++ b/src/Mvc/test/WebSites/ApplicationModelWebSite/Conventions/ActionDescriptionAttribute.cs
@@ -9,7 +9,7 @@ namespace ApplicationModelWebSite
{
public class ActionDescriptionAttribute : Attribute, IActionModelConvention
{
- private object _value;
+ private readonly object _value;
public ActionDescriptionAttribute(object value)
{
diff --git a/src/Mvc/test/WebSites/ApplicationModelWebSite/Conventions/ApplicationDescription.cs b/src/Mvc/test/WebSites/ApplicationModelWebSite/Conventions/ApplicationDescription.cs
index 39f982706301..69835063769a 100644
--- a/src/Mvc/test/WebSites/ApplicationModelWebSite/Conventions/ApplicationDescription.cs
+++ b/src/Mvc/test/WebSites/ApplicationModelWebSite/Conventions/ApplicationDescription.cs
@@ -8,7 +8,7 @@ namespace ApplicationModelWebSite
{
public class ApplicationDescription : IApplicationModelConvention
{
- private string _description;
+ private readonly string _description;
public ApplicationDescription(string description)
{
diff --git a/src/Mvc/test/WebSites/ApplicationModelWebSite/Conventions/ControllerDescriptionAttribute.cs b/src/Mvc/test/WebSites/ApplicationModelWebSite/Conventions/ControllerDescriptionAttribute.cs
index 20109b08ad71..8a1e98647d34 100644
--- a/src/Mvc/test/WebSites/ApplicationModelWebSite/Conventions/ControllerDescriptionAttribute.cs
+++ b/src/Mvc/test/WebSites/ApplicationModelWebSite/Conventions/ControllerDescriptionAttribute.cs
@@ -8,7 +8,7 @@ namespace ApplicationModelWebSite
{
public class ControllerDescriptionAttribute : Attribute, IControllerModelConvention
{
- private object _value;
+ private readonly object _value;
public ControllerDescriptionAttribute(object value)
{
diff --git a/src/Mvc/test/WebSites/BasicWebSite/Controllers/AsyncActionsController.cs b/src/Mvc/test/WebSites/BasicWebSite/Controllers/AsyncActionsController.cs
index b9a5b688535b..a870daab5167 100644
--- a/src/Mvc/test/WebSites/BasicWebSite/Controllers/AsyncActionsController.cs
+++ b/src/Mvc/test/WebSites/BasicWebSite/Controllers/AsyncActionsController.cs
@@ -199,7 +199,7 @@ public CustomAwaitable(int simulateDelayMilliseconds, T result)
public class CustomAwaiter : INotifyCompletion
{
- private IList _continuations = new List();
+ private readonly IList _continuations = new List();
public CustomAwaiter(int simulateDelayMilliseconds)
{
diff --git a/src/Mvc/test/WebSites/BasicWebSite/Controllers/RazorComponentsController.cs b/src/Mvc/test/WebSites/BasicWebSite/Controllers/RazorComponentsController.cs
index 2af557a16075..6b094048387c 100644
--- a/src/Mvc/test/WebSites/BasicWebSite/Controllers/RazorComponentsController.cs
+++ b/src/Mvc/test/WebSites/BasicWebSite/Controllers/RazorComponentsController.cs
@@ -8,7 +8,7 @@ namespace BasicWebSite.Controllers
{
public class RazorComponentsController : Controller
{
- private static WeatherRow[] _weatherData = new[]
+ private static readonly WeatherRow[] _weatherData = new[]
{
new WeatherRow
{
diff --git a/src/Mvc/test/WebSites/BasicWebSite/Controllers/TestingController.cs b/src/Mvc/test/WebSites/BasicWebSite/Controllers/TestingController.cs
index 167d29e89dfd..bf9a2cf5c535 100644
--- a/src/Mvc/test/WebSites/BasicWebSite/Controllers/TestingController.cs
+++ b/src/Mvc/test/WebSites/BasicWebSite/Controllers/TestingController.cs
@@ -72,8 +72,8 @@ public IActionResult RedirectHandlerStatusCode303()
public class RedirectUsingStatusCode : ActionResult
{
- private string _url;
- private HttpStatusCode _statusCode;
+ private readonly string _url;
+ private readonly HttpStatusCode _statusCode;
public RedirectUsingStatusCode(string url, HttpStatusCode statusCode)
{
diff --git a/src/Mvc/test/WebSites/BasicWebSite/Conventions/ApplicationDescription.cs b/src/Mvc/test/WebSites/BasicWebSite/Conventions/ApplicationDescription.cs
index 88bf1f27e2ee..682eefac88fc 100644
--- a/src/Mvc/test/WebSites/BasicWebSite/Conventions/ApplicationDescription.cs
+++ b/src/Mvc/test/WebSites/BasicWebSite/Conventions/ApplicationDescription.cs
@@ -7,7 +7,7 @@ namespace BasicWebSite
{
public class ApplicationDescription : IApplicationModelConvention
{
- private string _description;
+ private readonly string _description;
public ApplicationDescription(string description)
{
diff --git a/src/Mvc/test/WebSites/ControllersFromServicesWebSite/TagHelpers/InServicesTagHelper.cs b/src/Mvc/test/WebSites/ControllersFromServicesWebSite/TagHelpers/InServicesTagHelper.cs
index 778bb1724d9a..dcb6be2efdda 100644
--- a/src/Mvc/test/WebSites/ControllersFromServicesWebSite/TagHelpers/InServicesTagHelper.cs
+++ b/src/Mvc/test/WebSites/ControllersFromServicesWebSite/TagHelpers/InServicesTagHelper.cs
@@ -9,7 +9,7 @@ namespace ControllersFromServicesWebSite.TagHelpers
[HtmlTargetElement("InServices")]
public class InServicesTagHelper : TagHelper
{
- private ValueService _value;
+ private readonly ValueService _value;
public InServicesTagHelper(ValueService value)
{
diff --git a/src/Mvc/test/WebSites/GenericHostWebSite/Controllers/TestingController.cs b/src/Mvc/test/WebSites/GenericHostWebSite/Controllers/TestingController.cs
index b79e078d19c7..9a35c53cdbf3 100644
--- a/src/Mvc/test/WebSites/GenericHostWebSite/Controllers/TestingController.cs
+++ b/src/Mvc/test/WebSites/GenericHostWebSite/Controllers/TestingController.cs
@@ -72,8 +72,8 @@ public IActionResult RedirectHandlerStatusCode303()
public class RedirectUsingStatusCode : ActionResult
{
- private string _url;
- private HttpStatusCode _statusCode;
+ private readonly string _url;
+ private readonly HttpStatusCode _statusCode;
public RedirectUsingStatusCode(string url, HttpStatusCode statusCode)
{
diff --git a/src/Mvc/test/WebSites/RazorWebSite/Services/TestBodyTagHelperComponent.cs b/src/Mvc/test/WebSites/RazorWebSite/Services/TestBodyTagHelperComponent.cs
index 750dd61d20a3..f83a7b6cf1c9 100644
--- a/src/Mvc/test/WebSites/RazorWebSite/Services/TestBodyTagHelperComponent.cs
+++ b/src/Mvc/test/WebSites/RazorWebSite/Services/TestBodyTagHelperComponent.cs
@@ -11,8 +11,8 @@ namespace RazorWebSite
{
public class TestBodyTagHelperComponent : ITagHelperComponent
{
- private int _order;
- private string _html;
+ private readonly int _order;
+ private readonly string _html;
public TestBodyTagHelperComponent() : this(1, "")
{
diff --git a/src/Mvc/test/WebSites/VersioningWebSite/Controllers/AddressController.cs b/src/Mvc/test/WebSites/VersioningWebSite/Controllers/AddressController.cs
index 245699dfa880..bd3f40ac4e18 100644
--- a/src/Mvc/test/WebSites/VersioningWebSite/Controllers/AddressController.cs
+++ b/src/Mvc/test/WebSites/VersioningWebSite/Controllers/AddressController.cs
@@ -10,7 +10,7 @@ namespace VersioningWebSite
// Same template overlapping version sets disambiguated by order.
public class AddressController : Controller
{
- private TestResponseGenerator _generator;
+ private readonly TestResponseGenerator _generator;
public AddressController(TestResponseGenerator generator)
{
diff --git a/src/ProjectTemplates/BlazorTemplates.Tests/BlazorTemplateTest.cs b/src/ProjectTemplates/BlazorTemplates.Tests/BlazorTemplateTest.cs
index 121960ee852c..de296b9d254e 100644
--- a/src/ProjectTemplates/BlazorTemplates.Tests/BlazorTemplateTest.cs
+++ b/src/ProjectTemplates/BlazorTemplates.Tests/BlazorTemplateTest.cs
@@ -43,12 +43,12 @@ public ITestOutputHelper Output
return _output;
}
}
-
+
public abstract string ProjectType { get; }
private static readonly bool _isCIEnvironment =
!string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("ContinuousIntegrationBuild"));
- protected async override Task InitializeCoreAsync(TestContext context)
+ protected override async Task InitializeCoreAsync(TestContext context)
{
BrowserManager = await BrowserManager.CreateAsync(CreateConfiguration(), LoggerFactory);
BrowserContextInfo = new ContextInformation(LoggerFactory);
diff --git a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X/src/ViewComponentTagHelperPass.cs b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X/src/ViewComponentTagHelperPass.cs
index ba9938a1238e..91865fc75d06 100644
--- a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X/src/ViewComponentTagHelperPass.cs
+++ b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X/src/ViewComponentTagHelperPass.cs
@@ -146,7 +146,7 @@ private void AddTagHelperClass(Context context, TagHelperDescriptor tagHelper)
private struct Context
{
- private Dictionary _tagHelpers;
+ private readonly Dictionary _tagHelpers;
public Context(NamespaceDeclarationIntermediateNode @namespace, ClassDeclarationIntermediateNode @class)
{
diff --git a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X/test/IntegrationTests/CodeGenerationIntegrationTest.cs b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X/test/IntegrationTests/CodeGenerationIntegrationTest.cs
index 86eb6afc0ddd..e4144fe7184f 100644
--- a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X/test/IntegrationTests/CodeGenerationIntegrationTest.cs
+++ b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X/test/IntegrationTests/CodeGenerationIntegrationTest.cs
@@ -11,7 +11,7 @@ namespace Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X.IntegrationTests
{
public class CodeGenerationIntegrationTest : IntegrationTestBase
{
- private readonly static CSharpCompilation DefaultBaseCompilation = MvcShim.BaseCompilation.WithAssemblyName("AppCode");
+ private static readonly CSharpCompilation DefaultBaseCompilation = MvcShim.BaseCompilation.WithAssemblyName("AppCode");
public CodeGenerationIntegrationTest()
: base(generateBaselines: null, projectDirectoryHint: "Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X")
diff --git a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X/test/ModelDirectiveTest.cs b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X/test/ModelDirectiveTest.cs
index 7a4c811dbdad..0cb572a8a8a8 100644
--- a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X/test/ModelDirectiveTest.cs
+++ b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X/test/ModelDirectiveTest.cs
@@ -320,7 +320,7 @@ public override void VisitNamespaceDeclaration(NamespaceDeclarationIntermediateN
private class DesignTimeOptionsFeature : IConfigureRazorParserOptionsFeature, IConfigureRazorCodeGenerationOptionsFeature
{
- private bool _designTime;
+ private readonly bool _designTime;
public DesignTimeOptionsFeature(bool designTime)
{
diff --git a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/src/ViewComponentTagHelperPass.cs b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/src/ViewComponentTagHelperPass.cs
index f5c37eb13b08..81c21566fc2c 100644
--- a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/src/ViewComponentTagHelperPass.cs
+++ b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/src/ViewComponentTagHelperPass.cs
@@ -146,7 +146,7 @@ private void AddTagHelperClass(Context context, TagHelperDescriptor tagHelper)
private struct Context
{
- private Dictionary _tagHelpers;
+ private readonly Dictionary _tagHelpers;
public Context(NamespaceDeclarationIntermediateNode @namespace, ClassDeclarationIntermediateNode @class)
{
diff --git a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/test/IntegrationTests/CodeGenerationIntegrationTest.cs b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/test/IntegrationTests/CodeGenerationIntegrationTest.cs
index 0fa87ec5f795..5bc78e055000 100644
--- a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/test/IntegrationTests/CodeGenerationIntegrationTest.cs
+++ b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/test/IntegrationTests/CodeGenerationIntegrationTest.cs
@@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X.IntegrationTests
{
public class CodeGenerationIntegrationTest : IntegrationTestBase
{
- private readonly static CSharpCompilation DefaultBaseCompilation = MvcShim.BaseCompilation.WithAssemblyName("AppCode");
+ private static readonly CSharpCompilation DefaultBaseCompilation = MvcShim.BaseCompilation.WithAssemblyName("AppCode");
public CodeGenerationIntegrationTest()
: base(generateBaselines: null, projectDirectoryHint: "Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X")
diff --git a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/test/IntegrationTests/InstrumentationPassIntegrationTest.cs b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/test/IntegrationTests/InstrumentationPassIntegrationTest.cs
index 4a4e752c3735..36611468a368 100644
--- a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/test/IntegrationTests/InstrumentationPassIntegrationTest.cs
+++ b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/test/IntegrationTests/InstrumentationPassIntegrationTest.cs
@@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X.IntegrationTests
{
public class InstrumentationPassIntegrationTest : IntegrationTestBase
{
- private readonly static CSharpCompilation DefaultBaseCompilation = MvcShim.BaseCompilation.WithAssemblyName("AppCode");
+ private static readonly CSharpCompilation DefaultBaseCompilation = MvcShim.BaseCompilation.WithAssemblyName("AppCode");
public InstrumentationPassIntegrationTest()
: base(generateBaselines: null, projectDirectoryHint: "Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X")
diff --git a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/test/ModelDirectiveTest.cs b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/test/ModelDirectiveTest.cs
index d01195906be4..e20876455ef4 100644
--- a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/test/ModelDirectiveTest.cs
+++ b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X/test/ModelDirectiveTest.cs
@@ -318,7 +318,7 @@ public override void VisitNamespaceDeclaration(NamespaceDeclarationIntermediateN
private class DesignTimeOptionsFeature : IConfigureRazorParserOptionsFeature, IConfigureRazorCodeGenerationOptionsFeature
{
- private bool _designTime;
+ private readonly bool _designTime;
public DesignTimeOptionsFeature(bool designTime)
{
diff --git a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/src/MvcViewDocumentClassifierPass.cs b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/src/MvcViewDocumentClassifierPass.cs
index 9d5c43b1ab44..91378d632ff3 100644
--- a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/src/MvcViewDocumentClassifierPass.cs
+++ b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/src/MvcViewDocumentClassifierPass.cs
@@ -10,7 +10,7 @@ namespace Microsoft.AspNetCore.Mvc.Razor.Extensions
{
public class MvcViewDocumentClassifierPass : DocumentClassifierPassBase
{
- private bool _useConsolidatedMvcViews;
+ private readonly bool _useConsolidatedMvcViews;
public static readonly string MvcViewDocumentKind = "mvc.1.0.view";
diff --git a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/src/RazorPageDocumentClassifierPass.cs b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/src/RazorPageDocumentClassifierPass.cs
index 06752cf93a0d..65eed6f8554b 100644
--- a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/src/RazorPageDocumentClassifierPass.cs
+++ b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/src/RazorPageDocumentClassifierPass.cs
@@ -12,7 +12,7 @@ namespace Microsoft.AspNetCore.Mvc.Razor.Extensions
{
public class RazorPageDocumentClassifierPass : DocumentClassifierPassBase
{
- private bool _useConsolidatedMvcViews;
+ private readonly bool _useConsolidatedMvcViews;
public static readonly string RazorPageDocumentKind = "mvc.1.0.razor-page";
public static readonly string RouteTemplateKey = "RouteTemplate";
diff --git a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/src/ViewComponentTagHelperPass.cs b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/src/ViewComponentTagHelperPass.cs
index 0c3b14563e52..9292ae75cc6b 100644
--- a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/src/ViewComponentTagHelperPass.cs
+++ b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/src/ViewComponentTagHelperPass.cs
@@ -146,7 +146,7 @@ private void AddTagHelperClass(Context context, TagHelperDescriptor tagHelper)
private struct Context
{
- private Dictionary _tagHelpers;
+ private readonly Dictionary _tagHelpers;
public Context(NamespaceDeclarationIntermediateNode @namespace, ClassDeclarationIntermediateNode @class)
{
diff --git a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/test/IntegrationTests/CodeGenerationIntegrationTest.cs b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/test/IntegrationTests/CodeGenerationIntegrationTest.cs
index 3386060adb7b..edfe250ed16b 100644
--- a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/test/IntegrationTests/CodeGenerationIntegrationTest.cs
+++ b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/test/IntegrationTests/CodeGenerationIntegrationTest.cs
@@ -13,7 +13,7 @@ namespace Microsoft.AspNetCore.Mvc.Razor.Extensions.IntegrationTests
{
public class CodeGenerationIntegrationTest : IntegrationTestBase
{
- private readonly static CSharpCompilation DefaultBaseCompilation = MvcShim.BaseCompilation.WithAssemblyName("AppCode");
+ private static readonly CSharpCompilation DefaultBaseCompilation = MvcShim.BaseCompilation.WithAssemblyName("AppCode");
public CodeGenerationIntegrationTest()
: base(generateBaselines: null, projectDirectoryHint: "Microsoft.AspNetCore.Mvc.Razor.Extensions")
diff --git a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/test/ModelDirectiveTest.cs b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/test/ModelDirectiveTest.cs
index 527120915b4f..1d807edab3c9 100644
--- a/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/test/ModelDirectiveTest.cs
+++ b/src/Razor/Microsoft.AspNetCore.Mvc.Razor.Extensions/test/ModelDirectiveTest.cs
@@ -302,7 +302,7 @@ public override void VisitNamespaceDeclaration(NamespaceDeclarationIntermediateN
private class DesignTimeOptionsFeature : IConfigureRazorParserOptionsFeature, IConfigureRazorCodeGenerationOptionsFeature
{
- private bool _designTime;
+ private readonly bool _designTime;
public DesignTimeOptionsFeature(bool designTime)
{
diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/ClassifiedSpanVisitor.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/ClassifiedSpanVisitor.cs
index f1627441309c..96544078e367 100644
--- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/ClassifiedSpanVisitor.cs
+++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/ClassifiedSpanVisitor.cs
@@ -11,8 +11,8 @@ namespace Microsoft.AspNetCore.Razor.Language
{
internal class ClassifiedSpanVisitor : SyntaxWalker
{
- private RazorSourceDocument _source;
- private List _spans;
+ private readonly RazorSourceDocument _source;
+ private readonly List _spans;
private BlockKindInternal _currentBlockKind;
private SyntaxNode _currentBlock;
diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/CodeGeneration/CodeWriterExtensions.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/CodeGeneration/CodeWriterExtensions.cs
index 734cfa49d719..c17a41af4e8e 100644
--- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/CodeGeneration/CodeWriterExtensions.cs
+++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/CodeGeneration/CodeWriterExtensions.cs
@@ -586,9 +586,9 @@ private static void WriteCStyleStringLiteral(CodeWriter writer, string literal)
public struct CSharpCodeWritingScope : IDisposable
{
- private CodeWriter _writer;
- private bool _autoSpace;
- private int _tabSize;
+ private readonly CodeWriter _writer;
+ private readonly bool _autoSpace;
+ private readonly int _tabSize;
private int _startIndent;
public CSharpCodeWritingScope(CodeWriter writer, bool autoSpace = true)
diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Components/ComponentDuplicateAttributeDiagnosticPass.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Components/ComponentDuplicateAttributeDiagnosticPass.cs
index 36a0e0da916c..5d6014e6c72f 100644
--- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Components/ComponentDuplicateAttributeDiagnosticPass.cs
+++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Components/ComponentDuplicateAttributeDiagnosticPass.cs
@@ -21,7 +21,7 @@ protected override void ExecuteCore(RazorCodeDocument codeDocument, DocumentInte
private class Visitor : IntermediateNodeWalker
{
- private Dictionary _attributes = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ private readonly Dictionary _attributes = new Dictionary(StringComparer.OrdinalIgnoreCase);
public override void VisitMarkupElement(MarkupElementIntermediateNode node)
{
diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/DefaultDirectiveSyntaxTreePass.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/DefaultDirectiveSyntaxTreePass.cs
index ae4ba4989153..563d8148da4a 100644
--- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/DefaultDirectiveSyntaxTreePass.cs
+++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/DefaultDirectiveSyntaxTreePass.cs
@@ -27,8 +27,8 @@ public RazorSyntaxTree Execute(RazorCodeDocument codeDocument, RazorSyntaxTree s
private class NestedSectionVerifier : SyntaxRewriter
{
private int _nestedLevel;
- private RazorSyntaxTree _syntaxTree;
- private List _diagnostics;
+ private readonly RazorSyntaxTree _syntaxTree;
+ private readonly List _diagnostics;
public NestedSectionVerifier(RazorSyntaxTree syntaxTree)
{
diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/DefaultRazorTagHelperBinderPhase.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/DefaultRazorTagHelperBinderPhase.cs
index 53e6c378f46f..3d9825b009f2 100644
--- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/DefaultRazorTagHelperBinderPhase.cs
+++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/DefaultRazorTagHelperBinderPhase.cs
@@ -228,7 +228,7 @@ private bool AssemblyContainsTagHelpers(string assemblyName, IReadOnlyList _notFullyQualifiedComponents;
- private string _filePath;
+ private readonly string _filePath;
private RazorSourceDocument _source;
public ComponentDirectiveVisitor(string filePath, IReadOnlyList tagHelpers, string currentNamespace)
diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/DefaultRequiredAttributeDescriptorBuilder.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/DefaultRequiredAttributeDescriptorBuilder.cs
index 0f68f2967721..9a642486ae50 100644
--- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/DefaultRequiredAttributeDescriptorBuilder.cs
+++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/DefaultRequiredAttributeDescriptorBuilder.cs
@@ -9,7 +9,7 @@ namespace Microsoft.AspNetCore.Razor.Language
{
internal class DefaultRequiredAttributeDescriptorBuilder : RequiredAttributeDescriptorBuilder
{
- private DefaultTagMatchingRuleDescriptorBuilder _parent;
+ private readonly DefaultTagMatchingRuleDescriptorBuilder _parent;
private RazorDiagnosticCollection _diagnostics;
private readonly Dictionary _metadata = new Dictionary();
diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/DefaultTagMatchingRuleDescriptorBuilder.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/DefaultTagMatchingRuleDescriptorBuilder.cs
index 4c8524ccb79d..40c836f782ef 100644
--- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/DefaultTagMatchingRuleDescriptorBuilder.cs
+++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/DefaultTagMatchingRuleDescriptorBuilder.cs
@@ -9,7 +9,7 @@ namespace Microsoft.AspNetCore.Razor.Language
{
internal class DefaultTagMatchingRuleDescriptorBuilder : TagMatchingRuleDescriptorBuilder
{
- private DefaultTagHelperDescriptorBuilder _parent;
+ private readonly DefaultTagHelperDescriptorBuilder _parent;
private List _requiredAttributeBuilders;
private RazorDiagnosticCollection _diagnostics;
diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Intermediate/IntermediateNodeFormatterBase.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Intermediate/IntermediateNodeFormatterBase.cs
index 16498f2fbc6b..ce1fb6facb4f 100644
--- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Intermediate/IntermediateNodeFormatterBase.cs
+++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Intermediate/IntermediateNodeFormatterBase.cs
@@ -11,7 +11,7 @@ namespace Microsoft.AspNetCore.Razor.Language.Intermediate
internal class IntermediateNodeFormatterBase : IntermediateNodeFormatter
{
private string _content;
- private Dictionary _properties = new Dictionary(StringComparer.Ordinal);
+ private readonly Dictionary _properties = new Dictionary(StringComparer.Ordinal);
protected FormatterContentMode ContentMode { get; set; }
diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/CSharpCodeParser.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/CSharpCodeParser.cs
index c6f701153137..56391ea3fc33 100644
--- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/CSharpCodeParser.cs
+++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/CSharpCodeParser.cs
@@ -11,7 +11,7 @@ namespace Microsoft.AspNetCore.Razor.Language.Legacy
{
internal class CSharpCodeParser : TokenizerBackedParser
{
- private static HashSet InvalidNonWhitespaceNameCharacters = new HashSet(new[]
+ private static readonly HashSet InvalidNonWhitespaceNameCharacters = new HashSet(new[]
{
'@', '!', '<', '/', '?', '[', '>', ']', '=', '"', '\'', '*'
});
@@ -67,8 +67,8 @@ internal class CSharpCodeParser : TokenizerBackedParser
private readonly ISet CurrentKeywords = new HashSet(DefaultKeywords);
- private Dictionary, CSharpTransitionSyntax>> _keywordParserMap = new Dictionary, CSharpTransitionSyntax>>();
- private Dictionary, CSharpTransitionSyntax>> _directiveParserMap = new Dictionary, CSharpTransitionSyntax>>(StringComparer.Ordinal);
+ private readonly Dictionary, CSharpTransitionSyntax>> _keywordParserMap = new Dictionary, CSharpTransitionSyntax>>();
+ private readonly Dictionary, CSharpTransitionSyntax>> _directiveParserMap = new Dictionary, CSharpTransitionSyntax>>(StringComparer.Ordinal);
public CSharpCodeParser(ParserContext context)
: this(directives: Enumerable.Empty(), context: context)
diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/CSharpLanguageCharacteristics.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/CSharpLanguageCharacteristics.cs
index 50a07886a687..de870adb821f 100644
--- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/CSharpLanguageCharacteristics.cs
+++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/CSharpLanguageCharacteristics.cs
@@ -10,7 +10,7 @@ namespace Microsoft.AspNetCore.Razor.Language.Legacy
{
internal class CSharpLanguageCharacteristics : LanguageCharacteristics
{
- private static Dictionary _tokenSamples = new Dictionary()
+ private static readonly Dictionary _tokenSamples = new Dictionary()
{
{ SyntaxKind.Arrow, "->" },
{ SyntaxKind.Minus, "-" },
@@ -64,7 +64,7 @@ internal class CSharpLanguageCharacteristics : LanguageCharacteristics _keywordNames = new Dictionary()
+ private static readonly IReadOnlyDictionary _keywordNames = new Dictionary()
{
{ CSharpKeyword.Await, "await" },
{ CSharpKeyword.Abstract, "abstract" },
diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/CSharpTokenizer.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/CSharpTokenizer.cs
index 765f63e38892..d0a95cd876c4 100644
--- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/CSharpTokenizer.cs
+++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/CSharpTokenizer.cs
@@ -11,7 +11,7 @@ namespace Microsoft.AspNetCore.Razor.Language.Legacy
{
internal class CSharpTokenizer : Tokenizer
{
- private Dictionary> _operatorHandlers;
+ private readonly Dictionary> _operatorHandlers;
private static readonly Dictionary _keywords = new Dictionary(StringComparer.Ordinal)
{
@@ -559,8 +559,8 @@ private StateResult VerbatimStringLiteral()
private StateResult QuotedStringLiteral() => QuotedLiteral('\"', IsEndQuotedStringLiteral, SyntaxKind.StringLiteral);
- private Func IsEndQuotedCharacterLiteral = (c) => c == '\\' || c == '\'' || ParserHelpers.IsNewLine(c);
- private Func IsEndQuotedStringLiteral = (c) => c == '\\' || c == '\"' || ParserHelpers.IsNewLine(c);
+ private readonly Func IsEndQuotedCharacterLiteral = (c) => c == '\\' || c == '\'' || ParserHelpers.IsNewLine(c);
+ private readonly Func IsEndQuotedStringLiteral = (c) => c == '\\' || c == '\"' || ParserHelpers.IsNewLine(c);
private StateResult QuotedLiteral(char quote, Func isEndQuotedLiteral, SyntaxKind literalType)
{
diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/FirstDirectiveCSharpLanguageCharacteristics.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/FirstDirectiveCSharpLanguageCharacteristics.cs
index c3761ce5c593..8d4e033f60b7 100644
--- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/FirstDirectiveCSharpLanguageCharacteristics.cs
+++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/FirstDirectiveCSharpLanguageCharacteristics.cs
@@ -1,4 +1,4 @@
-// Copyright (c) .NET Foundation. All rights reserved.
+// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.AspNetCore.Razor.Language.Legacy
@@ -11,7 +11,7 @@ private FirstDirectiveCSharpLanguageCharacteristics()
{
}
- public new static FirstDirectiveCSharpLanguageCharacteristics Instance => _instance;
+ public static new FirstDirectiveCSharpLanguageCharacteristics Instance => _instance;
public override CSharpTokenizer CreateTokenizer(ITextDocument source) => new DirectiveCSharpTokenizer(source);
}
diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/FirstDirectiveHtmlLanguageCharacteristics.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/FirstDirectiveHtmlLanguageCharacteristics.cs
index 2e2c7bea6bb8..ce969c758c26 100644
--- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/FirstDirectiveHtmlLanguageCharacteristics.cs
+++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/FirstDirectiveHtmlLanguageCharacteristics.cs
@@ -11,7 +11,7 @@ private FirstDirectiveHtmlLanguageCharacteristics()
{
}
- public new static FirstDirectiveHtmlLanguageCharacteristics Instance => _instance;
+ public static new FirstDirectiveHtmlLanguageCharacteristics Instance => _instance;
public override HtmlTokenizer CreateTokenizer(ITextDocument source) => new DirectiveHtmlTokenizer(source);
}
diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/TagHelperParseTreeRewriter.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/TagHelperParseTreeRewriter.cs
index fef11964c684..ef83e8f93757 100644
--- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/TagHelperParseTreeRewriter.cs
+++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Legacy/TagHelperParseTreeRewriter.cs
@@ -58,7 +58,7 @@ internal sealed class Rewriter : SyntaxRewriter
private readonly TagHelperBinder _tagHelperBinder;
private readonly Stack _trackerStack;
private readonly ErrorSink _errorSink;
- private RazorParserFeatureFlags _featureFlags;
+ private readonly RazorParserFeatureFlags _featureFlags;
public Rewriter(
RazorSourceDocument source,
diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/RazorCodeDocumentExtensions.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/RazorCodeDocumentExtensions.cs
index 69338cf6a0c9..861329cd66d9 100644
--- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/RazorCodeDocumentExtensions.cs
+++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/RazorCodeDocumentExtensions.cs
@@ -14,7 +14,7 @@ public static class RazorCodeDocumentExtensions
{
private static readonly char[] PathSeparators = new char[] { '/', '\\' };
private static readonly char[] NamespaceSeparators = new char[] { '.' };
- private static object CssScopeKey = new object();
+ private static readonly object CssScopeKey = new object();
public static TagHelperDocumentContext GetTagHelperContext(this RazorCodeDocument document)
{
diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/RazorDiagnostic.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/RazorDiagnostic.cs
index 2f74cfbfad74..f1bfdc377ecb 100644
--- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/RazorDiagnostic.cs
+++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/RazorDiagnostic.cs
@@ -22,7 +22,7 @@ public abstract class RazorDiagnostic : IEquatable, IFormattabl
public abstract bool Equals(RazorDiagnostic other);
- public override abstract int GetHashCode();
+ public abstract override int GetHashCode();
public static RazorDiagnostic Create(RazorDiagnosticDescriptor descriptor, SourceSpan span)
{
diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/InternalSyntax/SyntaxListOfT.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/InternalSyntax/SyntaxListOfT.cs
index e5552cceaf9f..416b368bf266 100644
--- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/InternalSyntax/SyntaxListOfT.cs
+++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/InternalSyntax/SyntaxListOfT.cs
@@ -153,7 +153,7 @@ public static implicit operator SyntaxList(SyntaxList nodes)
internal struct Enumerator
{
- private SyntaxList _list;
+ private readonly SyntaxList _list;
private int _index;
internal Enumerator(SyntaxList list)
diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/InternalSyntax/SyntaxToken.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/InternalSyntax/SyntaxToken.cs
index 2b958788ee16..05493700439e 100644
--- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/InternalSyntax/SyntaxToken.cs
+++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/InternalSyntax/SyntaxToken.cs
@@ -81,7 +81,7 @@ protected override void WriteTokenTo(TextWriter writer, bool leading, bool trail
}
}
- public override sealed GreenNode GetLeadingTrivia()
+ public sealed override GreenNode GetLeadingTrivia()
{
return _leadingTrivia;
}
@@ -91,7 +91,7 @@ public override int GetLeadingTriviaWidth()
return _leadingTrivia == null ? 0 : _leadingTrivia.FullWidth;
}
- public override sealed GreenNode GetTrailingTrivia()
+ public sealed override GreenNode GetTrailingTrivia()
{
return _trailingTrivia;
}
@@ -131,12 +131,12 @@ internal override GreenNode SetAnnotations(SyntaxAnnotation[] annotations)
return new SyntaxToken(Kind, Content, _leadingTrivia, _trailingTrivia, GetDiagnostics(), annotations);
}
- protected override sealed int GetSlotCount()
+ protected sealed override int GetSlotCount()
{
return 0;
}
- internal override sealed GreenNode GetSlot(int index)
+ internal sealed override GreenNode GetSlot(int index)
{
throw new InvalidOperationException("Tokens don't have slots.");
}
diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/InternalSyntax/SyntaxTrivia.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/InternalSyntax/SyntaxTrivia.cs
index 84ad53155ac6..841d134f380f 100644
--- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/InternalSyntax/SyntaxTrivia.cs
+++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/InternalSyntax/SyntaxTrivia.cs
@@ -47,12 +47,12 @@ public sealed override int GetTrailingTriviaWidth()
return 0;
}
- protected override sealed int GetSlotCount()
+ protected sealed override int GetSlotCount()
{
return 0;
}
- internal override sealed GreenNode GetSlot(int index)
+ internal sealed override GreenNode GetSlot(int index)
{
throw new InvalidOperationException();
}
diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SpecializedCollections.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SpecializedCollections.cs
index 3e1094003fe1..48b51cecdd7e 100644
--- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SpecializedCollections.cs
+++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SpecializedCollections.cs
@@ -130,7 +130,7 @@ public bool Remove(T item)
internal class List : Collection, IList, IReadOnlyList
{
- public static readonly new List Instance = new List();
+ public static new readonly List Instance = new List();
protected List()
{
diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SyntaxToken.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SyntaxToken.cs
index e3ecd35bf66b..92f288dc9471 100644
--- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SyntaxToken.cs
+++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SyntaxToken.cs
@@ -20,12 +20,12 @@ internal SyntaxToken(GreenNode green, SyntaxNode parent, int position)
public string Content => Green.Content;
- internal override sealed SyntaxNode GetCachedSlot(int index)
+ internal sealed override SyntaxNode GetCachedSlot(int index)
{
throw new InvalidOperationException("Tokens can't have slots.");
}
- internal override sealed SyntaxNode GetNodeSlot(int slot)
+ internal sealed override SyntaxNode GetNodeSlot(int slot)
{
throw new InvalidOperationException("Tokens can't have slots.");
}
diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SyntaxTrivia.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SyntaxTrivia.cs
index d16e42f1edba..f94fa5ddb291 100644
--- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SyntaxTrivia.cs
+++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SyntaxTrivia.cs
@@ -16,12 +16,12 @@ internal SyntaxTrivia(GreenNode green, SyntaxNode parent, int position)
public string Text => Green.Text;
- internal override sealed SyntaxNode GetCachedSlot(int index)
+ internal sealed override SyntaxNode GetCachedSlot(int index)
{
throw new InvalidOperationException();
}
- internal override sealed SyntaxNode GetNodeSlot(int slot)
+ internal sealed override SyntaxNode GetNodeSlot(int slot)
{
throw new InvalidOperationException();
}
diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SyntaxTriviaList.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SyntaxTriviaList.cs
index 2097e9391c18..22d1760fbc4d 100644
--- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SyntaxTriviaList.cs
+++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SyntaxTriviaList.cs
@@ -1,4 +1,4 @@
-// Copyright (c) .NET Foundation. All rights reserved.
+// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
@@ -507,7 +507,7 @@ public static SyntaxTriviaList Create(SyntaxTrivia trivia)
///
public struct Reversed : IEnumerable, IEquatable
{
- private SyntaxTriviaList _list;
+ private readonly SyntaxTriviaList _list;
public Reversed(in SyntaxTriviaList list)
{
diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/TagHelperSpanVisitor.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/TagHelperSpanVisitor.cs
index 836a45ae983c..422d1bf447fa 100644
--- a/src/Razor/Microsoft.AspNetCore.Razor.Language/src/TagHelperSpanVisitor.cs
+++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/src/TagHelperSpanVisitor.cs
@@ -9,8 +9,8 @@ namespace Microsoft.AspNetCore.Razor.Language
{
internal class TagHelperSpanVisitor : SyntaxWalker
{
- private RazorSourceDocument _source;
- private List _spans;
+ private readonly RazorSourceDocument _source;
+ private readonly List _spans;
public TagHelperSpanVisitor(RazorSourceDocument source)
{
diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/test/DefaultRazorIntermediateNodeLoweringPhaseIntegrationTest.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/test/DefaultRazorIntermediateNodeLoweringPhaseIntegrationTest.cs
index 4d008b89d90a..8611b720e86b 100644
--- a/src/Razor/Microsoft.AspNetCore.Razor.Language/test/DefaultRazorIntermediateNodeLoweringPhaseIntegrationTest.cs
+++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/test/DefaultRazorIntermediateNodeLoweringPhaseIntegrationTest.cs
@@ -516,7 +516,7 @@ private static TagHelperDescriptor CreateTagHelperDescriptor(
private class DesignTimeOptionsFeature : IConfigureRazorParserOptionsFeature, IConfigureRazorCodeGenerationOptionsFeature
{
- private bool _designTime;
+ private readonly bool _designTime;
public DesignTimeOptionsFeature(bool designTime)
{
diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Extensions/DefaultTagHelperTargetExtensionTest.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Extensions/DefaultTagHelperTargetExtensionTest.cs
index 2a8bc2b33524..a9ef4d18b8b6 100644
--- a/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Extensions/DefaultTagHelperTargetExtensionTest.cs
+++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Extensions/DefaultTagHelperTargetExtensionTest.cs
@@ -1209,7 +1209,7 @@ private static TagHelperDescriptor CreateTagHelperDescriptor(
private class DesignTimeOptionsFeature : IConfigureRazorParserOptionsFeature, IConfigureRazorCodeGenerationOptionsFeature
{
- private bool _designTime;
+ private readonly bool _designTime;
public DesignTimeOptionsFeature(bool designTime)
{
diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Legacy/BaselineWriter.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Legacy/BaselineWriter.cs
index e84bfd7a6c4c..56af6e242260 100644
--- a/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Legacy/BaselineWriter.cs
+++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Legacy/BaselineWriter.cs
@@ -8,7 +8,7 @@ namespace Microsoft.AspNetCore.Razor.Language.Legacy
{
public static class BaselineWriter
{
- private static object baselineLock = new object();
+ private static readonly object baselineLock = new object();
[Conditional("GENERATE_BASELINES")]
public static void WriteBaseline(string baselineFile, string output)
diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Legacy/CSharpTokenizerTestBase.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Legacy/CSharpTokenizerTestBase.cs
index 83b2adc684fb..98f3e0119488 100644
--- a/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Legacy/CSharpTokenizerTestBase.cs
+++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Legacy/CSharpTokenizerTestBase.cs
@@ -7,7 +7,7 @@ namespace Microsoft.AspNetCore.Razor.Language.Legacy
{
public abstract class CSharpTokenizerTestBase : TokenizerTestBase
{
- private static SyntaxToken _ignoreRemaining = SyntaxFactory.Token(SyntaxKind.Marker, string.Empty);
+ private static readonly SyntaxToken _ignoreRemaining = SyntaxFactory.Token(SyntaxKind.Marker, string.Empty);
internal override object IgnoreRemaining
{
diff --git a/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Legacy/HtmlTokenizerTestBase.cs b/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Legacy/HtmlTokenizerTestBase.cs
index 0b6250d6d8f1..dc89c9909bf7 100644
--- a/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Legacy/HtmlTokenizerTestBase.cs
+++ b/src/Razor/Microsoft.AspNetCore.Razor.Language/test/Legacy/HtmlTokenizerTestBase.cs
@@ -7,7 +7,7 @@ namespace Microsoft.AspNetCore.Razor.Language.Legacy
{
public abstract class HtmlTokenizerTestBase : TokenizerTestBase
{
- private static SyntaxToken _ignoreRemaining = SyntaxFactory.Token(SyntaxKind.Marker, string.Empty);
+ private static readonly SyntaxToken _ignoreRemaining = SyntaxFactory.Token(SyntaxKind.Marker, string.Empty);
internal override object IgnoreRemaining
{
diff --git a/src/Razor/Microsoft.CodeAnalysis.Razor/src/BindTagHelperDescriptorProvider.cs b/src/Razor/Microsoft.CodeAnalysis.Razor/src/BindTagHelperDescriptorProvider.cs
index 3916a28c2900..828b7e82adc8 100644
--- a/src/Razor/Microsoft.CodeAnalysis.Razor/src/BindTagHelperDescriptorProvider.cs
+++ b/src/Razor/Microsoft.CodeAnalysis.Razor/src/BindTagHelperDescriptorProvider.cs
@@ -579,7 +579,7 @@ public ElementBindData(
private class BindElementDataVisitor : SymbolVisitor
{
- private List _results;
+ private readonly List _results;
public BindElementDataVisitor(List results)
{
diff --git a/src/Razor/Microsoft.CodeAnalysis.Razor/src/EventHandlerTagHelperDescriptorProvider.cs b/src/Razor/Microsoft.CodeAnalysis.Razor/src/EventHandlerTagHelperDescriptorProvider.cs
index 9c83533509ff..aa9f7b611011 100644
--- a/src/Razor/Microsoft.CodeAnalysis.Razor/src/EventHandlerTagHelperDescriptorProvider.cs
+++ b/src/Razor/Microsoft.CodeAnalysis.Razor/src/EventHandlerTagHelperDescriptorProvider.cs
@@ -260,7 +260,7 @@ public EventHandlerData(
private class EventHandlerDataVisitor : SymbolVisitor
{
- private List _results;
+ private readonly List _results;
public EventHandlerDataVisitor(List results)
{
diff --git a/src/Razor/Microsoft.CodeAnalysis.Razor/src/RequiredAttributeParser.cs b/src/Razor/Microsoft.CodeAnalysis.Razor/src/RequiredAttributeParser.cs
index 898e065439ed..fc74d678d629 100644
--- a/src/Razor/Microsoft.CodeAnalysis.Razor/src/RequiredAttributeParser.cs
+++ b/src/Razor/Microsoft.CodeAnalysis.Razor/src/RequiredAttributeParser.cs
@@ -35,7 +35,7 @@ private class DefaultRequiredAttributeParser
private static readonly char[] InvalidCssQuotelessValueCharacters = { ' ', '\t', ']' };
private int _index;
- private string _requiredAttributes;
+ private readonly string _requiredAttributes;
public DefaultRequiredAttributeParser(string requiredAttributes)
{
diff --git a/src/Razor/Microsoft.CodeAnalysis.Razor/src/TagHelperTypeVisitor.cs b/src/Razor/Microsoft.CodeAnalysis.Razor/src/TagHelperTypeVisitor.cs
index 3387cfd1e87f..cc19de3cf942 100644
--- a/src/Razor/Microsoft.CodeAnalysis.Razor/src/TagHelperTypeVisitor.cs
+++ b/src/Razor/Microsoft.CodeAnalysis.Razor/src/TagHelperTypeVisitor.cs
@@ -8,8 +8,8 @@ namespace Microsoft.CodeAnalysis.Razor
// Visits top-level types and finds interface implementations.
internal class TagHelperTypeVisitor : SymbolVisitor
{
- private INamedTypeSymbol _interface;
- private List _results;
+ private readonly INamedTypeSymbol _interface;
+ private readonly List _results;
public TagHelperTypeVisitor(INamedTypeSymbol @interface, List results)
{
diff --git a/src/Razor/Razor.Runtime/src/Runtime/TagHelpers/TagHelperExecutionContext.cs b/src/Razor/Razor.Runtime/src/Runtime/TagHelpers/TagHelperExecutionContext.cs
index 5443bcd5444a..05c1242005af 100644
--- a/src/Razor/Razor.Runtime/src/Runtime/TagHelpers/TagHelperExecutionContext.cs
+++ b/src/Razor/Razor.Runtime/src/Runtime/TagHelpers/TagHelperExecutionContext.cs
@@ -21,7 +21,7 @@ public class TagHelperExecutionContext
private TagHelperContent _childContent;
private Func _executeChildContentAsync;
private Dictionary _perEncoderChildContent;
- private TagHelperAttributeList _allAttributes;
+ private readonly TagHelperAttributeList _allAttributes;
///
/// Internal for testing purposes only.
diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/Language/IntegrationTests/RazorIntegrationTestBase.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/Language/IntegrationTests/RazorIntegrationTestBase.cs
index 0488941c0e8a..180fde3c9f46 100644
--- a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/Language/IntegrationTests/RazorIntegrationTestBase.cs
+++ b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/Language/IntegrationTests/RazorIntegrationTestBase.cs
@@ -465,7 +465,7 @@ protected override void ExecuteCore(RazorCodeDocument codeDocument)
private class TestImportProjectFeature : IImportProjectFeature
{
- private List _imports;
+ private readonly List _imports;
public TestImportProjectFeature(List imports)
{
diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/Language/TestRazorProjectFileSystem.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/Language/TestRazorProjectFileSystem.cs
index 271c6224372d..754ec32088ac 100644
--- a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/Language/TestRazorProjectFileSystem.cs
+++ b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/Language/TestRazorProjectFileSystem.cs
@@ -9,7 +9,7 @@ namespace Microsoft.AspNetCore.Razor.Language
{
internal class TestRazorProjectFileSystem : DefaultRazorProjectFileSystem
{
- public new static RazorProjectFileSystem Empty = new TestRazorProjectFileSystem();
+ public static new RazorProjectFileSystem Empty = new TestRazorProjectFileSystem();
private readonly Dictionary _lookup;
diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.ComponentShim/Microsoft.AspNetCore.Components.Forms.netstandard2.0.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.ComponentShim/Microsoft.AspNetCore.Components.Forms.netstandard2.0.cs
index 4674ff0fb4e2..f6161b164cc5 100644
--- a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.ComponentShim/Microsoft.AspNetCore.Components.Forms.netstandard2.0.cs
+++ b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.ComponentShim/Microsoft.AspNetCore.Components.Forms.netstandard2.0.cs
@@ -64,12 +64,12 @@ public void Clear(System.Linq.Expressions.Expression> access
}
public sealed partial class ValidationRequestedEventArgs : System.EventArgs
{
- public static readonly new Microsoft.AspNetCore.Components.Forms.ValidationRequestedEventArgs Empty;
+ public static new readonly Microsoft.AspNetCore.Components.Forms.ValidationRequestedEventArgs Empty;
public ValidationRequestedEventArgs() { }
}
public sealed partial class ValidationStateChangedEventArgs : System.EventArgs
{
- public static readonly new Microsoft.AspNetCore.Components.Forms.ValidationStateChangedEventArgs Empty;
+ public static new readonly Microsoft.AspNetCore.Components.Forms.ValidationStateChangedEventArgs Empty;
public ValidationStateChangedEventArgs() { }
}
}
diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.ComponentShim/Microsoft.AspNetCore.Components.netstandard2.0.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.ComponentShim/Microsoft.AspNetCore.Components.netstandard2.0.cs
index 7e807c0f675a..d9e1409a4bbc 100644
--- a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.ComponentShim/Microsoft.AspNetCore.Components.netstandard2.0.cs
+++ b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.ComponentShim/Microsoft.AspNetCore.Components.netstandard2.0.cs
@@ -337,8 +337,8 @@ public void SetParameterProperties(object target) { }
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct Enumerator
{
- private object _dummy;
- private int _dummyPrimitive;
+ private readonly object _dummy;
+ private readonly int _dummyPrimitive;
public Microsoft.AspNetCore.Components.ParameterValue Current { get { throw null; } }
public bool MoveNext() { throw null; }
}
diff --git a/src/Security/Authentication/Certificate/src/LoggingExtensions.cs b/src/Security/Authentication/Certificate/src/LoggingExtensions.cs
index e6a67c0ffa40..2d97f194bcf0 100644
--- a/src/Security/Authentication/Certificate/src/LoggingExtensions.cs
+++ b/src/Security/Authentication/Certificate/src/LoggingExtensions.cs
@@ -8,10 +8,10 @@ namespace Microsoft.Extensions.Logging
{
internal static class LoggingExtensions
{
- private static Action _noCertificate;
- private static Action _notHttps;
- private static Action _certRejected;
- private static Action _certFailedValidation;
+ private static readonly Action _noCertificate;
+ private static readonly Action _notHttps;
+ private static readonly Action _certRejected;
+ private static readonly Action _certFailedValidation;
static LoggingExtensions()
{
diff --git a/src/Security/Authentication/Cookies/samples/CookieSessionSample/MemoryCacheTicketStore.cs b/src/Security/Authentication/Cookies/samples/CookieSessionSample/MemoryCacheTicketStore.cs
index ebb660361b43..158921b07cf7 100644
--- a/src/Security/Authentication/Cookies/samples/CookieSessionSample/MemoryCacheTicketStore.cs
+++ b/src/Security/Authentication/Cookies/samples/CookieSessionSample/MemoryCacheTicketStore.cs
@@ -9,7 +9,7 @@ namespace CookieSessionSample
public class MemoryCacheTicketStore : ITicketStore
{
private const string KeyPrefix = "AuthSessionStore-";
- private IMemoryCache _cache;
+ private readonly IMemoryCache _cache;
public MemoryCacheTicketStore()
{
diff --git a/src/Security/Authentication/Cookies/src/CookieAuthenticationHandler.cs b/src/Security/Authentication/Cookies/src/CookieAuthenticationHandler.cs
index 28e5545a141e..b42a64be7834 100644
--- a/src/Security/Authentication/Cookies/src/CookieAuthenticationHandler.cs
+++ b/src/Security/Authentication/Cookies/src/CookieAuthenticationHandler.cs
@@ -276,7 +276,7 @@ protected virtual async Task FinishResponseAsync()
}
///
- protected async override Task HandleSignInAsync(ClaimsPrincipal user, AuthenticationProperties? properties)
+ protected override async Task HandleSignInAsync(ClaimsPrincipal user, AuthenticationProperties? properties)
{
if (user == null)
{
@@ -369,7 +369,7 @@ protected async override Task HandleSignInAsync(ClaimsPrincipal user, Authentica
}
///
- protected async override Task HandleSignOutAsync(AuthenticationProperties? properties)
+ protected override async Task HandleSignOutAsync(AuthenticationProperties? properties)
{
properties = properties ?? new AuthenticationProperties();
diff --git a/src/Security/Authentication/Core/src/HandleRequestResult.cs b/src/Security/Authentication/Core/src/HandleRequestResult.cs
index 7fd664b080bf..73eb461df720 100644
--- a/src/Security/Authentication/Core/src/HandleRequestResult.cs
+++ b/src/Security/Authentication/Core/src/HandleRequestResult.cs
@@ -97,7 +97,7 @@ public static HandleRequestResult SkipHandler()
/// Indicates that there were no results produced during authentication.
///
/// The result.
- public new static HandleRequestResult NoResult()
+ public static new HandleRequestResult NoResult()
{
return new HandleRequestResult() { None = true };
}
diff --git a/src/Security/Authentication/JwtBearer/src/JwtBearerOptions.cs b/src/Security/Authentication/JwtBearer/src/JwtBearerOptions.cs
index 6017853304d2..efd79d9a9dd7 100644
--- a/src/Security/Authentication/JwtBearer/src/JwtBearerOptions.cs
+++ b/src/Security/Authentication/JwtBearer/src/JwtBearerOptions.cs
@@ -16,7 +16,7 @@ namespace Microsoft.AspNetCore.Authentication.JwtBearer
///
public class JwtBearerOptions : AuthenticationSchemeOptions
{
- private JwtSecurityTokenHandler _defaultHandler = new JwtSecurityTokenHandler();
+ private readonly JwtSecurityTokenHandler _defaultHandler = new JwtSecurityTokenHandler();
///
/// Initializes a new instance of .
diff --git a/src/Security/Authentication/Negotiate/src/Internal/NegotiateLoggingExtensions.cs b/src/Security/Authentication/Negotiate/src/Internal/NegotiateLoggingExtensions.cs
index 90a0f4c0c637..61c75b5bfdb3 100644
--- a/src/Security/Authentication/Negotiate/src/Internal/NegotiateLoggingExtensions.cs
+++ b/src/Security/Authentication/Negotiate/src/Internal/NegotiateLoggingExtensions.cs
@@ -7,18 +7,18 @@ namespace Microsoft.Extensions.Logging
{
internal static class NegotiateLoggingExtensions
{
- private static Action _incompleteNegotiateChallenge;
- private static Action _negotiateComplete;
- private static Action _enablingCredentialPersistence;
- private static Action _disablingCredentialPersistence;
- private static Action _exceptionProcessingAuth;
- private static Action _credentialError;
- private static Action _clientError;
- private static Action _challengeNegotiate;
- private static Action _reauthenticating;
- private static Action _deferring;
- private static Action _negotiateError;
- private static Action _protocolNotSupported;
+ private static readonly Action _incompleteNegotiateChallenge;
+ private static readonly Action _negotiateComplete;
+ private static readonly Action _enablingCredentialPersistence;
+ private static readonly Action _disablingCredentialPersistence;
+ private static readonly Action _exceptionProcessingAuth;
+ private static readonly Action _credentialError;
+ private static readonly Action _clientError;
+ private static readonly Action _challengeNegotiate;
+ private static readonly Action _reauthenticating;
+ private static readonly Action _deferring;
+ private static readonly Action _negotiateError;
+ private static readonly Action _protocolNotSupported;
static NegotiateLoggingExtensions()
{
diff --git a/src/Security/Authentication/OAuth/src/LoggingExtensions.cs b/src/Security/Authentication/OAuth/src/LoggingExtensions.cs
index 2ec9befe172a..003e9638a779 100644
--- a/src/Security/Authentication/OAuth/src/LoggingExtensions.cs
+++ b/src/Security/Authentication/OAuth/src/LoggingExtensions.cs
@@ -7,7 +7,7 @@ namespace Microsoft.Extensions.Logging
{
internal static class LoggingExtensions
{
- private static Action _handleChallenge;
+ private static readonly Action _handleChallenge;
static LoggingExtensions()
{
diff --git a/src/Security/Authentication/OpenIdConnect/src/LoggingExtensions.cs b/src/Security/Authentication/OpenIdConnect/src/LoggingExtensions.cs
index 2692942a495a..61399b1d101f 100644
--- a/src/Security/Authentication/OpenIdConnect/src/LoggingExtensions.cs
+++ b/src/Security/Authentication/OpenIdConnect/src/LoggingExtensions.cs
@@ -7,58 +7,58 @@ namespace Microsoft.Extensions.Logging
{
internal static class LoggingExtensions
{
- private static Action _redirectToIdentityProviderForSignOutHandledResponse;
- private static Action _redirectToIdentityProviderHandledResponse;
- private static Action _signOutCallbackRedirectHandledResponse;
- private static Action _signOutCallbackRedirectSkipped;
- private static Action _updatingConfiguration;
- private static Action _receivedIdToken;
- private static Action _redeemingCodeForTokens;
- private static Action _enteringOpenIdAuthenticationHandlerHandleRemoteAuthenticateAsync;
- private static Action _enteringOpenIdAuthenticationHandlerHandleUnauthorizedAsync;
- private static Action _enteringOpenIdAuthenticationHandlerHandleSignOutAsync;
- private static Action _messageReceived;
- private static Action _messageReceivedContextHandledResponse;
- private static Action _messageReceivedContextSkipped;
- private static Action _authorizationCodeReceived;
- private static Action _configurationManagerRequestRefreshCalled;
- private static Action _tokenResponseReceived;
- private static Action _tokenValidatedHandledResponse;
- private static Action _tokenValidatedSkipped;
- private static Action _authenticationFailedContextHandledResponse;
- private static Action _authenticationFailedContextSkipped;
- private static Action _authorizationCodeReceivedContextHandledResponse;
- private static Action _authorizationCodeReceivedContextSkipped;
- private static Action _tokenResponseReceivedHandledResponse;
- private static Action _tokenResponseReceivedSkipped;
- private static Action _userInformationReceived;
- private static Action _userInformationReceivedHandledResponse;
- private static Action _userInformationReceivedSkipped;
- private static Action _invalidLogoutQueryStringRedirectUrl;
- private static Action _nullOrEmptyAuthorizationResponseState;
- private static Action _unableToReadAuthorizationResponseState;
- private static Action _responseError;
- private static Action _responseErrorWithStatusCode;
- private static Action _exceptionProcessingMessage;
- private static Action _accessTokenNotAvailable;
- private static Action _retrievingClaims;
- private static Action _userInfoEndpointNotSet;
- private static Action _unableToProtectNonceCookie;
- private static Action _invalidAuthenticationRequestUrl;
- private static Action _unableToReadIdToken;
- private static Action _invalidSecurityTokenType;
- private static Action _unableToValidateIdToken;
- private static Action _postAuthenticationLocalRedirect;
- private static Action _postSignOutRedirect;
- private static Action _remoteSignOutHandledResponse;
- private static Action _remoteSignOutSkipped;
- private static Action _remoteSignOut;
- private static Action _remoteSignOutSessionIdMissing;
- private static Action _remoteSignOutSessionIdInvalid;
- private static Action _authenticationSchemeSignedOut;
- private static Action _handleChallenge;
- private static Action _remoteSignOutIssuerMissing;
- private static Action _remoteSignOutIssuerInvalid;
+ private static readonly Action _redirectToIdentityProviderForSignOutHandledResponse;
+ private static readonly Action _redirectToIdentityProviderHandledResponse;
+ private static readonly Action _signOutCallbackRedirectHandledResponse;
+ private static readonly Action _signOutCallbackRedirectSkipped;
+ private static readonly Action _updatingConfiguration;
+ private static readonly Action _receivedIdToken;
+ private static readonly Action _redeemingCodeForTokens;
+ private static readonly Action _enteringOpenIdAuthenticationHandlerHandleRemoteAuthenticateAsync;
+ private static readonly Action _enteringOpenIdAuthenticationHandlerHandleUnauthorizedAsync;
+ private static readonly Action _enteringOpenIdAuthenticationHandlerHandleSignOutAsync;
+ private static readonly Action