{
internal class DbMetaDataFactory
{
- private DataSet _metaDataCollectionsDataSet;
+ private readonly DataSet _metaDataCollectionsDataSet;
private string _normalizedServerVersion;
private string _serverVersionString;
// well known column names
//
internal abstract class DebugSafeHandleMinusOneIsInvalid : SafeHandleMinusOneIsInvalid
{
- private string _trace;
+ private readonly string _trace;
protected DebugSafeHandleMinusOneIsInvalid(bool ownsHandle) : base(ownsHandle)
{
//
internal abstract class DebugSafeHandleZeroOrMinusOneIsInvalid : SafeHandleZeroOrMinusOneIsInvalid
{
- private string _trace;
+ private readonly string _trace;
protected DebugSafeHandleZeroOrMinusOneIsInvalid(bool ownsHandle) : base(ownsHandle)
{
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()
{
/// </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.
/// </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.
private bool _disposed;
- private ConcurrentDictionary<Type, Func<ServiceProviderEngineScope, object?>> _realizedServices;
+ private readonly ConcurrentDictionary<Type, Func<ServiceProviderEngineScope, object?>> _realizedServices;
internal CallSiteFactory CallSiteFactory { get; }
{
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;
{
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) { }
private Timer? _timer;
private bool _timerInitialized;
private object _timerLock = new();
- private Func<Timer> _timerFactory;
+ private readonly Func<Timer> _timerFactory;
private bool _disposed;
/// <summary>
{
internal sealed class InMemoryFileInfo : FileInfoBase
{
- private InMemoryDirectoryInfo _parent;
+ private readonly InMemoryDirectoryInfo _parent;
public InMemoryFileInfo(string file, InMemoryDirectoryInfo parent)
{
{
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) { }
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;
{
internal sealed class ConfigureContainerAdapter<TContainerBuilder> : IConfigureContainerAdapter
{
- private Action<HostBuilderContext, TContainerBuilder> _action;
+ private readonly Action<HostBuilderContext, TContainerBuilder> _action;
public ConfigureContainerAdapter(Action<HostBuilderContext, TContainerBuilder> action)
{
{
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)
{
/// </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;
/// </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;
{
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;
long end = Stopwatch.GetTimestamp();
long timestampDelta = end - _startTimestamp;
- long ticks = (long)(TimestampToTicks * timestampDelta);
+ long ticks = (long)(s_timestampToTicks * timestampDelta);
return new TimeSpan(ticks);
}
}
{
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;
{
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);
});
}
private ConcurrentDictionary<string, ConsoleFormatter> _formatters;
private readonly ConsoleLoggerProcessor _messageQueue;
- private IDisposable? _optionsReloadToken;
+ private readonly IDisposable? _optionsReloadToken;
private IExternalScopeProvider _scopeProvider = NullExternalScopeProvider.Instance;
/// <summary>
IOptionsMonitor<TOptions>
where TOptions : ConsoleFormatterOptions
{
- private TOptions _options;
+ private readonly TOptions _options;
+
public FormatterOptionsMonitor(TOptions options)
{
_options = options;
{
internal sealed class JsonConsoleFormatter : ConsoleFormatter, IDisposable
{
- private IDisposable? _optionsReloadToken;
+ private readonly IDisposable? _optionsReloadToken;
public JsonConsoleFormatter(IOptionsMonitor<JsonConsoleFormatterOptions> options)
: base(ConsoleFormatterNames.Json)
#else
private static bool IsAndroidOrAppleMobile => false;
#endif
- private IDisposable? _optionsReloadToken;
+ private readonly IDisposable? _optionsReloadToken;
public SimpleConsoleFormatter(IOptionsMonitor<SimpleConsoleFormatterOptions> options)
: base(ConsoleFormatterNames.Simple)
{
internal sealed class SystemdConsoleFormatter : ConsoleFormatter, IDisposable
{
- private IDisposable? _optionsReloadToken;
+ private readonly IDisposable? _optionsReloadToken;
public SystemdConsoleFormatter(IOptionsMonitor<ConsoleFormatterOptions> options)
: base(ConsoleFormatterNames.Systemd)
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.
{
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)
{
/// <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.
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)
{
{
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)
{
/// </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)
{
private sealed class StreamWrapper : Stream
{
- private Stream _stream;
+ private readonly Stream _stream;
private bool _readFirstByte;
internal byte _firstByte;
+
public StreamWrapper(Stream stream)
{
_stream = stream;
{
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)) { }
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))
{
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()
{
[ThreadStatic]
private static Scope? s_activeScope;
- private Scope m_instanceScope;
+ private readonly Scope m_instanceScope;
private const string AppDomainDataSetDefaultAllowedTypesKey = "System.Data.DataSetDefaultAllowedTypes";
/// <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.
private readonly WaitCallback _poolCreateRequest;
private int _waitCount;
- private PoolWaitHandles _waitHandles;
+ private readonly PoolWaitHandles _waitHandles;
private Exception? _resError;
private volatile bool _errorOccurred;
internal class DbMetaDataFactory
{ // V1.2.3300
- private DataSet _metaDataCollectionsDataSet;
+ private readonly DataSet _metaDataCollectionsDataSet;
private string _normalizedServerVersion;
private string _serverVersionString;
// well known column names
/// </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.
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,
{
// 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;
/// </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)
{
/// </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)
{
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;
/// </summary>
public sealed class BufferedGraphics : IDisposable
{
- private Graphics? _targetGraphics;
+ private readonly Graphics? _targetGraphics;
private readonly IntPtr _targetDC;
private Graphics _bufferedGraphicsSurface;
private BufferedGraphicsContext _context;
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)
/// </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;
}
}
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.
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.
{
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;
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;
// Mutable struct! Don't make this readonly
private BufferSegmentStack _bufferSegmentPool;
- private StreamPipeReaderOptions _options;
+ private readonly StreamPipeReaderOptions _options;
/// <summary>
/// Creates a new StreamPipeReader.
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
private object[]? _specialCollectionsSlots;
private HttpGeneralHeaders? _generalHeaders;
- private bool _containsTrailingHeaders;
+ private readonly bool _containsTrailingHeaders;
#region Response 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))
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;
{
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()
// 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;
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;
private Action<object?>? _cancellationAction;
private GCHandle _keepAlive;
- private TaskCompletionSource _finalTaskSource;
+ private readonly TaskCompletionSource _finalTaskSource;
public ResettableValueTaskSource(bool runContinuationsAsynchronously = true)
{
}
};
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" />.
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"/>
/// <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.
// Synchronized wrapper for hashtable
private sealed class SyncHashtable : Hashtable, IEnumerable
{
- private Hashtable _table;
+ private readonly Hashtable _table;
internal SyncHashtable(Hashtable table) : base(false)
{
{
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
// 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]
ushort[]? casingTable = s_casingTable[pageNumber];
- if (casingTable == s_noCasingPage)
+ if (casingTable == NoCasingPage)
{
return c;
}
// 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;
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;
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)
{
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)
[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.
/// </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)
{
private long _overflowCount;
// dummy node serving as a start and end of the ring list
- private ThreadLocalNode _nodes;
+ private readonly ThreadLocalNode _nodes;
public ThreadInt64PersistentCounter()
{
/// 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;
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)
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;
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)
{
internal sealed class DataContractPairKey
{
- private object _object1;
- private object _object2;
+ private readonly object _object1;
+ private readonly object _object2;
internal DataContractPairKey(object object1, object object2)
{
private int _attributeCount;
private int _attributeIndex;
- private Hashtable _cache = new Hashtable();
+ private readonly Hashtable _cache = new Hashtable();
private XmlNodeReader? _xmlNodeReader;
private Queue<IDataNode>? _deserializedDataNodes;
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;
private readonly XmlResolver? _xmlResolver;
private readonly ValidationEventHandler? _validationEvent;
private ValidatingReaderState _validationState;
- private XmlValueGetter _valueGetter;
+ private readonly XmlValueGetter _valueGetter;
// namespace management
private readonly XmlNamespaceManager? _nsManager;
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;
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;
/// </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)
{
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]
{
{
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()
{
{
internal sealed class XPathMultyIterator : ResettableIterator
{
- private ResettableIterator[] arr;
+ private readonly ResettableIterator[] arr;
private int firstNotEmpty;
private int position;
/// </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]
[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))
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;
}
}
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
{
internal sealed class ArrayJSGenerator : PrimitiveJSGenerator
{
- private MarshalerType _elementMarshalerType;
+ private readonly MarshalerType _elementMarshalerType;
+
public ArrayJSGenerator(MarshalerType elementMarshalerType)
: base(MarshalerType.Array)
{
{
internal sealed class ArraySegmentJSGenerator : PrimitiveJSGenerator
{
- private MarshalerType _elementMarshalerType;
+ private readonly MarshalerType _elementMarshalerType;
+
public ArraySegmentJSGenerator(MarshalerType elementMarshalerType)
: base(MarshalerType.ArraySegment)
{
{
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())
{
{
internal sealed class SpanJSGenerator : PrimitiveJSGenerator
{
- private MarshalerType _elementMarshalerType;
+ private readonly MarshalerType _elementMarshalerType;
+
public SpanJSGenerator(MarshalerType elementMarshalerType)
: base(MarshalerType.Span)
{
{
internal sealed class TaskJSGenerator : BaseJSGenerator
{
- private MarshalerType _resultMarshalerType;
+ private readonly MarshalerType _resultMarshalerType;
+
public TaskJSGenerator(MarshalerType resultMarshalerType)
: base(MarshalerType.Task, new Forwarder())
{
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)
{
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.
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; }
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;
/// <seealso cref="X500DistinguishedName"/>
public sealed class X500RelativeDistinguishedName
{
- private Oid? _singleElementType;
+ private readonly Oid? _singleElementType;
private readonly ReadOnlyMemory<byte> _singleElementValue;
/// <summary>
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
private readonly MetadataLoadContextInternal _metadataLoadContext;
- private INamedTypeSymbol? _namedTypeSymbol;
+ private readonly INamedTypeSymbol? _namedTypeSymbol;
- private IArrayTypeSymbol? _arrayTypeSymbol;
+ private readonly IArrayTypeSymbol? _arrayTypeSymbol;
private Type? _elementType;
private sealed class DebugView
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
- private JsonArray _node;
+ private readonly JsonArray _node;
public DebugView(JsonArray node)
{
private sealed class DebugView
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
- private JsonObject _node;
+ private readonly JsonObject _node;
public DebugView(JsonObject node)
{
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;
{
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);
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,
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;
{
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
{
private int _permitCount;
private int _queueCount;
- private int[] _requestsPerSegment;
+ private readonly int[] _requestsPerSegment;
private int _currentSegmentIndex;
private long _lastReplenishmentTick;
private long? _idleSince;
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
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;
}
}
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;
}
}
internal sealed class Phase0EnlistmentShim
{
- private Phase0NotifyShim _phase0NotifyShim;
+ private readonly Phase0NotifyShim _phase0NotifyShim;
internal ITransactionPhase0EnlistmentAsync? Phase0EnlistmentAsync { get; set; }
internal sealed class TransactionShim
{
- private DtcProxyShimFactory _shimFactory;
- private TransactionNotifyShim _transactionNotifyShim;
+ private readonly DtcProxyShimFactory _shimFactory;
+ private readonly TransactionNotifyShim _transactionNotifyShim;
internal ITransaction Transaction { get; set; }
internal sealed class VoterBallotShim
{
- private VoterNotifyShim _voterNotifyShim;
+ private readonly VoterNotifyShim _voterNotifyShim;
internal ITransactionVoterBallotAsync2? VoterBallotAsync2 { get; set; }
[Serializable]
internal sealed class OletxDependentTransaction : OletxTransaction
{
- private OletxVolatileEnlistmentContainer _volatileEnlistmentContainer;
+ private readonly OletxVolatileEnlistmentContainer _volatileEnlistmentContainer;
private int _completed;
}
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
// 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;
// Transaction manager
internal OletxTransactionManager OletxTransactionManagerInstance { get; }
- private TransactionShim? _transactionShim;
+ private readonly TransactionShim? _transactionShim;
// guid related to transaction
internal Guid TxGuid { get; private set; }
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
// 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
internal sealed class OletxTransactionManager
{
- private IsolationLevel _isolationLevelProperty;
+ private readonly IsolationLevel _isolationLevelProperty;
- private TimeSpan _timeoutProperty;
+ private readonly TimeSpan _timeoutProperty;
private TransactionOptions _configuredTransactionOptions = default;
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
}
}
- private string? _nodeNameField;
+ private readonly string? _nodeNameField;
internal static void ShimNotificationCallback(object? state, bool timeout)
{
internal sealed class OletxInternalResourceManager
{
- private OletxTransactionManager _oletxTm;
+ private readonly OletxTransactionManager _oletxTm;
internal Guid Identifier { get; }
Done
}
- private IEnlistmentNotificationInternal _iEnlistmentNotification;
+ private readonly IEnlistmentNotificationInternal _iEnlistmentNotification;
private OletxVolatileEnlistmentState _state = OletxVolatileEnlistmentState.Active;
private OletxVolatileEnlistmentContainer? _container;
internal bool EnlistDuringPrepareRequired;