Sprinkle some more readonly around (#81297)
authorStephen Toub <stoub@microsoft.com>
Tue, 14 Feb 2023 20:33:24 +0000 (15:33 -0500)
committerGitHub <noreply@github.com>
Tue, 14 Feb 2023 20:33:24 +0000 (15:33 -0500)
* Sprinkle some more readonly around

* Revert a few changes / address feedback

112 files changed:
src/libraries/Common/src/System/Data/ProviderBase/DbMetaDataFactory.cs
src/libraries/Common/src/System/Net/DebugSafeHandleMinusOneIsInvalid.cs
src/libraries/Common/src/System/Net/DebugSafeHandleZeroOrMinusOneIsInvalid.cs
src/libraries/Common/src/System/Net/NetworkInformation/HostInformationPal.Windows.cs
src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationExtensions.cs
src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationReloadToken.cs
src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceProvider.cs
src/libraries/Microsoft.Extensions.DependencyModel/src/Resolution/AppBaseCompilationAssemblyResolver.cs
src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeAssetGroup.cs
src/libraries/Microsoft.Extensions.FileProviders.Physical/src/PhysicalFilesWatcher.cs
src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/InMemoryFileInfo.cs
src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/Internal/PatternContexts/PatternContext.cs
src/libraries/Microsoft.Extensions.Hosting/src/HostBuilder.cs
src/libraries/Microsoft.Extensions.Hosting/src/Internal/ConfigureContainerAdapter.cs
src/libraries/Microsoft.Extensions.Hosting/src/Internal/ServiceFactoryAdapter.cs
src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingHttpMessageHandler.cs
src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingScopeHttpMessageHandler.cs
src/libraries/Microsoft.Extensions.Http/src/ValueStopwatch.cs
src/libraries/Microsoft.Extensions.Logging.Abstractions/src/FormattedLogValues.cs
src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleLoggerProvider.cs
src/libraries/Microsoft.Extensions.Logging.Console/src/FormatterOptionsMonitor.cs
src/libraries/Microsoft.Extensions.Logging.Console/src/JsonConsoleFormatter.cs
src/libraries/Microsoft.Extensions.Logging.Console/src/SimpleConsoleFormatter.cs
src/libraries/Microsoft.Extensions.Logging.Console/src/SystemdConsoleFormatter.cs
src/libraries/Microsoft.Extensions.Logging/src/LoggerFactory.cs
src/libraries/Microsoft.Extensions.Logging/src/LoggerFactoryScopeProvider.cs
src/libraries/Microsoft.Extensions.Options.ConfigurationExtensions/src/ConfigurationChangeTokenSource.cs
src/libraries/Microsoft.NETCore.Platforms/src/GenerateRuntimeGraph.cs
src/libraries/Microsoft.NETCore.Platforms/src/RuntimeGroupCollection.cs
src/libraries/Microsoft.NETCore.Platforms/src/RuntimeVersion.cs
src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesigntimeLicenseContextSerializer.cs
src/libraries/System.Configuration.ConfigurationManager/src/System/Diagnostics/FilterElement.cs
src/libraries/System.Configuration.ConfigurationManager/src/System/Diagnostics/ListenerElementsCollection.cs
src/libraries/System.Configuration.ConfigurationManager/src/System/Diagnostics/TypedElement.cs
src/libraries/System.Data.Common/src/System/Data/TypeLimiter.cs
src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPool.cs
src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbMetaDataFactory.cs
src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityTagsCollection.cs
src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/AggregatorStore.cs
src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/MeterListener.cs
src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/ObservableGauge.cs
src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/ObservableUpDownCounter.cs
src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreKey.cs
src/libraries/System.Drawing.Common/src/System/Drawing/BufferedGraphics.cs
src/libraries/System.Drawing.Common/src/System/Drawing/ImageInfo.cs
src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/Encoder.cs
src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/FrameDimension.cs
src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/ImageFormat.cs
src/libraries/System.IO.Compression/src/System/IO/Compression/ZipArchive.cs
src/libraries/System.IO.Compression/src/System/IO/Compression/ZipArchiveEntry.cs
src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeReader.cs
src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/SortQueryOperator.cs
src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpResponseHeaders.cs
src/libraries/System.Net.Http/src/System/Net/Http/Headers/ProductInfoHeaderValue.cs
src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http3RequestStream.cs
src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpNegotiateAuthenticationModule.cs
src/libraries/System.Net.Quic/src/System/Net/Quic/Internal/MsQuicSafeHandle.cs
src/libraries/System.Net.Quic/src/System/Net/Quic/Internal/ResettableValueTaskSource.cs
src/libraries/System.Net.Quic/src/System/Net/Quic/QuicStream.cs
src/libraries/System.Net.Security/src/System/Net/Security/NegotiateAuthentication.cs
src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Tasks.cs
src/libraries/System.Private.CoreLib/src/System/Collections/Hashtable.cs
src/libraries/System.Private.CoreLib/src/System/Globalization/OrdinalCasing.Icu.cs
src/libraries/System.Private.CoreLib/src/System/Globalization/SortVersion.cs
src/libraries/System.Private.CoreLib/src/System/IO/Strategies/OSFileStreamStrategy.cs
src/libraries/System.Private.CoreLib/src/System/IndexOfAnyValues/IndexOfAnyCharValuesInRange.cs
src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs
src/libraries/System.Private.CoreLib/src/System/Threading/PortableThreadPool.WaitThread.cs
src/libraries/System.Private.CoreLib/src/System/Threading/ThreadInt64PersistentCounter.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ClassDataContract.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataReader.cs
src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaImporter.cs
src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs
src/libraries/System.Private.Xml/src/System/Xml/Schema/ContentValidator.cs
src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compilation.cs
src/libraries/System.Private.Xml/src/System/Xml/Serialization/ContextAwareTables.cs
src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathMultyIterator.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilXmlWriter.cs
src/libraries/System.Private.Xml/src/System/Xml/Xsl/SourceLineInfo.cs
src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/Runtime/BindingFlagSupport/QueriedMemberList.cs
src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCacheEntry.cs
src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/Marshaling/ArrayJSGenerator.cs
src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/Marshaling/ArraySegmentJSGenerator.cs
src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/Marshaling/FuncJSGenerator.cs
src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/Marshaling/SpanJSGenerator.cs
src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/Marshaling/TaskJSGenerator.cs
src/libraries/System.Runtime.Serialization.Schema/src/System/Runtime/Serialization/Schema/CodeExporter.cs
src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseMessage.cs
src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/BasicSymmetricCipherLiteBCrypt.cs
src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CryptoStream.cs
src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X500RelativeDistinguishedName.cs
src/libraries/System.Text.Json/gen/JsonSourceGenerator.Emitter.cs
src/libraries/System.Text.Json/gen/Reflection/TypeWrapper.cs
src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonArray.cs
src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.cs
src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.cs
src/libraries/System.Text.Json/src/System/Text/Json/Serialization/ReferenceEqualsWrapper.cs
src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexReplacement.cs
src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/DefaultPartitionedRateLimiter.cs
src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/SlidingWindowRateLimiter.cs
src/libraries/System.Threading.Tasks.Dataflow/src/Base/DataflowBlock.cs
src/libraries/System.Transactions.Local/src/System/Transactions/Configuration/DefaultSettingsSection.cs
src/libraries/System.Transactions.Local/src/System/Transactions/Configuration/MachineSettingsSection.cs
src/libraries/System.Transactions.Local/src/System/Transactions/DtcProxyShim/Phase0Shim.cs
src/libraries/System.Transactions.Local/src/System/Transactions/DtcProxyShim/TransactionShim.cs
src/libraries/System.Transactions.Local/src/System/Transactions/DtcProxyShim/VoterShim.cs
src/libraries/System.Transactions.Local/src/System/Transactions/Oletx/OletxDependentTransaction.cs
src/libraries/System.Transactions.Local/src/System/Transactions/Oletx/OletxEnlistment.cs
src/libraries/System.Transactions.Local/src/System/Transactions/Oletx/OletxTransaction.cs
src/libraries/System.Transactions.Local/src/System/Transactions/Oletx/OletxTransactionManager.cs
src/libraries/System.Transactions.Local/src/System/Transactions/Oletx/OletxVolatileEnlistment.cs

index 054eff2..cc8547a 100644 (file)
@@ -10,7 +10,7 @@ namespace System.Data.ProviderBase
 {
     internal class DbMetaDataFactory
     {
-        private DataSet _metaDataCollectionsDataSet;
+        private readonly DataSet _metaDataCollectionsDataSet;
         private string _normalizedServerVersion;
         private string _serverVersionString;
         // well known column names
index 847b34a..53796ad 100644 (file)
@@ -12,7 +12,7 @@ namespace System.Net
     //
     internal abstract class DebugSafeHandleMinusOneIsInvalid : SafeHandleMinusOneIsInvalid
     {
-        private string _trace;
+        private readonly string _trace;
 
         protected DebugSafeHandleMinusOneIsInvalid(bool ownsHandle) : base(ownsHandle)
         {
index 6afe348..397e99c 100644 (file)
@@ -12,7 +12,7 @@ namespace System.Net
     //
     internal abstract class DebugSafeHandleZeroOrMinusOneIsInvalid : SafeHandleZeroOrMinusOneIsInvalid
     {
-        private string _trace;
+        private readonly string _trace;
 
         protected DebugSafeHandleZeroOrMinusOneIsInvalid(bool ownsHandle) : base(ownsHandle)
         {
index 6035b9e..728afc1 100644 (file)
@@ -21,7 +21,7 @@ namespace System.Net.NetworkInformation
         private static bool s_enableDns;
 
         private static volatile bool s_initialized;
-        private static object s_syncObject = new object();
+        private static readonly object s_syncObject = new object();
 
         public static string GetHostName()
         {
index 8f6a3b5..f84c5c1 100644 (file)
@@ -11,8 +11,8 @@ namespace Microsoft.Extensions.Configuration
     /// </summary>
     public static class FileConfigurationExtensions
     {
-        private static string FileProviderKey = "FileProvider";
-        private static string FileLoadExceptionHandlerKey = "FileLoadExceptionHandler";
+        private const string FileProviderKey = "FileProvider";
+        private const string FileLoadExceptionHandlerKey = "FileLoadExceptionHandler";
 
         /// <summary>
         /// Sets the default <see cref="IFileProvider"/> to be used for file-based providers.
index 8a07d19..97ab47b 100644 (file)
@@ -13,7 +13,7 @@ namespace Microsoft.Extensions.Configuration
     /// </summary>
     public class ConfigurationReloadToken : IChangeToken
     {
-        private CancellationTokenSource _cts = new CancellationTokenSource();
+        private readonly CancellationTokenSource _cts = new CancellationTokenSource();
 
         /// <summary>
         /// Indicates if this token will proactively raise callbacks. Callbacks are still guaranteed to be invoked, eventually.
index 5954d08..b776b78 100644 (file)
@@ -25,7 +25,7 @@ namespace Microsoft.Extensions.DependencyInjection
 
         private bool _disposed;
 
-        private ConcurrentDictionary<Type, Func<ServiceProviderEngineScope, object?>> _realizedServices;
+        private readonly ConcurrentDictionary<Type, Func<ServiceProviderEngineScope, object?>> _realizedServices;
 
         internal CallSiteFactory CallSiteFactory { get; }
 
index bec2afa..73d7f3d 100644 (file)
@@ -10,7 +10,7 @@ namespace Microsoft.Extensions.DependencyModel.Resolution
 {
     public class AppBaseCompilationAssemblyResolver : ICompilationAssemblyResolver
     {
-        private static string RefsDirectoryName = "refs";
+        private const string RefsDirectoryName = "refs";
         private readonly IFileSystem _fileSystem;
         private readonly string _basePath;
         private readonly DependencyContextPaths _dependencyContextPaths;
index f303e64..39a0b5b 100644 (file)
@@ -8,8 +8,8 @@ namespace Microsoft.Extensions.DependencyModel
 {
     public class RuntimeAssetGroup
     {
-        private IReadOnlyList<string>? _assetPaths;
-        private IReadOnlyList<RuntimeFile>? _runtimeFiles;
+        private readonly IReadOnlyList<string>? _assetPaths;
+        private readonly IReadOnlyList<RuntimeFile>? _runtimeFiles;
 
         public RuntimeAssetGroup(string? runtime, params string[] assetPaths) : this(runtime, (IEnumerable<string>)assetPaths) { }
 
index f5b5b45..905dd85 100644 (file)
@@ -41,7 +41,7 @@ namespace Microsoft.Extensions.FileProviders.Physical
         private Timer? _timer;
         private bool _timerInitialized;
         private object _timerLock = new();
-        private Func<Timer> _timerFactory;
+        private readonly Func<Timer> _timerFactory;
         private bool _disposed;
 
         /// <summary>
index 93f8703..cac43eb 100644 (file)
@@ -8,7 +8,7 @@ namespace Microsoft.Extensions.FileSystemGlobbing.Internal
 {
     internal sealed class InMemoryFileInfo : FileInfoBase
     {
-        private InMemoryDirectoryInfo _parent;
+        private readonly InMemoryDirectoryInfo _parent;
 
         public InMemoryFileInfo(string file, InMemoryDirectoryInfo parent)
         {
index e00d307..53b428c 100644 (file)
@@ -9,7 +9,7 @@ namespace Microsoft.Extensions.FileSystemGlobbing.Internal.PatternContexts
 {
     public abstract class PatternContext<TFrame> : IPatternContext where TFrame : struct
     {
-        private Stack<TFrame> _stack = new();
+        private readonly Stack<TFrame> _stack = new();
         protected TFrame Frame;
 
         public virtual void Declare(Action<IPathSegment, bool> declare) { }
index dad58db..596c9af 100644 (file)
@@ -25,10 +25,10 @@ namespace Microsoft.Extensions.Hosting
         private const string HostBuildingEventName = "HostBuilding";
         private const string HostBuiltEventName = "HostBuilt";
 
-        private List<Action<IConfigurationBuilder>> _configureHostConfigActions = new List<Action<IConfigurationBuilder>>();
-        private List<Action<HostBuilderContext, IConfigurationBuilder>> _configureAppConfigActions = new List<Action<HostBuilderContext, IConfigurationBuilder>>();
-        private List<Action<HostBuilderContext, IServiceCollection>> _configureServicesActions = new List<Action<HostBuilderContext, IServiceCollection>>();
-        private List<IConfigureContainerAdapter> _configureContainerActions = new List<IConfigureContainerAdapter>();
+        private readonly List<Action<IConfigurationBuilder>> _configureHostConfigActions = new List<Action<IConfigurationBuilder>>();
+        private readonly List<Action<HostBuilderContext, IConfigurationBuilder>> _configureAppConfigActions = new List<Action<HostBuilderContext, IConfigurationBuilder>>();
+        private readonly List<Action<HostBuilderContext, IServiceCollection>> _configureServicesActions = new List<Action<HostBuilderContext, IServiceCollection>>();
+        private readonly List<IConfigureContainerAdapter> _configureContainerActions = new List<IConfigureContainerAdapter>();
         private IServiceFactoryAdapter _serviceProviderFactory;
         private bool _hostBuilt;
         private IConfiguration? _hostConfiguration;
index 810a28e..2974183 100644 (file)
@@ -7,7 +7,7 @@ namespace Microsoft.Extensions.Hosting.Internal
 {
     internal sealed class ConfigureContainerAdapter<TContainerBuilder> : IConfigureContainerAdapter
     {
-        private Action<HostBuilderContext, TContainerBuilder> _action;
+        private readonly Action<HostBuilderContext, TContainerBuilder> _action;
 
         public ConfigureContainerAdapter(Action<HostBuilderContext, TContainerBuilder> action)
         {
index 6eebf47..69f7c35 100644 (file)
@@ -11,7 +11,7 @@ namespace Microsoft.Extensions.Hosting.Internal
     {
         private IServiceProviderFactory<TContainerBuilder>? _serviceProviderFactory;
         private readonly Func<HostBuilderContext>? _contextResolver;
-        private Func<HostBuilderContext, IServiceProviderFactory<TContainerBuilder>>? _factoryResolver;
+        private readonly Func<HostBuilderContext, IServiceProviderFactory<TContainerBuilder>>? _factoryResolver;
 
         public ServiceFactoryAdapter(IServiceProviderFactory<TContainerBuilder> serviceProviderFactory)
         {
index b1ffecf..62ec57c 100644 (file)
@@ -15,7 +15,7 @@ namespace Microsoft.Extensions.Http.Logging
     /// </summary>
     public class LoggingHttpMessageHandler : DelegatingHandler
     {
-        private ILogger _logger;
+        private readonly ILogger _logger;
         private readonly HttpClientFactoryOptions? _options;
 
         private static readonly Func<string, bool> _shouldNotRedactHeaderValue = (header) => false;
index 2ef5fbe..a2cadee 100644 (file)
@@ -15,7 +15,7 @@ namespace Microsoft.Extensions.Http.Logging
     /// </summary>
     public class LoggingScopeHttpMessageHandler : DelegatingHandler
     {
-        private ILogger _logger;
+        private readonly ILogger _logger;
         private readonly HttpClientFactoryOptions? _options;
 
         private static readonly Func<string, bool> _shouldNotRedactHeaderValue = (header) => false;
index fd29b32..c5373a0 100644 (file)
@@ -8,9 +8,9 @@ namespace Microsoft.Extensions.Internal
 {
     internal struct ValueStopwatch
     {
-        private static readonly double TimestampToTicks = TimeSpan.TicksPerSecond / (double)Stopwatch.Frequency;
+        private static readonly double s_timestampToTicks = TimeSpan.TicksPerSecond / (double)Stopwatch.Frequency;
 
-        private long _startTimestamp;
+        private readonly long _startTimestamp;
 
         public bool IsActive => _startTimestamp != 0;
 
@@ -32,7 +32,7 @@ namespace Microsoft.Extensions.Internal
 
             long end = Stopwatch.GetTimestamp();
             long timestampDelta = end - _startTimestamp;
-            long ticks = (long)(TimestampToTicks * timestampDelta);
+            long ticks = (long)(s_timestampToTicks * timestampDelta);
             return new TimeSpan(ticks);
         }
     }
index 4ee3793..782f9bc 100644 (file)
@@ -17,8 +17,10 @@ namespace Microsoft.Extensions.Logging
     {
         internal const int MaxCachedFormatters = 1024;
         private const string NullFormat = "[null]";
-        private static int _count;
-        private static ConcurrentDictionary<string, LogValuesFormatter> _formatters = new ConcurrentDictionary<string, LogValuesFormatter>();
+
+        private static int s_count;
+        private static readonly ConcurrentDictionary<string, LogValuesFormatter> s_formatters = new ConcurrentDictionary<string, LogValuesFormatter>();
+
         private readonly LogValuesFormatter? _formatter;
         private readonly object?[]? _values;
         private readonly string _originalMessage;
@@ -30,18 +32,18 @@ namespace Microsoft.Extensions.Logging
         {
             if (values != null && values.Length != 0 && format != null)
             {
-                if (_count >= MaxCachedFormatters)
+                if (s_count >= MaxCachedFormatters)
                 {
-                    if (!_formatters.TryGetValue(format, out _formatter))
+                    if (!s_formatters.TryGetValue(format, out _formatter))
                     {
                         _formatter = new LogValuesFormatter(format);
                     }
                 }
                 else
                 {
-                    _formatter = _formatters.GetOrAdd(format, f =>
+                    _formatter = s_formatters.GetOrAdd(format, f =>
                     {
-                        Interlocked.Increment(ref _count);
+                        Interlocked.Increment(ref s_count);
                         return new LogValuesFormatter(f);
                     });
                 }
index 6bbb9b7..b85273d 100644 (file)
@@ -23,7 +23,7 @@ namespace Microsoft.Extensions.Logging.Console
         private ConcurrentDictionary<string, ConsoleFormatter> _formatters;
         private readonly ConsoleLoggerProcessor _messageQueue;
 
-        private IDisposable? _optionsReloadToken;
+        private readonly IDisposable? _optionsReloadToken;
         private IExternalScopeProvider _scopeProvider = NullExternalScopeProvider.Instance;
 
         /// <summary>
index a47d455..e729eaa 100644 (file)
@@ -11,7 +11,8 @@ namespace Microsoft.Extensions.Logging.Console
         IOptionsMonitor<TOptions>
         where TOptions : ConsoleFormatterOptions
     {
-        private TOptions _options;
+        private readonly TOptions _options;
+
         public FormatterOptionsMonitor(TOptions options)
         {
             _options = options;
index 2e07ed8..e3e2aa1 100644 (file)
@@ -16,7 +16,7 @@ namespace Microsoft.Extensions.Logging.Console
 {
     internal sealed class JsonConsoleFormatter : ConsoleFormatter, IDisposable
     {
-        private IDisposable? _optionsReloadToken;
+        private readonly IDisposable? _optionsReloadToken;
 
         public JsonConsoleFormatter(IOptionsMonitor<JsonConsoleFormatterOptions> options)
             : base(ConsoleFormatterNames.Json)
index d2c189d..c75c623 100644 (file)
@@ -22,7 +22,7 @@ namespace Microsoft.Extensions.Logging.Console
 #else
         private static bool IsAndroidOrAppleMobile => false;
 #endif
-        private IDisposable? _optionsReloadToken;
+        private readonly IDisposable? _optionsReloadToken;
 
         public SimpleConsoleFormatter(IOptionsMonitor<SimpleConsoleFormatterOptions> options)
             : base(ConsoleFormatterNames.Simple)
index 9ee390e..5c06263 100644 (file)
@@ -12,7 +12,7 @@ namespace Microsoft.Extensions.Logging.Console
 {
     internal sealed class SystemdConsoleFormatter : ConsoleFormatter, IDisposable
     {
-        private IDisposable? _optionsReloadToken;
+        private readonly IDisposable? _optionsReloadToken;
 
         public SystemdConsoleFormatter(IOptionsMonitor<ConsoleFormatterOptions> options)
             : base(ConsoleFormatterNames.Systemd)
index 315ea91..eb2a22b 100644 (file)
@@ -18,10 +18,10 @@ namespace Microsoft.Extensions.Logging
         private readonly List<ProviderRegistration> _providerRegistrations = new List<ProviderRegistration>();
         private readonly object _sync = new object();
         private volatile bool _disposed;
-        private IDisposable? _changeTokenRegistration;
+        private readonly IDisposable? _changeTokenRegistration;
         private LoggerFilterOptions _filterOptions;
         private IExternalScopeProvider? _scopeProvider;
-        private LoggerFactoryOptions _factoryOptions;
+        private readonly LoggerFactoryOptions _factoryOptions;
 
         /// <summary>
         /// Creates a new <see cref="LoggerFactory"/> instance.
index 2115b98..9795a46 100644 (file)
@@ -132,7 +132,7 @@ namespace Microsoft.Extensions.Logging
         {
             private string? _cachedToString;
             private const int MaxItems = 5;
-            private KeyValuePair<string, object?>[] _items = new KeyValuePair<string, object?>[MaxItems];
+            private readonly KeyValuePair<string, object?>[] _items = new KeyValuePair<string, object?>[MaxItems];
 
             public ActivityLogScope(Activity activity, ActivityTrackingOptions activityTrackingOption)
             {
index d939409..3fbc7b9 100644 (file)
@@ -14,7 +14,7 @@ namespace Microsoft.Extensions.Options
     /// <typeparam name="TOptions"></typeparam>
     public class ConfigurationChangeTokenSource<TOptions> : IOptionsChangeTokenSource<TOptions>
     {
-        private IConfiguration _config;
+        private readonly IConfiguration _config;
 
         /// <summary>
         /// Constructor taking the <see cref="IConfiguration"/> instance to watch.
index 314dd59..f431e27 100644 (file)
@@ -395,7 +395,7 @@ namespace Microsoft.NETCore.Platforms.BuildTasks
             return true;
         }
 
-        private static XNamespace s_dgmlns = @"http://schemas.microsoft.com/vs/2009/dgml";
+        private static readonly XNamespace s_dgmlns = @"http://schemas.microsoft.com/vs/2009/dgml";
         private static void WriteRuntimeGraph(RuntimeGraph graph, string dependencyGraphFilePath)
         {
 
index 447aa72..e069508 100644 (file)
@@ -12,9 +12,9 @@ namespace Microsoft.NETCore.Platforms.BuildTasks
 {
     public class RuntimeGroupCollection
     {
-        private ICollection<RuntimeGroup> allRuntimeGroups;
-        private Dictionary<string, List<RuntimeGroup>> runtimeGroupsByBaseRID;
-        private HashSet<RID> knownRIDs;
+        private readonly ICollection<RuntimeGroup> allRuntimeGroups;
+        private readonly Dictionary<string, List<RuntimeGroup>> runtimeGroupsByBaseRID;
+        private readonly HashSet<RID> knownRIDs;
 
         public RuntimeGroupCollection(ICollection<RuntimeGroup> runtimeGroups)
         {
index 954659f..ca7b1db 100644 (file)
@@ -11,9 +11,9 @@ namespace Microsoft.NETCore.Platforms.BuildTasks
     /// </summary>
     public sealed class RuntimeVersion : IComparable, IComparable<RuntimeVersion>, IEquatable<RuntimeVersion>
     {
-        private string versionString;
-        private Version version;
-        private bool hasMinor;
+        private readonly string versionString;
+        private readonly Version version;
+        private readonly bool hasMinor;
 
         public RuntimeVersion(string versionString)
         {
index 1c30a4d..179b413 100644 (file)
@@ -62,9 +62,10 @@ namespace System.ComponentModel.Design
 
         private sealed class StreamWrapper : Stream
         {
-            private Stream _stream;
+            private readonly Stream _stream;
             private bool _readFirstByte;
             internal byte _firstByte;
+
             public StreamWrapper(Stream stream)
             {
                 _stream = stream;
index 6067c06..c3fd5ab 100644 (file)
@@ -7,7 +7,7 @@ namespace System.Diagnostics
 {
     internal sealed class FilterElement : TypedElement
     {
-        private static ConditionalWeakTable<TraceFilter, string> s_initData = new();
+        private static readonly ConditionalWeakTable<TraceFilter, string> s_initData = new();
 
         public FilterElement() : base(typeof(TraceFilter)) { }
 
index 04a5496..5cb1e66 100644 (file)
@@ -82,12 +82,12 @@ namespace System.Diagnostics
         private static readonly ConfigurationProperty s_propName = new("name", typeof(string), null, ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsKey);
         private static readonly ConfigurationProperty s_propOutputOpts = new("traceOutputOptions", typeof(TraceOptions), TraceOptions.None, ConfigurationPropertyOptions.None);
 
-        private ConfigurationProperty _propListenerTypeName;
-        private bool _allowReferences;
+        private readonly ConfigurationProperty _propListenerTypeName;
+        private readonly bool _allowReferences;
         private StringDictionary _attributes;
         internal bool _isAddedByDefault;
 
-        private static ConditionalWeakTable<TraceListener, string> s_initData = new();
+        private static readonly ConditionalWeakTable<TraceListener, string> s_initData = new();
 
         public ListenerElement(bool allowReferences) : base(typeof(TraceListener))
         {
index da386ed..fbe87cf 100644 (file)
@@ -9,9 +9,9 @@ namespace System.Diagnostics
         protected static readonly ConfigurationProperty s_propTypeName = new("type", typeof(string), string.Empty, ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsTypeStringTransformationRequired);
         protected static readonly ConfigurationProperty s_propInitData = new("initializeData", typeof(string), string.Empty, ConfigurationPropertyOptions.None);
 
-        protected ConfigurationPropertyCollection _properties;
+        protected readonly ConfigurationPropertyCollection _properties;
         protected object _runtimeObject;
-        private Type _baseType;
+        private readonly Type _baseType;
 
         public TypedElement(Type baseType) : base()
         {
index 4d68583..8bc9376 100644 (file)
@@ -16,7 +16,7 @@ namespace System.Data
         [ThreadStatic]
         private static Scope? s_activeScope;
 
-        private Scope m_instanceScope;
+        private readonly Scope m_instanceScope;
 
         private const string AppDomainDataSetDefaultAllowedTypesKey = "System.Data.DataSetDefaultAllowedTypes";
 
@@ -183,7 +183,7 @@ namespace System.Data
             /// <summary>
             /// Types which are allowed within the context of this scope.
             /// </summary>
-            private HashSet<Type> m_allowedTypes;
+            private readonly HashSet<Type> m_allowedTypes;
 
             /// <summary>
             /// This thread's previous scope.
index 155899e..4e3b0e9 100644 (file)
@@ -352,7 +352,7 @@ namespace System.Data.ProviderBase
         private readonly WaitCallback _poolCreateRequest;
 
         private int _waitCount;
-        private PoolWaitHandles _waitHandles;
+        private readonly PoolWaitHandles _waitHandles;
 
         private Exception? _resError;
         private volatile bool _errorOccurred;
index 3cc3c08..1ace12d 100644 (file)
@@ -11,7 +11,7 @@ namespace System.Data.ProviderBase
     internal class DbMetaDataFactory
     { // V1.2.3300
 
-        private DataSet _metaDataCollectionsDataSet;
+        private readonly DataSet _metaDataCollectionsDataSet;
         private string _normalizedServerVersion;
         private string _serverVersionString;
         // well known column names
index f009edc..5d0b28a 100644 (file)
@@ -21,7 +21,7 @@ namespace System.Diagnostics
     /// </summary>
     public class ActivityTagsCollection : IDictionary<string, object?>
     {
-        private List<KeyValuePair<string, object?>> _list = new List<KeyValuePair<string, object?>>();
+        private readonly List<KeyValuePair<string, object?>> _list = new List<KeyValuePair<string, object?>>();
 
         /// <summary>
         /// Create a new instance of the collection.
index 0a33c60..e16e505 100644 (file)
@@ -410,10 +410,10 @@ namespace System.Diagnostics.Metrics
         where TObjectSequence : struct, IObjectSequence, IEquatable<TObjectSequence>
         where TAggregator : Aggregator
     {
-        private int _expectedLabelCount;
-        private LabelInstruction[] _instructions;
-        private ConcurrentDictionary<TObjectSequence, TAggregator> _valuesDict;
-        private Func<TObjectSequence, TAggregator?> _createAggregator;
+        private readonly int _expectedLabelCount;
+        private readonly LabelInstruction[] _instructions;
+        private readonly ConcurrentDictionary<TObjectSequence, TAggregator> _valuesDict;
+        private readonly Func<TObjectSequence, TAggregator?> _createAggregator;
 
         public LabelInstructionInterpreter(
             int expectedLabelCount,
index 6c3d38f..f007da5 100644 (file)
@@ -18,10 +18,10 @@ namespace System.Diagnostics.Metrics
     {
         // We use LikedList here so we don't have to take any lock while iterating over the list as we always hold on a node which be either valid or null.
         // DiagLinkedList is thread safe for Add, Remove, and Clear operations.
-        private static List<MeterListener> s_allStartedListeners = new List<MeterListener>();
+        private static readonly List<MeterListener> s_allStartedListeners = new List<MeterListener>();
 
         // List of the instruments which the current listener is listening to.
-        private DiagLinkedList<Instrument> _enabledMeasurementInstruments = new DiagLinkedList<Instrument>();
+        private readonly DiagLinkedList<Instrument> _enabledMeasurementInstruments = new DiagLinkedList<Instrument>();
         private bool _disposed;
 
         // We initialize all measurement callback with no-op operations so we'll avoid the null checks during the execution;
index 6e659a5..db57db0 100644 (file)
@@ -15,7 +15,7 @@ namespace System.Diagnostics.Metrics
     /// </remarks>
     public sealed class ObservableGauge<T> : ObservableInstrument<T> where T : struct
     {
-        private object _callback;
+        private readonly object _callback;
 
         internal ObservableGauge(Meter meter, string name, Func<T> observeValue, string? unit, string? description) : base(meter, name, unit, description)
         {
index 1589930..9d3b32b 100644 (file)
@@ -15,7 +15,7 @@ namespace System.Diagnostics.Metrics
     /// </remarks>
     public sealed class ObservableUpDownCounter<T> : ObservableInstrument<T> where T : struct
     {
-        private object _callback;
+        private readonly object _callback;
 
         internal ObservableUpDownCounter(Meter meter, string name, Func<T> observeValue, string? unit, string? description) : base(meter, name, unit, description)
         {
index 845afc0..e3cd669 100644 (file)
@@ -10,7 +10,7 @@ namespace System.DirectoryServices.AccountManagement
     internal sealed class ADStoreKey : StoreKey
     {
         // For regular ADStoreKeys
-        private System.Guid _objectGuid;
+        private readonly System.Guid _objectGuid;
 
         // For ADStoreKeys corresponding to well-known SIDs
         private readonly bool _wellKnownSid;
index f7bcdf4..4224959 100644 (file)
@@ -13,7 +13,7 @@ namespace System.Drawing
     /// </summary>
     public sealed class BufferedGraphics : IDisposable
     {
-        private Graphics? _targetGraphics;
+        private readonly Graphics? _targetGraphics;
         private readonly IntPtr _targetDC;
         private Graphics _bufferedGraphicsSurface;
         private BufferedGraphicsContext _context;
index 822cded..9eb32d8 100644 (file)
@@ -29,7 +29,7 @@ namespace System.Drawing
             private readonly bool _animated;
             private EventHandler? _onFrameChangedHandler;
             private readonly long[]? _frameEndTimes;
-            private long _totalAnimationTime;
+            private readonly long _totalAnimationTime;
             private long _frameTimer;
 
             public ImageInfo(Image image)
index 13d0adf..b7f92cd 100644 (file)
@@ -31,16 +31,10 @@ namespace System.Drawing.Imaging
         /// </summary>
         public static readonly Encoder SaveAsCmyk = new Encoder(new Guid(unchecked((int)0xa219bbc9), unchecked((short)0x0a9d), unchecked((short)0x4005), new byte[] { 0xa3, 0xee, 0x3a, 0x42, 0x1b, 0x8b, 0xb0, 0x6c }));
 
-        private Guid _guid;
+        private readonly Guid _guid;
 
-        public Encoder(Guid guid)
-        {
-            _guid = guid;
-        }
+        public Encoder(Guid guid) => _guid = guid;
 
-        public Guid Guid
-        {
-            get { return _guid; }
-        }
+        public Guid Guid => _guid;
     }
 }
index 44d36d2..bbfcec1 100644 (file)
@@ -12,7 +12,7 @@ namespace System.Drawing.Imaging
         private static readonly FrameDimension s_resolution = new FrameDimension(new Guid("{84236f7b-3bd3-428f-8dab-4ea1439ca315}"));
         private static readonly FrameDimension s_page = new FrameDimension(new Guid("{7462dc86-6180-4c7e-8e3f-ee7333a7a483}"));
 
-        private Guid _guid;
+        private readonly Guid _guid;
 
         /// <summary>
         /// Initializes a new instance of the <see cref='FrameDimension'/> class with the specified GUID.
index 1a37c8b..41d30e4 100644 (file)
@@ -28,7 +28,7 @@ namespace System.Drawing.Imaging
         private static readonly ImageFormat s_heif = new ImageFormat(new Guid("{b96b3cb6-0728-11d3-9d7b-0000f81ef32e}"));
         private static readonly ImageFormat s_webp = new ImageFormat(new Guid("{b96b3cb7-0728-11d3-9d7b-0000f81ef32e}"));
 
-        private Guid _guid;
+        private readonly Guid _guid;
 
         /// <summary>
         /// Initializes a new instance of the <see cref='ImageFormat'/> class with the specified GUID.
index 17a9f59..6d6b0e8 100644 (file)
@@ -16,18 +16,18 @@ namespace System.IO.Compression
     {
         private readonly Stream _archiveStream;
         private ZipArchiveEntry? _archiveStreamOwner;
-        private BinaryReader? _archiveReader;
-        private ZipArchiveMode _mode;
-        private List<ZipArchiveEntry> _entries;
-        private ReadOnlyCollection<ZipArchiveEntry> _entriesCollection;
-        private Dictionary<string, ZipArchiveEntry> _entriesDictionary;
+        private readonly BinaryReader? _archiveReader;
+        private readonly ZipArchiveMode _mode;
+        private readonly List<ZipArchiveEntry> _entries;
+        private readonly ReadOnlyCollection<ZipArchiveEntry> _entriesCollection;
+        private readonly Dictionary<string, ZipArchiveEntry> _entriesDictionary;
         private bool _readEntries;
-        private bool _leaveOpen;
+        private readonly bool _leaveOpen;
         private long _centralDirectoryStart; //only valid after ReadCentralDirectory
         private bool _isDisposed;
         private uint _numberOfThisDisk; //only valid after ReadCentralDirectory
         private long _expectedNumberOfEntries;
-        private Stream? _backingStream;
+        private readonly Stream? _backingStream;
         private byte[] _archiveComment;
         private Encoding? _entryNameAndCommentEncoding;
 
index 5cbfc57..1fd84d7 100644 (file)
@@ -23,7 +23,7 @@ namespace System.IO.Compression
         private ZipVersionNeededValues _versionMadeBySpecification;
         internal ZipVersionNeededValues _versionToExtract;
         private BitFlagValues _generalPurposeBitFlag;
-        private bool _isEncrypted;
+        private readonly bool _isEncrypted;
         private CompressionMethodValues _storedCompressionMethod;
         private DateTimeOffset _lastModified;
         private long _compressedSize;
index b911295..47ccc47 100644 (file)
@@ -29,7 +29,7 @@ namespace System.IO.Pipelines
         // Mutable struct! Don't make this readonly
         private BufferSegmentStack _bufferSegmentPool;
 
-        private StreamPipeReaderOptions _options;
+        private readonly StreamPipeReaderOptions _options;
 
         /// <summary>
         /// Creates a new StreamPipeReader.
index a1fe751..06a3002 100644 (file)
@@ -118,7 +118,7 @@ namespace System.Linq.Parallel
 
     internal sealed class SortQueryOperatorResults<TInputOutput, TSortKey> : QueryResults<TInputOutput>
     {
-        private QueryResults<TInputOutput> _childQueryResults; // Results of the child query
+        private readonly QueryResults<TInputOutput> _childQueryResults; // Results of the child query
         private readonly SortQueryOperator<TInputOutput, TSortKey> _op; // Operator that generated these results
         private QuerySettings _settings; // Settings collected from the query
 
index 9529fb8..1497289 100644 (file)
@@ -16,7 +16,7 @@ namespace System.Net.Http.Headers
 
         private object[]? _specialCollectionsSlots;
         private HttpGeneralHeaders? _generalHeaders;
-        private bool _containsTrailingHeaders;
+        private readonly bool _containsTrailingHeaders;
 
         #region Response Headers
 
index 40a6b47..6ed9717 100644 (file)
@@ -8,18 +8,12 @@ namespace System.Net.Http.Headers
 {
     public class ProductInfoHeaderValue : ICloneable
     {
-        private ProductHeaderValue? _product;
-        private string? _comment;
+        private readonly ProductHeaderValue? _product;
+        private readonly string? _comment;
 
-        public ProductHeaderValue? Product
-        {
-            get { return _product; }
-        }
+        public ProductHeaderValue? Product => _product;
 
-        public string? Comment
-        {
-            get { return _comment; }
-        }
+        public string? Comment => _comment;
 
         public ProductInfoHeaderValue(string productName, string? productVersion)
             : this(new ProductHeaderValue(productName, productVersion))
index 0386447..70b1690 100644 (file)
@@ -25,18 +25,18 @@ namespace System.Net.Http
         private readonly HttpRequestMessage _request;
         private Http3Connection _connection;
         private long _streamId = -1; // A stream does not have an ID until the first I/O against it. This gets set almost immediately following construction.
-        private QuicStream _stream;
+        private readonly QuicStream _stream;
         private ArrayBuffer _sendBuffer;
         private ArrayBuffer _recvBuffer;
         private TaskCompletionSource<bool>? _expect100ContinueCompletionSource; // True indicates we should send content (e.g. received 100 Continue).
         private bool _disposed;
-        private CancellationTokenSource _requestBodyCancellationSource;
+        private readonly CancellationTokenSource _requestBodyCancellationSource;
 
         // Allocated when we receive a :status header.
         private HttpResponseMessage? _response;
 
         // Header decoding.
-        private QPackDecoder _headerDecoder;
+        private readonly QPackDecoder _headerDecoder;
         private HeaderState _headerState;
         private int _headerBudgetRemaining;
 
index 57fa1cc..52946d5 100644 (file)
@@ -11,7 +11,7 @@ namespace System.Net.Mail
 {
     internal sealed class SmtpNegotiateAuthenticationModule : ISmtpAuthenticationModule
     {
-        private static byte[] _saslNoSecurtyLayerToken = new byte[] { 1, 0, 0, 0 };
+        private static readonly byte[] s_saslNoSecurtyLayerToken = new byte[] { 1, 0, 0, 0 };
         private readonly Dictionary<object, NegotiateAuthentication> _sessions = new Dictionary<object, NegotiateAuthentication>();
 
         internal SmtpNegotiateAuthenticationModule()
@@ -168,7 +168,7 @@ namespace System.Net.Mail
 
             // let MakeSignature figure out length of output
             ArrayBufferWriter<byte> outputWriter = new ArrayBufferWriter<byte>();
-            statusCode = clientContext.Wrap(_saslNoSecurtyLayerToken, outputWriter, false, out _);
+            statusCode = clientContext.Wrap(s_saslNoSecurtyLayerToken, outputWriter, false, out _);
             if (statusCode != NegotiateAuthenticationStatusCode.Completed)
             {
                 return null;
index 58b4144..3adc922 100644 (file)
@@ -21,7 +21,7 @@ internal unsafe class MsQuicSafeHandle : SafeHandle
 
     private readonly delegate* unmanaged[Cdecl]<QUIC_HANDLE*, void> _releaseAction;
     private string? _traceId;
-    private SafeHandleType _type;
+    private readonly SafeHandleType _type;
 
     public override bool IsInvalid => handle == IntPtr.Zero;
 
index 3ec8f53..76dd9ea 100644 (file)
@@ -31,7 +31,7 @@ internal sealed class ResettableValueTaskSource : IValueTaskSource
     private Action<object?>? _cancellationAction;
     private GCHandle _keepAlive;
 
-    private TaskCompletionSource _finalTaskSource;
+    private readonly TaskCompletionSource _finalTaskSource;
 
     public ResettableValueTaskSource(bool runContinuationsAsynchronously = true)
     {
index 4de2f95..701a1ed 100644 (file)
@@ -108,15 +108,15 @@ public sealed partial class QuicStream
         }
     };
     private MsQuicBuffers _sendBuffers = new MsQuicBuffers();
-    private object _sendBuffersLock = new object();
+    private readonly object _sendBuffersLock = new object();
 
     private readonly long _defaultErrorCode;
 
-    private bool _canRead;
-    private bool _canWrite;
+    private readonly bool _canRead;
+    private readonly bool _canWrite;
 
     private long _id = -1;
-    private QuicStreamType _type;
+    private readonly QuicStreamType _type;
 
     /// <summary>
     /// Stream id, see <see href="https://www.rfc-editor.org/rfc/rfc9000.html#name-stream-types-and-identifier" />.
index e03b7a5..47c0307 100644 (file)
@@ -18,11 +18,11 @@ namespace System.Net.Security
         private readonly NTAuthentication? _ntAuthentication;
         private readonly string _requestedPackage;
         private readonly bool _isServer;
+        private readonly TokenImpersonationLevel _requiredImpersonationLevel;
+        private readonly ProtectionLevel _requiredProtectionLevel;
+        private readonly ExtendedProtectionPolicy? _extendedProtectionPolicy;
+        private readonly bool _isSecureConnection;
         private IIdentity? _remoteIdentity;
-        private TokenImpersonationLevel _requiredImpersonationLevel;
-        private ProtectionLevel _requiredProtectionLevel;
-        private ExtendedProtectionPolicy? _extendedProtectionPolicy;
-        private bool _isSecureConnection;
 
         /// <summary>
         /// Initializes a new instance of the <see cref="NegotiateAuthentication"/>
index c35e184..7519dbd 100644 (file)
@@ -922,7 +922,7 @@ namespace System.Net.Sockets
             /// <summary>The owning socket.</summary>
             private readonly Socket _owner;
             /// <summary>Whether this should be cached as a read or a write on the <see cref="_owner"/></summary>
-            private bool _isReadForCaching;
+            private readonly bool _isReadForCaching;
             /// <summary>
             /// <see cref="s_completedSentinel"/> if it has completed. Another delegate if OnCompleted was called before the operation could complete,
             /// in which case it's the delegate to invoke when the operation does complete.
index 11dc9e7..b0c8757 100644 (file)
@@ -1245,7 +1245,7 @@ namespace System.Collections
         // Synchronized wrapper for hashtable
         private sealed class SyncHashtable : Hashtable, IEnumerable
         {
-            private Hashtable _table;
+            private readonly Hashtable _table;
 
             internal SyncHashtable(Hashtable table) : base(false)
             {
index af44c2d..a3bdd38 100644 (file)
@@ -11,12 +11,12 @@ namespace System.Globalization
 {
     internal static partial class OrdinalCasing
     {
-        // s_noCasingPage means the Unicode page doesn't support any casing and no case translation is needed.
-        private static ushort [] s_noCasingPage = Array.Empty<ushort>();
+        // NoCasingPage means the Unicode page doesn't support any casing and no case translation is needed.
+        private static ushort[] NoCasingPage => Array.Empty<ushort>();
 
         // s_basicLatin is covering the casing for the Basic Latin & C0 Controls range.
         // we are not lazy initializing this range because it is the most common used range and we'll cache it anyway very early.
-        private static ushort [] s_basicLatin =
+        private static readonly ushort[] s_basicLatin =
         {
             // Upper Casing
 
@@ -41,48 +41,48 @@ namespace System.Globalization
         // s_casingTable is covering the Unicode BMP plane only. Surrogate casing is handled separately.
         // Every cell in the table is covering the casing of 256 characters in the BMP.
         // Every cell is array of 512 character for uppercasing mapping.
-        private static ushort []?[] s_casingTable = InitCasingTable();
+        private static readonly ushort[]?[] s_casingTable = InitCasingTable();
 
         /*
          The table is initialized to:
         {
             // 0000-07FF //       s_basicLatin,            null,            null,            null,            null,            null,            null,            null,
             // 0800-0FFF //               null,            null,            null,            null,            null,            null,            null,            null,
-            // 1000-17FF //               null,  s_noCasingPage,            null,            null,  s_noCasingPage,  s_noCasingPage,            null,            null,
+            // 1000-17FF //               null,    NoCasingPage,            null,            null,    NoCasingPage,    NoCasingPage,            null,            null,
             // 1800-1FFF //               null,            null,            null,            null,            null,            null,            null,            null,
-            // 2000-27FF //               null,            null,  s_noCasingPage,  s_noCasingPage,            null,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,
-            // 2800-2FFF //     s_noCasingPage,  s_noCasingPage,  s_noCasingPage,            null,            null,            null,            null,            null,
-            // 3000-37FF //               null,            null,            null,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,
-            // 3800-3FFF //     s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,
-            // 4000-47FF //     s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,
-            // 4800-4FFF //     s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,
-            // 5000-57FF //     s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,
-            // 5800-5FFF //     s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,
-            // 6000-67FF //     s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,
-            // 6800-6FFF //     s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,
-            // 7000-77FF //     s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,
-            // 7800-7FFF //     s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,
-            // 8000-87FF //     s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,
-            // 8800-8FFF //     s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,
-            // 9000-97FF //     s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,
-            // 9800-9FFF //     s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,            null,
-            // A000-A7FF //     s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,            null,  s_noCasingPage,            null,            null,
-            // A800-AFFF //               null,            null,            null,            null,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,
-            // B000-B7FF //     s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,
-            // B800-BFFF //     s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,
-            // C000-C7FF //     s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,
-            // C800-CFFF //     s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,
-            // D000-D7FF //     s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,            null,
-            // D800-DFFF //     s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,
-            // E000-E7FF //     s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,
-            // E800-EFFF //     s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,
-            // F000-F7FF //     s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,  s_noCasingPage,
-            // F800-FFFF //     s_noCasingPage,  s_noCasingPage,            null,            null,  s_noCasingPage,            null,            null,            null,
+            // 2000-27FF //               null,            null,    NoCasingPage,    NoCasingPage,            null,    NoCasingPage,    NoCasingPage,    NoCasingPage,
+            // 2800-2FFF //       NoCasingPage,    NoCasingPage,    NoCasingPage,            null,            null,            null,            null,            null,
+            // 3000-37FF //               null,            null,            null,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,
+            // 3800-3FFF //       NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,
+            // 4000-47FF //       NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,
+            // 4800-4FFF //       NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,
+            // 5000-57FF //       NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,
+            // 5800-5FFF //       NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,
+            // 6000-67FF //       NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,
+            // 6800-6FFF //       NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,
+            // 7000-77FF //       NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,
+            // 7800-7FFF //       NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,
+            // 8000-87FF //       NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,
+            // 8800-8FFF //       NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,
+            // 9000-97FF //       NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,
+            // 9800-9FFF //       NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,            null,
+            // A000-A7FF //       NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,            null,    NoCasingPage,            null,            null,
+            // A800-AFFF //               null,            null,            null,            null,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,
+            // B000-B7FF //       NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,
+            // B800-BFFF //       NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,
+            // C000-C7FF //       NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,
+            // C800-CFFF //       NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,
+            // D000-D7FF //       NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,            null,
+            // D800-DFFF //       NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,
+            // E000-E7FF //       NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,
+            // E800-EFFF //       NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,
+            // F000-F7FF //       NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,    NoCasingPage,
+            // F800-FFFF //       NoCasingPage,    NoCasingPage,            null,            null,    NoCasingPage,            null,            null,            null,
         };
 */
 
         // 0 - null
-        // 1 - s_noCasingPage
+        // 1 - NoCasingPage
         // The bits are in reverse order for readability, i.e. the highest order bit refers to
         // the lowest index.
         private static ReadOnlySpan<byte> s_casingTableInit => new byte[32]
@@ -132,7 +132,7 @@ namespace System.Globalization
 
             ushort[]? casingTable = s_casingTable[pageNumber];
 
-            if (casingTable == s_noCasingPage)
+            if (casingTable == NoCasingPage)
             {
                 return c;
             }
@@ -420,7 +420,7 @@ namespace System.Globalization
                 // The bits are in reverse order
                 byte val = (byte)(s_casingTableInit[i / 8] >> (7 - (i % 8)));
                 if ((val & 1) == 1)
-                    table[i] = s_noCasingPage;
+                    table[i] = NoCasingPage;
             }
             table[0] = s_basicLatin;
             return table;
index 4b2cbae..448a0d1 100644 (file)
@@ -11,7 +11,7 @@ namespace System.Globalization
     public sealed class SortVersion : IEquatable<SortVersion?>
     {
         private readonly int m_NlsVersion; // Do not rename (binary serialization)
-        private Guid m_SortId; // Do not rename (binary serialization)
+        private readonly Guid m_SortId; // Do not rename (binary serialization)
 
         public int FullVersion => m_NlsVersion;
 
index b9f6c9e..83746a5 100644 (file)
@@ -15,7 +15,7 @@ namespace System.IO.Strategies
         private readonly FileAccess _access; // What file was opened for.
 
         protected long _filePosition;
-        private long _appendStart; // When appending, prevent overwriting file.
+        private readonly long _appendStart; // When appending, prevent overwriting file.
 
         internal OSFileStreamStrategy(SafeFileHandle handle, FileAccess access)
         {
index 0cde365..2aac505 100644 (file)
@@ -9,7 +9,8 @@ namespace System.Buffers
     internal sealed class IndexOfAnyCharValuesInRange<TShouldUsePacked> : IndexOfAnyValues<char>
         where TShouldUsePacked : struct, IndexOfAnyValues.IRuntimeConst
     {
-        private char _lowInclusive, _rangeInclusive, _highInclusive;
+        private readonly char _rangeInclusive;
+        private char _lowInclusive, _highInclusive;
         private readonly uint _lowUint, _highMinusLow;
 
         public IndexOfAnyCharValuesInRange(char lowInclusive, char highInclusive)
index 26fad2b..74d207b 100644 (file)
@@ -12,7 +12,7 @@ namespace System.Runtime.CompilerServices
     [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
     public sealed class RuntimeWrappedException : Exception
     {
-        private object _wrappedException; // EE expects this name
+        private readonly object _wrappedException; // EE expects this name
 
         // Not an api but has to be public as System.Linq.Expression invokes this through Reflection when an expression
         // throws an object that doesn't derive from Exception.
index 4c8512f..34f7b3e 100644 (file)
@@ -12,8 +12,8 @@ namespace System.Threading
     /// </summary>
     internal sealed partial class CompleteWaitThreadPoolWorkItem : IThreadPoolWorkItem
     {
-        private RegisteredWaitHandle _registeredWaitHandle;
-        private bool _timedOut;
+        private readonly RegisteredWaitHandle _registeredWaitHandle;
+        private readonly bool _timedOut;
 
         public CompleteWaitThreadPoolWorkItem(RegisteredWaitHandle registeredWaitHandle, bool timedOut)
         {
index c2d950e..0f7fbc0 100644 (file)
@@ -17,7 +17,7 @@ namespace System.Threading
         private long _overflowCount;
 
         // dummy node serving as a start and end of the ring list
-        private ThreadLocalNode _nodes;
+        private readonly ThreadLocalNode _nodes;
 
         public ThreadInt64PersistentCounter()
         {
index 28e992e..efdc1a7 100644 (file)
@@ -617,7 +617,7 @@ namespace System.Runtime.Serialization.DataContracts
             /// in serialization/deserialization we base the decision whether to Demand SerializationFormatter permission on this value and hasDataContract
             /// </SecurityNote>
             private bool _hasDataContract;
-            private bool _hasExtensionData;
+            private readonly bool _hasExtensionData;
 
             internal XmlDictionaryString[]? ContractNamespaces;
             internal XmlDictionaryString[]? MemberNames;
index 3921571..80b9a5b 100644 (file)
@@ -34,8 +34,8 @@ namespace System.Runtime.Serialization.DataContracts
             DynamicallyAccessedMemberTypes.PublicFields |
             DynamicallyAccessedMemberTypes.PublicProperties;
 
-        private XmlDictionaryString _name;
-        private XmlDictionaryString _ns;
+        private readonly XmlDictionaryString _name;
+        private readonly XmlDictionaryString _ns;
         private readonly DataContractCriticalHelper _helper;
 
         internal DataContract(DataContractCriticalHelper helper)
@@ -303,7 +303,7 @@ namespace System.Runtime.Serialization.DataContracts
             private static Dictionary<Type, DataContract?>? s_typeToBuiltInContract;
             private static Dictionary<XmlQualifiedName, DataContract?>? s_nameToBuiltInContract;
             private static Dictionary<string, DataContract?>? s_typeNameToBuiltInContract;
-            private static Hashtable s_namespaces = new Hashtable();
+            private static readonly Hashtable s_namespaces = new Hashtable();
             private static Dictionary<string, XmlDictionaryString>? s_clrTypeStrings;
             private static XmlDictionary? s_clrTypeStringsDictionary;
 
@@ -2404,10 +2404,10 @@ namespace System.Runtime.Serialization.DataContracts
 
     internal sealed class GenericInfo : IGenericNameProvider
     {
-        private string? _genericTypeName;
-        private XmlQualifiedName _xmlName;
+        private readonly string? _genericTypeName;
+        private readonly XmlQualifiedName _xmlName;
         private List<GenericInfo>? _paramGenericInfos;
-        private List<int> _nestedParamCounts;
+        private readonly List<int> _nestedParamCounts;
 
         internal GenericInfo(XmlQualifiedName xmlName, string? genericTypeName)
         {
@@ -2515,8 +2515,8 @@ namespace System.Runtime.Serialization.DataContracts
 
     internal sealed class DataContractPairKey
     {
-        private object _object1;
-        private object _object2;
+        private readonly object _object1;
+        private readonly object _object2;
 
         internal DataContractPairKey(object object1, object object2)
         {
index fc970ad..09af184 100644 (file)
@@ -41,7 +41,7 @@ namespace System.Runtime.Serialization
         private int _attributeCount;
         private int _attributeIndex;
 
-        private Hashtable _cache = new Hashtable();
+        private readonly Hashtable _cache = new Hashtable();
         private XmlNodeReader? _xmlNodeReader;
         private Queue<IDataNode>? _deserializedDataNodes;
 
index 478a975..befa4f4 100644 (file)
@@ -21,11 +21,11 @@ namespace System.Runtime.Serialization
 
     internal sealed class SchemaImporter
     {
-        private DataContractSet _dataContractSet;
-        private XmlSchemaSet _schemaSet;
-        private IEnumerable<XmlQualifiedName>? _typeNames;
-        private IEnumerable<XmlSchemaElement>? _elements;
-        private bool _importXmlDataType;
+        private readonly DataContractSet _dataContractSet;
+        private readonly XmlSchemaSet _schemaSet;
+        private readonly IEnumerable<XmlQualifiedName>? _typeNames;
+        private readonly IEnumerable<XmlSchemaElement>? _elements;
+        private readonly bool _importXmlDataType;
         private SchemaObjectDictionary _schemaObjects = null!;   // Not directly referenced. Always lazy initialized by property getter.
         private List<XmlSchemaRedefine> _redefineList = null!;   // Not directly referenced. Always lazy initialized by property getter.
         private bool _needToImportKnownTypesForObject;
index df7d85b..313fcba 100644 (file)
@@ -64,7 +64,7 @@ namespace System.Xml
         private readonly XmlResolver? _xmlResolver;
         private readonly ValidationEventHandler? _validationEvent;
         private ValidatingReaderState _validationState;
-        private XmlValueGetter _valueGetter;
+        private readonly XmlValueGetter _valueGetter;
 
         // namespace management
         private readonly XmlNamespaceManager? _nsManager;
@@ -81,14 +81,14 @@ namespace System.Xml
         private int _coreReaderAttributeCount;
         private int _currentAttrIndex;
         private AttributePSVIInfo[] _attributePSVINodes;
-        private ArrayList _defaultAttributes;
+        private readonly ArrayList _defaultAttributes;
 
         // Inline Schema
         private Parser? _inlineSchemaParser;
 
         // Typed Value & PSVI
         private object? _atomicValue;
-        private XmlSchemaInfo _xmlSchemaInfo;
+        private readonly XmlSchemaInfo _xmlSchemaInfo;
 
         // original string of the atomic value
         private string? _originalAtomicValueString;
@@ -101,14 +101,14 @@ namespace System.Xml
         private ValidatingReaderNodeData? _textNode;
 
         // To avoid SchemaNames creation
-        private string _nsXmlNs;
-        private string _nsXs;
-        private string _nsXsi;
-        private string _xsiType;
-        private string _xsiNil;
-        private string _xsdSchema;
-        private string _xsiSchemaLocation;
-        private string _xsiNoNamespaceSchemaLocation;
+        private readonly string _nsXmlNs;
+        private readonly string _nsXs;
+        private readonly string _nsXsi;
+        private readonly string _xsiType;
+        private readonly string _xsiNil;
+        private readonly string _xsdSchema;
+        private readonly string _xsiSchemaLocation;
+        private readonly string _xsiNoNamespaceSchemaLocation;
 
         // Underlying reader's IXmlLineInfo
         private IXmlLineInfo? _lineInfo;
index fcdc286..eabeb1e 100644 (file)
@@ -345,8 +345,8 @@ namespace System.Xml.Schema
     /// </summary>
     internal sealed class NamespaceListNode : SyntaxTreeNode
     {
-        private NamespaceList namespaceList;
-        private object particle;
+        private readonly NamespaceList namespaceList;
+        private readonly object particle;
 
         public NamespaceListNode(NamespaceList namespaceList, object particle)
         {
index 0ee0a68..6e5478a 100644 (file)
@@ -691,8 +691,8 @@ namespace System.Xml.Serialization
 
     internal sealed class TempAssemblyCache
     {
+        private readonly ConditionalWeakTable<Assembly, Dictionary<TempAssemblyCacheKey, TempAssembly>> _collectibleCaches = new ConditionalWeakTable<Assembly, Dictionary<TempAssemblyCacheKey, TempAssembly>>();
         private Dictionary<TempAssemblyCacheKey, TempAssembly> _fastCache = new Dictionary<TempAssemblyCacheKey, TempAssembly>();
-        private ConditionalWeakTable<Assembly, Dictionary<TempAssemblyCacheKey, TempAssembly>> _collectibleCaches = new ConditionalWeakTable<Assembly, Dictionary<TempAssemblyCacheKey, TempAssembly>>();
 
         internal TempAssembly? this[string? ns, Type t]
         {
index bec03e7..858ad99 100644 (file)
@@ -11,8 +11,8 @@ namespace System.Xml.Serialization
 {
     internal sealed class ContextAwareTables<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]T> where T : class?
     {
-        private Hashtable _defaultTable;
-        private ConditionalWeakTable<Type, T> _collectibleTable;
+        private readonly Hashtable _defaultTable;
+        private readonly ConditionalWeakTable<Type, T> _collectibleTable;
 
         public ContextAwareTables()
         {
index aadb4b2..c047cc4 100644 (file)
@@ -12,7 +12,7 @@ namespace MS.Internal.Xml.XPath
 {
     internal sealed class XPathMultyIterator : ResettableIterator
     {
-        private ResettableIterator[] arr;
+        private readonly ResettableIterator[] arr;
         private int firstNotEmpty;
         private int position;
 
index 83f5876..3112752 100644 (file)
@@ -37,8 +37,8 @@ namespace System.Xml.Xsl.Qil
     /// </remarks>
     internal sealed class QilXmlWriter : QilScopedVisitor
     {
-        private XmlWriter writer;
-        private Options options;
+        private readonly XmlWriter writer;
+        private readonly Options options;
         private readonly NameGenerator _ngen;
 
         [Flags]
index ac4e94d..48e8754 100644 (file)
@@ -27,9 +27,9 @@ namespace System.Xml.Xsl
     [DebuggerDisplay("{Uri} [{StartLine},{StartPos} -- {EndLine},{EndPos}]")]
     internal sealed class SourceLineInfo : ISourceLineInfo
     {
-        private string? uriString;
-        private Location start;
-        private Location end;
+        private readonly string? uriString;
+        private readonly Location start;
+        private readonly Location end;
 
         public SourceLineInfo(string? uriString, int startLine, int startPos, int endLine, int endPos)
             : this(uriString, new Location(startLine, startPos), new Location(endLine, endPos))
index 8bc7050..3b64819 100644 (file)
@@ -192,7 +192,7 @@ namespace System.Reflection.Runtime.BindingFlagSupport
         private int _declaredOnlyCount; // # of entries for members only in the most derived class.
         private M[] _members;  // Length is equal to or greater than _totalCount. Entries beyond _totalCount contain null or garbage and should be read.
         private BindingFlags[] _allFlagsThatMustMatch; // Length will be equal to _members.Length
-        private RuntimeTypeInfo? _typeThatBlockedBrowsing; // If non-null, one of the base classes was missing metadata.
+        private readonly RuntimeTypeInfo? _typeThatBlockedBrowsing; // If non-null, one of the base classes was missing metadata.
         private const int Grow = 64;
     }
 }
index 404091c..c0d218b 100644 (file)
@@ -18,7 +18,7 @@ namespace System.Runtime.Caching
         private int _state;
         // expiration
         private DateTime _utcAbsExp;
-        private TimeSpan _slidingExp;
+        private readonly TimeSpan _slidingExp;
         private ExpiresEntryRef _expiresEntryRef;
         private byte _expiresBucket; // index of the expiration list (bucket)
         // usage
index fb2dea2..816c9d7 100644 (file)
@@ -11,7 +11,8 @@ namespace Microsoft.Interop.JavaScript
 {
     internal sealed class ArrayJSGenerator : PrimitiveJSGenerator
     {
-        private MarshalerType _elementMarshalerType;
+        private readonly MarshalerType _elementMarshalerType;
+
         public ArrayJSGenerator(MarshalerType elementMarshalerType)
             : base(MarshalerType.Array)
         {
index 8b0e6bd..ef6ef06 100644 (file)
@@ -10,7 +10,8 @@ namespace Microsoft.Interop.JavaScript
 {
     internal sealed class ArraySegmentJSGenerator : PrimitiveJSGenerator
     {
-        private MarshalerType _elementMarshalerType;
+        private readonly MarshalerType _elementMarshalerType;
+
         public ArraySegmentJSGenerator(MarshalerType elementMarshalerType)
             : base(MarshalerType.ArraySegment)
         {
index be4773e..e1d1a4d 100644 (file)
@@ -13,8 +13,9 @@ namespace Microsoft.Interop.JavaScript
 {
     internal sealed class FuncJSGenerator : BaseJSGenerator
     {
-        private bool _isAction;
-        private MarshalerType[] _argumentMarshalerTypes;
+        private readonly bool _isAction;
+        private readonly MarshalerType[] _argumentMarshalerTypes;
+
         public FuncJSGenerator(bool isAction, MarshalerType[] argumentMarshalerTypes)
             : base(isAction ? MarshalerType.Action : MarshalerType.Function, new Forwarder())
         {
index bd627de..6d53af9 100644 (file)
@@ -10,7 +10,8 @@ namespace Microsoft.Interop.JavaScript
 {
     internal sealed class SpanJSGenerator : PrimitiveJSGenerator
     {
-        private MarshalerType _elementMarshalerType;
+        private readonly MarshalerType _elementMarshalerType;
+
         public SpanJSGenerator(MarshalerType elementMarshalerType)
             : base(MarshalerType.Span)
         {
index a88b755..f4a4261 100644 (file)
@@ -11,7 +11,8 @@ namespace Microsoft.Interop.JavaScript
 {
     internal sealed class TaskJSGenerator : BaseJSGenerator
     {
-        private MarshalerType _resultMarshalerType;
+        private readonly MarshalerType _resultMarshalerType;
+
         public TaskJSGenerator(MarshalerType resultMarshalerType)
             : base(MarshalerType.Task, new Forwarder())
         {
index 57064b5..7fb8957 100644 (file)
@@ -32,11 +32,11 @@ namespace System.Runtime.Serialization
         private static readonly object s_codeUserDataActualTypeKey = new object();
         private static readonly object s_surrogateDataKey = typeof(ISerializationSurrogateProvider2);
 
-        private DataContractSet _dataContractSet;
-        private CodeCompileUnit _codeCompileUnit;
-        private ImportOptions? _options;
-        private Dictionary<string, string> _namespaces;
-        private Dictionary<string, string?> _clrNamespaces;
+        private readonly DataContractSet _dataContractSet;
+        private readonly CodeCompileUnit _codeCompileUnit;
+        private readonly ImportOptions? _options;
+        private readonly Dictionary<string, string> _namespaces;
+        private readonly Dictionary<string, string?> _clrNamespaces;
 
         internal CodeExporter(DataContractSet dataContractSet, ImportOptions? options, CodeCompileUnit codeCompileUnit)
         {
index 1d74e26..6395c96 100644 (file)
@@ -31,8 +31,8 @@ namespace System.Security.Cryptography.Cose
         internal readonly byte[] _protectedHeaderAsBstr;
         internal readonly bool _isTagged;
 
-        private CoseHeaderMap _protectedHeaders;
-        private CoseHeaderMap _unprotectedHeaders;
+        private readonly CoseHeaderMap _protectedHeaders;
+        private readonly CoseHeaderMap _unprotectedHeaders;
 
         /// <summary>
         /// Gets the protected header parameters associated with this message.
index 484ccdb..431ad75 100644 (file)
@@ -10,8 +10,8 @@ namespace System.Security.Cryptography
     internal sealed class BasicSymmetricCipherLiteBCrypt : ILiteSymmetricCipher
     {
         private readonly bool _encrypting;
+        private readonly byte[]? _currentIv;
         private SafeKeyHandle _hKey;
-        private byte[]? _currentIv;
 
         public int BlockSizeInBytes { get; }
         public int PaddingSizeInBytes { get; }
index 8eac210..c1cc9a9 100644 (file)
@@ -18,10 +18,10 @@ namespace System.Security.Cryptography
         private readonly ICryptoTransform _transform;
         private byte[] _inputBuffer;  // read from _stream before _Transform
         private int _inputBufferIndex;
-        private int _inputBlockSize;
+        private readonly int _inputBlockSize;
         private byte[] _outputBuffer; // buffered output of _Transform
         private int _outputBufferIndex;
-        private int _outputBlockSize;
+        private readonly int _outputBlockSize;
         private bool _canRead;
         private bool _canWrite;
         private bool _finalBlockTransformed;
index 7c4d56b..e705588 100644 (file)
@@ -12,7 +12,7 @@ namespace System.Security.Cryptography.X509Certificates
     /// <seealso cref="X500DistinguishedName"/>
     public sealed class X500RelativeDistinguishedName
     {
-        private Oid? _singleElementType;
+        private readonly Oid? _singleElementType;
         private readonly ReadOnlyMemory<byte> _singleElementValue;
 
         /// <summary>
index ffa31a0..c794436 100644 (file)
@@ -41,9 +41,9 @@ namespace System.Text.Json.SourceGeneration
             private const string ValueVarName = "value";
             private const string WriterVarName = "writer";
 
-            private static AssemblyName _assemblyName = typeof(Emitter).Assembly.GetName();
+            private static readonly AssemblyName s_assemblyName = typeof(Emitter).Assembly.GetName();
             private static readonly string s_generatedCodeAttributeSource = $@"
-[global::System.CodeDom.Compiler.GeneratedCodeAttribute(""{_assemblyName.Name}"", ""{_assemblyName.Version}"")]
+[global::System.CodeDom.Compiler.GeneratedCodeAttribute(""{s_assemblyName.Name}"", ""{s_assemblyName.Version}"")]
 ";
 
             // global::fully.qualified.name for referenced types
index 392050c..33e3fc0 100644 (file)
@@ -19,9 +19,9 @@ namespace System.Text.Json.Reflection
 
         private readonly MetadataLoadContextInternal _metadataLoadContext;
 
-        private INamedTypeSymbol? _namedTypeSymbol;
+        private readonly INamedTypeSymbol? _namedTypeSymbol;
 
-        private IArrayTypeSymbol? _arrayTypeSymbol;
+        private readonly IArrayTypeSymbol? _arrayTypeSymbol;
 
         private Type? _elementType;
 
index ddcad35..f5ad9b2 100644 (file)
@@ -229,7 +229,7 @@ namespace System.Text.Json.Nodes
         private sealed class DebugView
         {
             [DebuggerBrowsable(DebuggerBrowsableState.Never)]
-            private JsonArray _node;
+            private readonly JsonArray _node;
 
             public DebugView(JsonArray node)
             {
index d1369d0..7beb9fd 100644 (file)
@@ -164,7 +164,7 @@ namespace System.Text.Json.Nodes
         private sealed class DebugView
         {
             [DebuggerBrowsable(DebuggerBrowsableState.Never)]
-            private JsonObject _node;
+            private readonly JsonObject _node;
 
             public DebugView(JsonObject node)
             {
index 8ee4182..e5f4655 100644 (file)
@@ -58,7 +58,7 @@ namespace System.Text.Json
         private JsonCommentHandling _readCommentHandling;
         private ReferenceHandler? _referenceHandler;
         private JavaScriptEncoder? _encoder;
-        private ConfigurationList<JsonConverter> _converters;
+        private readonly ConfigurationList<JsonConverter> _converters;
         private JsonIgnoreCondition _defaultIgnoreCondition;
         private JsonNumberHandling _numberHandling;
         private JsonUnknownTypeHandling _unknownTypeHandling;
index d905ff9..2314a21 100644 (file)
@@ -8,8 +8,10 @@ namespace System.Text.Json.Serialization
 {
     internal struct ReferenceEqualsWrapper : IEquatable<ReferenceEqualsWrapper>
     {
-        private object _object;
+        private readonly object _object;
+
         public ReferenceEqualsWrapper(object obj) => _object = obj;
+
         public override bool Equals([NotNullWhen(true)] object? obj) => obj is ReferenceEqualsWrapper otherObj && Equals(otherObj);
         public bool Equals(ReferenceEqualsWrapper obj) => ReferenceEquals(_object, obj._object);
         public override int GetHashCode() => RuntimeHelpers.GetHashCode(_object);
index 92abdc8..45ade77 100644 (file)
@@ -24,7 +24,7 @@ namespace System.Text.RegularExpressions
 
         private readonly string[] _strings; // table of string constants
         private readonly int[] _rules;      // negative -> group #, positive -> string #
-        private bool _hasBackreferences;    // true if the replacement has any backreferences; otherwise, false
+        private readonly bool _hasBackreferences;    // true if the replacement has any backreferences; otherwise, false
 
         /// <summary>
         /// Since RegexReplacement shares the same parser as Regex,
index 04e1716..3869fb4 100644 (file)
@@ -13,21 +13,21 @@ namespace System.Threading.RateLimiting
     internal sealed class DefaultPartitionedRateLimiter<TResource, TKey> : PartitionedRateLimiter<TResource> where TKey : notnull
     {
         private readonly Func<TResource, RateLimitPartition<TKey>> _partitioner;
-        private static TimeSpan _idleTimeLimit = TimeSpan.FromSeconds(10);
+        private static readonly TimeSpan s_idleTimeLimit = TimeSpan.FromSeconds(10);
 
         // TODO: Look at ConcurrentDictionary to try and avoid a global lock
-        private Dictionary<TKey, Lazy<RateLimiter>> _limiters;
+        private readonly Dictionary<TKey, Lazy<RateLimiter>> _limiters;
         private bool _disposed;
-        private TaskCompletionSource<object?> _disposeComplete = new(TaskCreationOptions.RunContinuationsAsynchronously);
+        private readonly TaskCompletionSource<object?> _disposeComplete = new(TaskCreationOptions.RunContinuationsAsynchronously);
 
         // Used by the Timer to call TryRelenish on ReplenishingRateLimiters
         // We use a separate list to avoid running TryReplenish (which might be user code) inside our lock
         // And we cache the list to amortize the allocation cost to as close to 0 as we can get
-        private List<KeyValuePair<TKey, Lazy<RateLimiter>>> _cachedLimiters = new();
+        private readonly List<KeyValuePair<TKey, Lazy<RateLimiter>>> _cachedLimiters = new();
         private bool _cacheInvalid;
-        private List<RateLimiter> _limitersToDispose = new();
-        private TimerAwaitable _timer;
-        private Task _timerTask;
+        private readonly List<RateLimiter> _limitersToDispose = new();
+        private readonly TimerAwaitable _timer;
+        private readonly Task _timerTask;
 
         // Use the Dictionary as the lock field so we don't need to allocate another object for a lock and have another field in the object
         private object Lock => _limiters;
@@ -226,13 +226,13 @@ namespace System.Threading.RateLimiting
                 {
                     continue;
                 }
-                if (rateLimiter.Value.Value.IdleDuration is TimeSpan idleDuration && idleDuration > _idleTimeLimit)
+                if (rateLimiter.Value.Value.IdleDuration is TimeSpan idleDuration && idleDuration > s_idleTimeLimit)
                 {
                     lock (Lock)
                     {
                         // Check time again under lock to make sure no one calls Acquire or WaitAsync after checking the time and removing the limiter
                         idleDuration = rateLimiter.Value.Value.IdleDuration ?? TimeSpan.Zero;
-                        if (idleDuration > _idleTimeLimit)
+                        if (idleDuration > s_idleTimeLimit)
                         {
                             // Remove limiter from the lookup table and mark cache as invalid
                             // If a request for this partition comes in it will have to create a new limiter now
index 6597687..c2927e2 100644 (file)
@@ -15,7 +15,7 @@ namespace System.Threading.RateLimiting
     {
         private int _permitCount;
         private int _queueCount;
-        private int[] _requestsPerSegment;
+        private readonly int[] _requestsPerSegment;
         private int _currentSegmentIndex;
         private long _lastReplenishmentTick;
         private long? _idleSince;
index 0cbc141..41d7ca9 100644 (file)
@@ -374,9 +374,9 @@ namespace System.Threading.Tasks.Dataflow
             private readonly TOutput _messageValue;
 
             /// <summary>CancellationToken used to cancel the send.</summary>
-            private CancellationToken _cancellationToken;
+            private readonly CancellationToken _cancellationToken;
             /// <summary>Registration with the cancellation token.</summary>
-            private CancellationTokenRegistration _cancellationRegistration;
+            private readonly CancellationTokenRegistration _cancellationRegistration;
             /// <summary>The cancellation/completion state of the source.</summary>
             private int _cancellationState; // one of the CANCELLATION_STATE_* constant values, defaulting to NONE
 
index 464577f..212941a 100644 (file)
@@ -6,15 +6,12 @@ namespace System.Transactions.Configuration
     internal sealed class DefaultSettingsSection // ConfigurationSection
     {
         private static readonly DefaultSettingsSection s_section = new DefaultSettingsSection();
-        private static TimeSpan s_timeout = TimeSpan.Parse(ConfigurationStrings.DefaultTimeout);
+        private static readonly TimeSpan s_timeout = TimeSpan.Parse(ConfigurationStrings.DefaultTimeout);
 
         internal static DefaultSettingsSection GetSection() => s_section;
 
         public static string DistributedTransactionManagerName { get; set; } = ConfigurationStrings.DefaultDistributedTransactionManagerName;
 
-        public static TimeSpan Timeout
-        {
-            get { return s_timeout; }
-        }
+        public static TimeSpan Timeout => s_timeout;
     }
 }
index 2989617..96528e9 100644 (file)
@@ -6,13 +6,10 @@ namespace System.Transactions.Configuration
     internal sealed class MachineSettingsSection // ConfigurationSection
     {
         private static readonly MachineSettingsSection s_section = new MachineSettingsSection();
-        private static TimeSpan s_maxTimeout = TimeSpan.Parse(ConfigurationStrings.DefaultMaxTimeout);
+        private static readonly TimeSpan s_maxTimeout = TimeSpan.Parse(ConfigurationStrings.DefaultMaxTimeout);
 
         internal static MachineSettingsSection GetSection() => s_section;
 
-        public static TimeSpan MaxTimeout
-        {
-            get { return s_maxTimeout; }
-        }
+        public static TimeSpan MaxTimeout => s_maxTimeout;
     }
 }
index 511c52a..6067bd0 100644 (file)
@@ -8,7 +8,7 @@ namespace System.Transactions.DtcProxyShim;
 
 internal sealed class Phase0EnlistmentShim
 {
-    private Phase0NotifyShim _phase0NotifyShim;
+    private readonly Phase0NotifyShim _phase0NotifyShim;
 
     internal ITransactionPhase0EnlistmentAsync? Phase0EnlistmentAsync { get; set; }
 
index 44f1ce3..0c428d6 100644 (file)
@@ -8,8 +8,8 @@ namespace System.Transactions.DtcProxyShim;
 
 internal sealed class TransactionShim
 {
-    private DtcProxyShimFactory _shimFactory;
-    private TransactionNotifyShim _transactionNotifyShim;
+    private readonly DtcProxyShimFactory _shimFactory;
+    private readonly TransactionNotifyShim _transactionNotifyShim;
 
     internal ITransaction Transaction { get; set; }
 
index ce30734..d7a90a6 100644 (file)
@@ -7,7 +7,7 @@ namespace System.Transactions.DtcProxyShim;
 
 internal sealed class VoterBallotShim
 {
-    private VoterNotifyShim _voterNotifyShim;
+    private readonly VoterNotifyShim _voterNotifyShim;
 
     internal ITransactionVoterBallotAsync2? VoterBallotAsync2 { get; set; }
 
index 55791a7..ee49c6c 100644 (file)
@@ -10,7 +10,7 @@ namespace System.Transactions.Oletx;
 [Serializable]
 internal sealed class OletxDependentTransaction : OletxTransaction
 {
-    private OletxVolatileEnlistmentContainer _volatileEnlistmentContainer;
+    private readonly OletxVolatileEnlistmentContainer _volatileEnlistmentContainer;
 
     private int _completed;
 
index 25d5b6f..a5392d2 100644 (file)
@@ -26,13 +26,13 @@ internal sealed class OletxEnlistment : OletxBaseEnlistment, IPromotedEnlistment
     }
 
     private Phase0EnlistmentShim? _phase0Shim;
-    private bool _canDoSinglePhase;
+    private readonly bool _canDoSinglePhase;
     private IEnlistmentNotificationInternal? _iEnlistmentNotification;
     // The information that comes from/goes to the proxy.
     private byte[]? _proxyPrepareInfoByteArray;
 
     private bool _isSinglePhase;
-    private Guid _transactionGuid = Guid.Empty;
+    private readonly Guid _transactionGuid = Guid.Empty;
 
     // Set to true if we receive an AbortRequest while we still have
     // another notification, like prepare, outstanding.  It indicates that
index 2010fc6..c85ebe1 100644 (file)
@@ -35,7 +35,7 @@ namespace System.Transactions.Oletx
         // filled with the propagation token from the serialization info.  Later, when
         // GetRealObject is called, this array is used to decide whether or not a new
         // transation needs to be created and if so, to create the transaction.
-        private byte[]? _propagationTokenForDeserialize;
+        private readonly byte[]? _propagationTokenForDeserialize;
 
         protected int Disposed;
 
@@ -462,7 +462,7 @@ namespace System.Transactions.Oletx
         // Transaction manager
         internal OletxTransactionManager OletxTransactionManagerInstance { get; }
 
-        private TransactionShim? _transactionShim;
+        private readonly TransactionShim? _transactionShim;
 
         // guid related to transaction
         internal Guid TxGuid { get; private set; }
@@ -492,7 +492,7 @@ namespace System.Transactions.Oletx
         internal OletxPhase1VolatileEnlistmentContainer? Phase1EnlistVolatilementContainer;
 
         // Used to get outcomes of transactions with a voter.
-        private OutcomeEnlistment? _outcomeEnlistment;
+        private readonly OutcomeEnlistment? _outcomeEnlistment;
 
         // This is a count of volatile and Phase0 durable enlistments on this transaction that have not yet voted.
         // This is incremented when an enlistment is made and decremented when the
@@ -514,8 +514,8 @@ namespace System.Transactions.Oletx
         // Enlistments on all clones of this Real transaction use this value.
         internal int _enlistmentCount;
 
-        private DateTime _creationTime;
-        private DateTime _lastStateChangeTime;
+        private readonly DateTime _creationTime;
+        private readonly DateTime _lastStateChangeTime;
         private TransactionTraceIdentifier _traceIdentifier = TransactionTraceIdentifier.Empty;
 
         // This field is set directly from the OletxCommittableTransaction constructor.  It will be null
index fccb1df..0843743 100644 (file)
@@ -10,9 +10,9 @@ namespace System.Transactions.Oletx;
 
 internal sealed class OletxTransactionManager
 {
-    private IsolationLevel _isolationLevelProperty;
+    private readonly IsolationLevel _isolationLevelProperty;
 
-    private TimeSpan _timeoutProperty;
+    private readonly TimeSpan _timeoutProperty;
 
     private TransactionOptions _configuredTransactionOptions = default;
 
@@ -27,7 +27,7 @@ internal sealed class OletxTransactionManager
     internal static volatile bool ProcessingTmDown;
 
     internal ReaderWriterLock DtcTransactionManagerLock;
-    private DtcTransactionManager _dtcTransactionManager;
+    private readonly DtcTransactionManager _dtcTransactionManager;
     internal OletxInternalResourceManager InternalResourceManager;
 
     internal static DtcProxyShimFactory ProxyShimFactory = null!; // Late initialization
@@ -50,7 +50,7 @@ internal sealed class OletxTransactionManager
         }
     }
 
-    private string? _nodeNameField;
+    private readonly string? _nodeNameField;
 
     internal static void ShimNotificationCallback(object? state, bool timeout)
     {
@@ -682,7 +682,7 @@ internal sealed class OletxTransactionManager
 
 internal sealed class OletxInternalResourceManager
 {
-    private OletxTransactionManager _oletxTm;
+    private readonly OletxTransactionManager _oletxTm;
 
     internal Guid Identifier { get; }
 
index 763d113..baed177 100644 (file)
@@ -996,7 +996,7 @@ internal sealed class OletxVolatileEnlistment : OletxBaseEnlistment, IPromotedEn
         Done
     }
 
-    private IEnlistmentNotificationInternal _iEnlistmentNotification;
+    private readonly IEnlistmentNotificationInternal _iEnlistmentNotification;
     private OletxVolatileEnlistmentState _state = OletxVolatileEnlistmentState.Active;
     private OletxVolatileEnlistmentContainer? _container;
     internal bool EnlistDuringPrepareRequired;