Skip to content

Commit

Permalink
Sprinkle some more readonly around (dotnet#81297)
Browse files Browse the repository at this point in the history
* Sprinkle some more readonly around

* Revert a few changes / address feedback
  • Loading branch information
stephentoub authored Feb 14, 2023
1 parent 6b72404 commit 58d1ecb
Show file tree
Hide file tree
Showing 112 changed files with 261 additions and 267 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ internal static class HostInformationPal
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()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public sealed class ServiceProvider : IServiceProvider, IDisposable, IAsyncDispo

private bool _disposed;

private ConcurrentDictionary<Type, Func<ServiceProviderEngineScope, object?>> _realizedServices;
private readonly ConcurrentDictionary<Type, Func<ServiceProviderEngineScope, object?>> _realizedServices;

internal CallSiteFactory CallSiteFactory { get; }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) { }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public class PhysicalFilesWatcher : IDisposable
private Timer? _timer;
private bool _timerInitialized;
private object _timerLock = new();
private Func<Timer> _timerFactory;
private readonly Func<Timer> _timerFactory;
private bool _disposed;

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) { }
Expand Down
8 changes: 4 additions & 4 deletions src/libraries/Microsoft.Extensions.Hosting/src/HostBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,10 @@ public partial class HostBuilder : IHostBuilder
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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ internal sealed class ServiceFactoryAdapter<TContainerBuilder> : IServiceFactory
{
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)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
6 changes: 3 additions & 3 deletions src/libraries/Microsoft.Extensions.Http/src/ValueStopwatch.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -32,7 +32,7 @@ public TimeSpan GetElapsedTime()

long end = Stopwatch.GetTimestamp();
long timestampDelta = end - _startTimestamp;
long ticks = (long)(TimestampToTicks * timestampDelta);
long ticks = (long)(s_timestampToTicks * timestampDelta);
return new TimeSpan(ticks);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -30,18 +32,18 @@ public FormattedLogValues(string? format, params object?[]? values)
{
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);
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public class ConsoleLoggerProvider : ILoggerProvider, ISupportExternalScope
private ConcurrentDictionary<string, ConsoleFormatter> _formatters;
private readonly ConsoleLoggerProcessor _messageQueue;

private IDisposable? _optionsReloadToken;
private readonly IDisposable? _optionsReloadToken;
private IExternalScopeProvider _scopeProvider = NullExternalScopeProvider.Instance;

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ internal sealed class FormatterOptionsMonitor<[DynamicallyAccessedMembers(Dynami
IOptionsMonitor<TOptions>
where TOptions : ConsoleFormatterOptions
{
private TOptions _options;
private readonly TOptions _options;

public FormatterOptionsMonitor(TOptions options)
{
_options = options;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ internal sealed class SimpleConsoleFormatter : ConsoleFormatter, IDisposable
#else
private static bool IsAndroidOrAppleMobile => false;
#endif
private IDisposable? _optionsReloadToken;
private readonly IDisposable? _optionsReloadToken;

public SimpleConsoleFormatter(IOptionsMonitor<SimpleConsoleFormatterOptions> options)
: base(ConsoleFormatterNames.Simple)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ public class LoggerFactory : ILoggerFactory
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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ private sealed class ActivityLogScope : IReadOnlyList<KeyValuePair<string, objec
{
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)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,7 @@ private static bool CompatibilityMapEquals(IDictionary<string, IEnumerable<strin
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)
{

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,10 @@ private static void SerializeWithBinaryFormatter(Stream o, string cryptoKey, Des

private sealed class StreamWrapper : Stream
{
private Stream _stream;
private readonly Stream _stream;
private bool _readFirstByte;
internal byte _firstByte;

public StreamWrapper(Stream stream)
{
_stream = stream;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)) { }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,12 +82,12 @@ internal sealed class ListenerElement : TypedElement
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))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ internal class TypedElement : ConfigurationElement
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()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ internal sealed class TypeLimiter
[ThreadStatic]
private static Scope? s_activeScope;

private Scope m_instanceScope;
private readonly Scope m_instanceScope;

private const string AppDomainDataSetDefaultAllowedTypesKey = "System.Data.DataSetDefaultAllowedTypes";

Expand Down Expand Up @@ -183,7 +183,7 @@ private sealed class Scope : IDisposable
/// <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.
Expand Down
Loading

0 comments on commit 58d1ecb

Please sign in to comment.