diff --git a/.editorconfig b/.editorconfig index a00fd02dd66..5e367c0750b 100644 --- a/.editorconfig +++ b/.editorconfig @@ -135,6 +135,21 @@ csharp_style_inlined_variable_declaration = true:suggestion csharp_style_throw_expression = true:suggestion csharp_style_conditional_delegate_call = true:suggestion +# Force rules + +# IDE0044: Add readonly modifier +dotnet_style_readonly_field = true:error +# IDE1006: Naming Styles +dotnet_diagnostic.IDE1006.severity = error +# IDE0003: Remove qualification +dotnet_style_qualification_for_method = false:none +# IDE0003: Remove qualification +dotnet_style_qualification_for_field = false:none +# IDE0003: Remove qualification +dotnet_style_qualification_for_property = false:none +# IDE0003: Remove qualification +dotnet_style_qualification_for_event = false:none + # Space preferences csharp_space_after_cast = false csharp_space_after_colon_in_inheritance_clause = true diff --git a/PowerShell.sln b/PowerShell.sln index b164361d7d2..cf90983621d 100644 --- a/PowerShell.sln +++ b/PowerShell.sln @@ -1,7 +1,6 @@ Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -# https://github.com/dotnet/project-system/blob/master/docs/opening-with-new-project-system.md#project-type-guids -VisualStudioVersion = 15.0.26730.12 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29806.167 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "powershell-win-core", "src\powershell-win-core\powershell-win-core.csproj", "{8359D422-E0C4-4A0D-94EB-3C9DD16B7932}" EndProject @@ -42,6 +41,11 @@ EndProject # # 73EA0BE6-C0C5-4B56-A5AA-DADA4C01D690 - powershell-unix # Only Linux is valid, all configurations mapped to Linux +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{D0361BC1-7403-4662-B918-215480B5CD17}" + ProjectSection(SolutionItems) = preProject + .editorconfig = .editorconfig + EndProjectSection +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution CodeCoverage|Any CPU = CodeCoverage|Any CPU diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs index 1e21b781742..98571d475ea 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs @@ -559,14 +559,14 @@ private void Cleanup() /// /// Event to notify ps thread that more action is available. /// - private ManualResetEventSlim moreActionEvent; + private readonly ManualResetEventSlim moreActionEvent; /// /// The following is the definition of action queue. /// The queue holding all actions to be executed in the context of either /// ProcessRecord or EndProcessing. /// - private ConcurrentQueue actionQueue; + private readonly ConcurrentQueue actionQueue; /// /// Lock object. diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimBaseAction.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimBaseAction.cs index 345b27bb48b..0ac7ac5c1cb 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimBaseAction.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimBaseAction.cs @@ -126,7 +126,7 @@ protected virtual void Block() /// /// Action completed event. /// - private ManualResetEventSlim completeEvent; + private readonly ManualResetEventSlim completeEvent; /// /// Response result. diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCmdletModuleInitialize.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCmdletModuleInitialize.cs index 72f6f0e28e4..a931ca66f85 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCmdletModuleInitialize.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCmdletModuleInitialize.cs @@ -79,21 +79,21 @@ internal CimCmdletAliasEntry(string name, string value) /// internal string Name { get { return this._name; } } - private string _name; + private readonly string _name; /// /// The string defining real cmdlet name. /// internal string Value { get { return this._value; } } - private string _value = string.Empty; + private readonly string _value = string.Empty; /// /// The string defining real cmdlet name. /// internal ScopedItemOptions Options { get { return this._options; } } - private ScopedItemOptions _options = ScopedItemOptions.AllScope | ScopedItemOptions.ReadOnly; + private readonly ScopedItemOptions _options = ScopedItemOptions.AllScope | ScopedItemOptions.ReadOnly; } /// diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs index 6420fe28909..6b1395e3fd5 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs @@ -261,7 +261,7 @@ internal ParameterBinder( /// /// Parameter names list. /// - private List parameterNamesList = new List(); + private readonly List parameterNamesList = new List(); /// /// @@ -275,7 +275,7 @@ internal ParameterBinder( /// /// Parameter names list before begin process. /// - private List parameterNamesListAtBeginProcess = new List(); + private readonly List parameterNamesListAtBeginProcess = new List(); /// /// @@ -676,7 +676,7 @@ protected virtual void DisposeInternal() /// /// Parameter binder used to resolve parameter set name. /// - private ParameterBinder parameterBinder; + private readonly ParameterBinder parameterBinder; /// /// diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetCimClass.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetCimClass.cs index a3826487e24..1d053a2b0dd 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetCimClass.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetCimClass.cs @@ -68,7 +68,7 @@ internal string MethodName get { return methodName; } } - private string methodName; + private readonly string methodName; /// /// @@ -82,7 +82,7 @@ internal string PropertyName get { return propertyName; } } - private string propertyName; + private readonly string propertyName; /// /// @@ -96,7 +96,7 @@ internal string QualifierName get { return qualifierName; } } - private string qualifierName; + private readonly string qualifierName; } /// diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs index fd44d922009..198c86e96af 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs @@ -53,7 +53,7 @@ public Exception Exception } } - private Exception exception; + private readonly Exception exception; /// /// @@ -124,7 +124,7 @@ public CimIndicationEventInstanceEventArgs(CimSubscriptionResult result) /// subscription result /// /// - private CimSubscriptionResult result; + private readonly CimSubscriptionResult result; } /// diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs index 74f4a571dd2..801939e5c48 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs @@ -57,7 +57,7 @@ internal string MethodName } } - private string methodName; + private readonly string methodName; /// /// parameters collection @@ -70,7 +70,7 @@ internal CimMethodParametersCollection ParametersCollection } } - private CimMethodParametersCollection collection; + private readonly CimMethodParametersCollection collection; } /// diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimPromptUser.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimPromptUser.cs index 4d4ff5d6ec5..98fb4ed3fc8 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimPromptUser.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimPromptUser.cs @@ -129,12 +129,12 @@ public string Message } } - private string message; + private readonly string message; /// /// Prompt type -Normal or Critical. /// - private CimPromptType prompt; + private readonly CimPromptType prompt; #endregion } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs index 5dee76e5f3c..ca61e4403d4 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs @@ -56,7 +56,7 @@ public CimSubscriptionResult Result } } - private CimSubscriptionResult result; + private readonly CimSubscriptionResult result; /// /// Constructor @@ -90,7 +90,7 @@ public Exception Exception } } - private Exception exception; + private readonly Exception exception; /// /// Constructor diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs index 55cf540c0e8..f357ccee1f5 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs @@ -51,7 +51,7 @@ internal object ErrorSource } } - private object errorSource; + private readonly object errorSource; } #endregion @@ -352,17 +352,17 @@ protected CimSession CurrentSession } } - private CimSession session; + private readonly CimSession session; /// /// Async operation that can be observed. /// - private IObservable observable; + private readonly IObservable observable; /// /// object used during delivering result. /// - private CimResultContext context; + private readonly CimResultContext context; #endregion } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs index 28d93fc668a..6c74fdf1198 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs @@ -32,7 +32,7 @@ public uint SessionId } } - private uint sessionId; + private readonly uint sessionId; /// /// InstanceId of the cimsession. @@ -58,7 +58,7 @@ public string Name } } - private string name; + private readonly string name; /// /// Computer name of the cimsession. @@ -71,7 +71,7 @@ public string ComputerName } } - private string computerName; + private readonly string computerName; /// /// Wrapped cimsession object. @@ -84,7 +84,7 @@ public CimSession CimSession } } - private CimSession cimSession; + private readonly CimSession cimSession; /// /// Computer name of the cimsession. @@ -110,7 +110,7 @@ internal ProtocolType GetProtocolType() return protocol; } - private ProtocolType protocol; + private readonly ProtocolType protocol; /// /// PSObject that wrapped the cimSession. @@ -231,35 +231,35 @@ internal class CimSessionState : IDisposable /// Dictionary used to holds all CimSessions in current runspace by session name. /// /// - private Dictionary> curCimSessionsByName; + private readonly Dictionary> curCimSessionsByName; /// /// /// Dictionary used to holds all CimSessions in current runspace by computer name. /// /// - private Dictionary> curCimSessionsByComputerName; + private readonly Dictionary> curCimSessionsByComputerName; /// /// /// Dictionary used to holds all CimSessions in current runspace by instance ID. /// /// - private Dictionary curCimSessionsByInstanceId; + private readonly Dictionary curCimSessionsByInstanceId; /// /// /// Dictionary used to holds all CimSessions in current runspace by session id. /// /// - private Dictionary curCimSessionsById; + private readonly Dictionary curCimSessionsById; /// /// /// Dictionary used to link CimSession object with PSObject. /// /// - private Dictionary curCimSessionWrapper; + private readonly Dictionary curCimSessionWrapper; #endregion @@ -934,7 +934,7 @@ internal CimSessionWrapper CimSessionWrapper } } - private CimSessionWrapper cimSessionWrapper; + private readonly CimSessionWrapper cimSessionWrapper; } /// @@ -1052,7 +1052,7 @@ public void ProcessRemainActions(CmdletOperationBase cmdletOperation) /// object. /// /// - private CimTestSession cimTestSession; + private readonly CimTestSession cimTestSession; #endregion // private members #region IDisposable diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs index a8e4fcd977f..99e36083ff3 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs @@ -218,7 +218,7 @@ internal class CimSessionProxy : IDisposable /// then call Dispose on it. /// /// - private static Dictionary temporarySessionCache = new Dictionary(); + private static readonly Dictionary temporarySessionCache = new Dictionary(); /// /// @@ -1065,7 +1065,7 @@ private static void AddShowComputerNameMarker(object o) } #if DEBUG - private static bool isCliXmlTestabilityHookActive = GetIsCliXmlTestabilityHookActive(); + private static readonly bool isCliXmlTestabilityHookActive = GetIsCliXmlTestabilityHookActive(); private static bool GetIsCliXmlTestabilityHookActive() { return !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("CDXML_CLIXML_TEST")); @@ -1567,7 +1567,7 @@ private bool Completed /// /// The current operation parameters. /// - private Hashtable operationParameters = new Hashtable(); + private readonly Hashtable operationParameters = new Hashtable(); /// /// Handler used to cancel operation. @@ -1675,7 +1675,7 @@ internal IObjectPreProcess ObjectPreProcess /// created to handle the "default" session, in cases where cmdlets are invoked without /// ComputerName and/or CimSession parameters. /// - private bool isDefaultSession; + private readonly bool isDefaultSession; #endregion @@ -2259,7 +2259,7 @@ protected override bool PreNewActionEvent(CmdletActionEventArgs args) #region private members - private CimNewCimInstance newCimInstance = null; + private readonly CimNewCimInstance newCimInstance = null; internal CimNewCimInstance NewCimInstanceOperation { get @@ -2348,7 +2348,7 @@ protected override bool PreNewActionEvent(CmdletActionEventArgs args) /// /// Ture indicates need to output the modified result. /// - private bool passThru = false; + private readonly bool passThru = false; #endregion } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSetCimInstance.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSetCimInstance.cs index d55532e805e..674eadfbe66 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSetCimInstance.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSetCimInstance.cs @@ -51,7 +51,7 @@ internal IDictionary Property } } - private IDictionary property; + private readonly IDictionary property; /// /// parameter set name @@ -64,7 +64,7 @@ internal string ParameterSetName } } - private string parameterSetName; + private readonly string parameterSetName; /// /// PassThru value @@ -77,7 +77,7 @@ internal bool PassThru } } - private bool passThru; + private readonly bool passThru; } /// diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs index fbd780450ab..9d367877a4c 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs @@ -375,7 +375,7 @@ public override void Execute(CmdletOperationBase cmdlet) /// Error instance /// /// - private CimInstance error; + private readonly CimInstance error; internal CimInstance Error { @@ -398,7 +398,7 @@ internal Exception Exception } } - private Exception exception; + private readonly Exception exception; /// /// @@ -406,7 +406,7 @@ internal Exception Exception /// the information while issuing the current operation /// /// - private InvocationContext invocationContext; + private readonly InvocationContext invocationContext; internal InvocationContext CimInvocationContext { @@ -419,7 +419,7 @@ internal InvocationContext CimInvocationContext /// /// /// - private CimResultContext cimResultContext; + private readonly CimResultContext cimResultContext; internal CimResultContext ResultContext { diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteMessage.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteMessage.cs index b351813c4d4..9a556b68c5e 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteMessage.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteMessage.cs @@ -22,12 +22,12 @@ internal sealed class CimWriteMessage : CimBaseAction /// /// Channel id. /// - private UInt32 channel; + private readonly UInt32 channel; /// /// Message to write to the channel. /// - private string message; + private readonly string message; #endregion #region Properties diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteProgress.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteProgress.cs index 720f5537d2b..e6651ed94ff 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteProgress.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteProgress.cs @@ -92,32 +92,32 @@ public override void Execute(CmdletOperationBase cmdlet) /// /// Activity of the given activity. /// - private string activity; + private readonly string activity; /// /// Activity identifier of the given activity. /// - private int activityID; + private readonly int activityID; /// /// Current operation text of the given activity. /// - private string currentOperation; + private readonly string currentOperation; /// /// Status description of the given activity. /// - private string statusDescription; + private readonly string statusDescription; /// /// Percentage completed of the given activity. /// - private UInt32 percentageCompleted; + private readonly UInt32 percentageCompleted; /// /// How many seconds remained for the given activity. /// - private UInt32 secondsRemaining; + private readonly UInt32 secondsRemaining; internal string Activity { diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteResultObject.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteResultObject.cs index b1ef21600ed..9a31f1c318e 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteResultObject.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteResultObject.cs @@ -47,7 +47,7 @@ internal object Result } } - private object result; + private readonly object result; #endregion } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs index 648f6cfb327..8e3cf15df58 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs @@ -188,7 +188,7 @@ public override void WriteObject(object sendToPipeline, bool enumerateCollection #region private methods - private CimRemoveCimInstance removeCimInstance; + private readonly CimRemoveCimInstance removeCimInstance; private const string cimRemoveCimInstanceParameterName = @"cimRemoveCimInstance"; @@ -268,7 +268,7 @@ public override void WriteObject(object sendToPipeline, bool enumerateCollection #region private methods - private CimSetCimInstance setCimInstance; + private readonly CimSetCimInstance setCimInstance; private const string theCimSetCimInstanceParameterName = @"theCimSetCimInstance"; @@ -331,7 +331,7 @@ public override void WriteObject(object sendToPipeline, bool enumerateCollection #region private methods - private CimInvokeCimMethod cimInvokeCimMethod; + private readonly CimInvokeCimMethod cimInvokeCimMethod; private const string theCimInvokeCimMethodParameterName = @"theCimInvokeCimMethod"; @@ -392,7 +392,7 @@ public override void WriteObject(object sendToPipeline, XOperationContextBase co #region private methods - private CimNewSession cimNewSession; + private readonly CimNewSession cimNewSession; private const string theCimNewSessionParameterName = @"theCimNewSession"; diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs index 06754aae168..13f3d17b689 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs @@ -318,7 +318,7 @@ CimGetAssociatedInstance CreateOperationAgent() /// /// Static parameter definition entries. /// - static Dictionary> parameters = new Dictionary> + static readonly Dictionary> parameters = new Dictionary> { { nameComputerName, new HashSet { @@ -347,7 +347,7 @@ CimGetAssociatedInstance CreateOperationAgent() /// /// Static parameter set entries. /// - static Dictionary parameterSets = new Dictionary + static readonly Dictionary parameterSets = new Dictionary { { CimBaseCommand.SessionSetName, new ParameterSetEntry(2, false) }, { CimBaseCommand.ComputerSetName, new ParameterSetEntry(1, true) }, diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs index 0c2032720a0..d695f9a0431 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs @@ -291,7 +291,7 @@ CimGetCimClass CreateOperationAgent() /// /// Static parameter definition entries. /// - static Dictionary> parameters = new Dictionary> + static readonly Dictionary> parameters = new Dictionary> { { nameCimSession, new HashSet { @@ -309,7 +309,7 @@ CimGetCimClass CreateOperationAgent() /// /// Static parameter set entries. /// - static Dictionary parameterSets = new Dictionary + static readonly Dictionary parameterSets = new Dictionary { { CimBaseCommand.SessionSetName, new ParameterSetEntry(1) }, { CimBaseCommand.ComputerSetName, new ParameterSetEntry(0, true) }, diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs index ba5f6125a7f..ab823258da9 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs @@ -552,7 +552,7 @@ private void CheckArgument() /// /// Static parameter definition entries. /// - static Dictionary> parameters = new Dictionary> + static readonly Dictionary> parameters = new Dictionary> { { nameCimSession, new HashSet { @@ -656,7 +656,7 @@ private void CheckArgument() /// /// Static parameter set entries. /// - static Dictionary parameterSets = new Dictionary + static readonly Dictionary parameterSets = new Dictionary { { CimBaseCommand.CimInstanceComputerSet, new ParameterSetEntry(1) }, { CimBaseCommand.CimInstanceSessionSet, new ParameterSetEntry(2) }, diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimSessionCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimSessionCommand.cs index 459c777c817..8355822d2e2 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimSessionCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimSessionCommand.cs @@ -173,7 +173,7 @@ protected override void ProcessRecord() /// /// Static parameter definition entries. /// - static Dictionary> parameters = new Dictionary> + static readonly Dictionary> parameters = new Dictionary> { { nameComputerName, new HashSet { @@ -200,7 +200,7 @@ protected override void ProcessRecord() /// /// Static parameter set entries. /// - static Dictionary parameterSets = new Dictionary + static readonly Dictionary parameterSets = new Dictionary { { CimBaseCommand.ComputerNameSet, new ParameterSetEntry(0, true) }, { CimBaseCommand.SessionIdSet, new ParameterSetEntry(1) }, diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs index b4d58032739..e2bbc81eaec 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs @@ -473,7 +473,7 @@ private void CheckArgument() /// /// Static parameter definition entries. /// - static Dictionary> parameters = new Dictionary> + static readonly Dictionary> parameters = new Dictionary> { { nameClassName, new HashSet { @@ -560,7 +560,7 @@ private void CheckArgument() /// /// Static parameter set entries. /// - static Dictionary parameterSets = new Dictionary + static readonly Dictionary parameterSets = new Dictionary { { CimBaseCommand.ClassNameComputerSet, new ParameterSetEntry(2, true) }, { CimBaseCommand.ResourceUriSessionSet, new ParameterSetEntry(3) }, diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs index 444dcd1f32c..f22093d161f 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs @@ -440,7 +440,7 @@ private void CheckArgument() /// /// Static parameter definition entries. /// - static Dictionary> parameters = new Dictionary> + static readonly Dictionary> parameters = new Dictionary> { { nameClassName, new HashSet { @@ -503,7 +503,7 @@ private void CheckArgument() /// /// Static parameter set entries. /// - static Dictionary parameterSets = new Dictionary + static readonly Dictionary parameterSets = new Dictionary { { CimBaseCommand.ClassNameSessionSet, new ParameterSetEntry(2) }, { CimBaseCommand.ClassNameComputerSet, new ParameterSetEntry(1, true) }, diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs index d53403d5e81..4b404457328 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs @@ -709,7 +709,7 @@ internal WSManSessionOptions CreateWSMANSessionOptions() /// /// Static parameter definition entries. /// - static Dictionary> parameters = new Dictionary> + static readonly Dictionary> parameters = new Dictionary> { { nameNoEncryption, new HashSet { @@ -810,7 +810,7 @@ internal WSManSessionOptions CreateWSMANSessionOptions() /// /// Static parameter set entries. /// - static Dictionary parameterSets = new Dictionary + static readonly Dictionary parameterSets = new Dictionary { { CimBaseCommand.ProtocolNameParameterSet, new ParameterSetEntry(1, true) }, { CimBaseCommand.DcomParameterSet, new ParameterSetEntry(0) }, diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs index e34ad952d50..3b713e1ffee 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs @@ -291,7 +291,7 @@ private void CheckArgument() /// /// Parameter binder used to resolve parameter set name. /// - private ParameterBinder parameterBinder = new ParameterBinder( + private readonly ParameterBinder parameterBinder = new ParameterBinder( parameters, parameterSets); /// @@ -319,7 +319,7 @@ private void SetParameter(object value, string parameterName) /// /// Static parameter definition entries. /// - static Dictionary> parameters = new Dictionary> + static readonly Dictionary> parameters = new Dictionary> { { nameClassName, new HashSet { @@ -356,7 +356,7 @@ private void SetParameter(object value, string parameterName) /// /// Static parameter set entries. /// - static Dictionary parameterSets = new Dictionary + static readonly Dictionary parameterSets = new Dictionary { { CimBaseCommand.QueryExpressionSessionSet, new ParameterSetEntry(2) }, { CimBaseCommand.QueryExpressionComputerSet, new ParameterSetEntry(1) }, diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs index c7f2ab4c6a3..ab94a7fca73 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs @@ -322,7 +322,7 @@ CimRemoveCimInstance CreateOperationAgent() /// /// Static parameter definition entries. /// - static Dictionary> parameters = new Dictionary> + static readonly Dictionary> parameters = new Dictionary> { { nameCimSession, new HashSet { @@ -371,7 +371,7 @@ CimRemoveCimInstance CreateOperationAgent() /// /// Static parameter set entries. /// - static Dictionary parameterSets = new Dictionary + static readonly Dictionary parameterSets = new Dictionary { { CimBaseCommand.CimInstanceComputerSet, new ParameterSetEntry(1, true) }, { CimBaseCommand.CimInstanceSessionSet, new ParameterSetEntry(2) }, diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimSessionCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimSessionCommand.cs index 20fae29b593..deca6cc385d 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimSessionCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimSessionCommand.cs @@ -199,7 +199,7 @@ protected override void ProcessRecord() /// /// Static parameter definition entries. /// - static Dictionary> parameters = new Dictionary> + static readonly Dictionary> parameters = new Dictionary> { { nameCimSession, new HashSet { @@ -231,7 +231,7 @@ protected override void ProcessRecord() /// /// Static parameter set entries. /// - static Dictionary parameterSets = new Dictionary + static readonly Dictionary parameterSets = new Dictionary { { CimBaseCommand.CimSessionSet, new ParameterSetEntry(1, true) }, { CimBaseCommand.ComputerNameSet, new ParameterSetEntry(1) }, diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs index 714a192081a..507dcd61097 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs @@ -380,7 +380,7 @@ CimSetCimInstance CreateOperationAgent() /// /// Static parameter definition entries. /// - static Dictionary> parameters = new Dictionary> + static readonly Dictionary> parameters = new Dictionary> { { nameCimSession, new HashSet { @@ -437,7 +437,7 @@ CimSetCimInstance CreateOperationAgent() /// /// Static parameter set entries. /// - static Dictionary parameterSets = new Dictionary + static readonly Dictionary parameterSets = new Dictionary { { CimBaseCommand.QuerySessionSet, new ParameterSetEntry(3) }, { CimBaseCommand.QueryComputerSet, new ParameterSetEntry(2) }, diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSample.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSample.cs index 3a7af308f29..b7d487701b5 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSample.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSample.cs @@ -193,6 +193,6 @@ public PerformanceCounterSample[] CounterSamples private PerformanceCounterSample[] _counterSamples = null; - private ResourceManager _resourceMgr = null; + private readonly ResourceManager _resourceMgr = null; } } diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSet.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSet.cs index c1474ec4209..cece3bffb9b 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSet.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSet.cs @@ -45,7 +45,7 @@ public string CounterSetName } } - private string _counterSetName = string.Empty; + private readonly string _counterSetName = string.Empty; public string MachineName { @@ -55,7 +55,7 @@ public string MachineName } } - private string _machineName = "."; + private readonly string _machineName = "."; public PerformanceCounterCategoryType CounterSetType { @@ -65,7 +65,7 @@ public PerformanceCounterCategoryType CounterSetType } } - private PerformanceCounterCategoryType _counterSetType; + private readonly PerformanceCounterCategoryType _counterSetType; public string Description { @@ -75,7 +75,7 @@ public string Description } } - private string _description = string.Empty; + private readonly string _description = string.Empty; internal Dictionary CounterInstanceMapping { @@ -85,7 +85,7 @@ internal Dictionary CounterInstanceMapping } } - private Dictionary _counterInstanceMapping; + private readonly Dictionary _counterInstanceMapping; public StringCollection Paths { diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs index 566ae6d1d22..8afaeaeff40 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs @@ -92,7 +92,7 @@ public string[] Counter @"\physicaldisk(_total)\current disk queue length"}; private bool _defaultCounters = true; - private List _accumulatedCounters = new List(); + private readonly List _accumulatedCounters = new List(); // // SampleInterval parameter. @@ -178,7 +178,7 @@ public string[] ComputerName private PdhHelper _pdhHelper = null; - private EventWaitHandle _cancelEventArrived = new EventWaitHandle(false, EventResetMode.ManualReset); + private readonly EventWaitHandle _cancelEventArrived = new EventWaitHandle(false, EventResetMode.ManualReset); // Culture identifier(s) private const string FrenchCultureId = "fr-FR"; diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs index 41829598482..9e0e9ceed2e 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs @@ -396,14 +396,14 @@ public SwitchParameter Oldest // Other private members and constants // private ResourceManager _resourceMgr = null; - private Dictionary _providersByLogMap = new Dictionary(); + private readonly Dictionary _providersByLogMap = new Dictionary(); private StringCollection _logNamesMatchingWildcard = null; - private StringCollection _resolvedPaths = new StringCollection(); + private readonly StringCollection _resolvedPaths = new StringCollection(); - private List _accumulatedLogNames = new List(); - private List _accumulatedProviderNames = new List(); - private List _accumulatedFileNames = new List(); + private readonly List _accumulatedLogNames = new List(); + private readonly List _accumulatedProviderNames = new List(); + private readonly List _accumulatedFileNames = new List(); private const uint MAX_EVENT_BATCH = 100; diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs index 1c0acb7f45a..54ed500583b 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs @@ -27,7 +27,7 @@ public sealed class NewWinEventCommand : PSCmdlet private const string TemplateTag = "template"; private const string DataTag = "data"; - private ResourceManager _resourceMgr = Microsoft.PowerShell.Commands.Diagnostics.Common.CommonUtilities.GetResourceManager(); + private readonly ResourceManager _resourceMgr = Microsoft.PowerShell.Commands.Diagnostics.Common.CommonUtilities.GetResourceManager(); /// /// ProviderName. diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs index c6c1ddd8be8..66cafb03371 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs @@ -423,7 +423,7 @@ public void Dispose() // // m_ConsumerPathToHandleAndInstanceMap map is used for reading counter date (live or from files). // - private Dictionary _consumerPathToHandleAndInstanceMap = new Dictionary(); + private readonly Dictionary _consumerPathToHandleAndInstanceMap = new Dictionary(); /// /// A helper reading in a Unicode string with embedded NULLs and splitting it into a StringCollection. diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJobBase.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJobBase.cs index 8ee336de383..b52c23c3dd4 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJobBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJobBase.cs @@ -14,7 +14,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim /// internal abstract class QueryJobBase : CimChildJobBase { - private CimQuery _cimQuery; + private readonly CimQuery _cimQuery; internal QueryJobBase(CimJobContext jobContext, CimQuery cimQuery) : base(jobContext) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs index 578b4a7efde..1a59fb55ff5 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs @@ -319,7 +319,7 @@ public Int16 Delay /// /// The indicator to use when show progress. /// - private string[] _indicator = { "|", "/", "-", "\\" }; + private readonly string[] _indicator = { "|", "/", "-", "\\" }; /// /// The activity id. diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs index 14f8a207ae5..640596e2c4f 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs @@ -85,7 +85,7 @@ private class MiscInfoGroup #endregion Static Data and Constants #region Instance Data - private string _machineName = localMachineName; // we might need to have cmdlet work on another machine + private readonly string _machineName = localMachineName; // we might need to have cmdlet work on another machine /// /// Collection of property names from the Property parameter, diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs index 2ba50c23459..ccdec01cc80 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs @@ -108,7 +108,7 @@ public virtual Process[] InputObject // We use a Dictionary to optimize the check whether the object // is already in the list. private List _matchingProcesses = new List(); - private Dictionary _keys = new Dictionary(); + private readonly Dictionary _keys = new Dictionary(); /// /// Retrieve the list of all processes matching the Name, Id @@ -955,7 +955,7 @@ private void myProcess_Exited(object sender, System.EventArgs e) #region Overrides - private List _processList = new List(); + private readonly List _processList = new List(); // Wait handle which is used by thread to sleep. private ManualResetEvent _waitHandle; @@ -2606,7 +2606,7 @@ internal class ProcessCollection /// JobObjectHandle is a reference to the job object used to track /// the child processes created by the main process hosted by the Start-Process cmdlet. /// - private Microsoft.PowerShell.Commands.SafeJobHandle _jobObjectHandle; + private readonly Microsoft.PowerShell.Commands.SafeJobHandle _jobObjectHandle; /// /// ProcessCollection constructor. diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs index bcb7330c674..4c8a7c36c7b 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs @@ -19,7 +19,7 @@ namespace Microsoft.PowerShell.Commands [Alias("scb")] public class SetClipboardCommand : PSCmdlet { - private List _contentList = new List(); + private readonly List _contentList = new List(); /// /// Property that sets clipboard content. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs index 397ca036151..a3b0f7e15c8 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs @@ -852,7 +852,7 @@ protected override void ProcessRecord() /// internal class ExportCsvHelper : IDisposable { - private char _delimiter; + private readonly char _delimiter; readonly private BaseCsvWritingCommand.QuoteKind _quoteKind; readonly private HashSet _quoteFields; readonly private StringBuilder _outputString; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs index 91985bd17c7..6cab64a4d29 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs @@ -21,17 +21,17 @@ internal class CustomSerialization /// /// Depth of serialization. /// - private int _depth; + private readonly int _depth; /// /// XmlWriter to be used for writing. /// - private XmlWriter _writer; + private readonly XmlWriter _writer; /// /// Whether type information should be included in the xml. /// - private bool _notypeinformation; + private readonly bool _notypeinformation; /// /// CustomerSerializer used for formatting the output for _writer. @@ -191,7 +191,7 @@ internal class /// /// Xml writer to be used. /// - private XmlWriter _writer; + private readonly XmlWriter _writer; /// /// Check first call for every pipeline object to write Object tag else property tag. @@ -201,7 +201,7 @@ internal class /// /// Should the type information to be shown. /// - private bool _notypeinformation; + private readonly bool _notypeinformation; /// /// Check object call. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs index 355d94912af..1a560a0010d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs @@ -43,7 +43,7 @@ public sealed class DebugRunspaceCommand : PSCmdlet // Debugging to persist until Ctrl+C or Debugger 'Exit' stops cmdlet. private bool _debugging; - private ManualResetEventSlim _newRunningScriptEvent = new ManualResetEventSlim(true); + private readonly ManualResetEventSlim _newRunningScriptEvent = new ManualResetEventSlim(true); private RunspaceAvailability _previousRunspaceAvailability = RunspaceAvailability.None; #endregion diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs index 1ac3e781ab7..431f30a3dcc 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs @@ -310,7 +310,7 @@ protected override void EndProcessing() /// /// Holds all the matching aliases for writing to the file. /// - private Collection _matchingAliases = new Collection(); + private readonly Collection _matchingAliases = new Collection(); private static string GetAliasLine(AliasInfo alias, string formatString) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ExpressionColumnInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ExpressionColumnInfo.cs index a9d60def958..0e529004aec 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ExpressionColumnInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ExpressionColumnInfo.cs @@ -11,7 +11,7 @@ namespace Microsoft.PowerShell.Commands { internal class ExpressionColumnInfo : ColumnInfo { - private PSPropertyExpression _expression; + private readonly PSPropertyExpression _expression; internal ExpressionColumnInfo(string staleObjectPropertyName, string displayName, PSPropertyExpression expression) : base(staleObjectPropertyName, displayName) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/HeaderInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/HeaderInfo.cs index d7d863e29b8..c88cdd0bcb0 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/HeaderInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/HeaderInfo.cs @@ -9,7 +9,7 @@ namespace Microsoft.PowerShell.Commands { internal class HeaderInfo { - private List _columns = new List(); + private readonly List _columns = new List(); internal void AddColumn(ColumnInfo col) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs index 48a9004e604..3db37f3528e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs @@ -11,8 +11,8 @@ namespace Microsoft.PowerShell.Commands { internal class OriginalColumnInfo : ColumnInfo { - private string _liveObjectPropertyName; - private OutGridViewCommand _parentCmdlet; + private readonly string _liveObjectPropertyName; + private readonly OutGridViewCommand _parentCmdlet; internal OriginalColumnInfo(string staleObjectPropertyName, string displayName, string liveObjectPropertyName, OutGridViewCommand parentCmdlet) : base(staleObjectPropertyName, displayName) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs index 8ae81bedd24..2945c94612e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs @@ -325,7 +325,7 @@ internal static GridHeader ConstructGridHeader(PSObject input, OutGridViewComman internal class ScalarTypeHeader : GridHeader { - private Type _originalScalarType; + private readonly Type _originalScalarType; internal ScalarTypeHeader(OutGridViewCommand parentCmd, PSObject input) : base(parentCmd) { @@ -351,7 +351,7 @@ internal override void ProcessInputObject(PSObject input) internal class NonscalarTypeHeader : GridHeader { - private AppliesTo _appliesTo = null; + private readonly AppliesTo _appliesTo = null; internal NonscalarTypeHeader(OutGridViewCommand parentCmd, PSObject input) : base(parentCmd) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs index 49d41d8ce3e..97b0dace7e9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs @@ -27,15 +27,15 @@ internal class OutWindowProxy : IDisposable private bool _isWindowStarted; - private string _title; + private readonly string _title; - private OutputModeOption _outputMode; + private readonly OutputModeOption _outputMode; private AutoResetEvent _closedEvent; - private OutGridViewCommand _parentCmdlet; + private readonly OutGridViewCommand _parentCmdlet; - private GraphicalHostReflectionWrapper _graphicalHostReflectionWrapper; + private readonly GraphicalHostReflectionWrapper _graphicalHostReflectionWrapper; /// /// Initializes a new instance of the OutWindowProxy class. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ScalarTypeColumnInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ScalarTypeColumnInfo.cs index b72c9b7d439..77f80c269a3 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ScalarTypeColumnInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ScalarTypeColumnInfo.cs @@ -8,7 +8,7 @@ namespace Microsoft.PowerShell.Commands { internal class ScalarTypeColumnInfo : ColumnInfo { - private Type _type; + private readonly Type _type; internal ScalarTypeColumnInfo(Type type) : base(type.Name, type.Name) @@ -45,7 +45,7 @@ internal override object GetValue(PSObject liveObject) internal class ToStringColumnInfo : ColumnInfo { - private OutGridViewCommand _parentCmdlet; + private readonly OutGridViewCommand _parentCmdlet; internal ToStringColumnInfo(string staleObjectPropertyName, string displayName, OutGridViewCommand parentCmdlet) : base(staleObjectPropertyName, displayName) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/WriteFormatDataCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/WriteFormatDataCommand.cs index 919264ad180..457418b30fc 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/WriteFormatDataCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/WriteFormatDataCommand.cs @@ -75,7 +75,7 @@ public string LiteralPath private bool _isLiteralPath = false; - private List _typeDefinitions = new List(); + private readonly List _typeDefinitions = new List(); private bool _force; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs index 5616a7fa436..84d2f3f2dd5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs @@ -276,7 +276,7 @@ private void pd_PrintPage(object sender, PrintPageEventArgs ev) /// /// Name of the printer to print to. Null means default printer. /// - private string _printerName = null; + private readonly string _printerName = null; /// /// Name of the font to use, if null the default is used. @@ -315,13 +315,13 @@ private void pd_PrintPage(object sender, PrintPageEventArgs ev) /// /// Text lines ready to print (after output cache playback). /// - private Queue _lines = new Queue(); + private readonly Queue _lines = new Queue(); /// /// Cached font object. /// private Font _printFont = null; - private WriteLineHelper _writeLineHelper; + private readonly WriteLineHelper _writeLineHelper; } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-string/Out-String.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-string/Out-String.cs index 5dcb3c4f588..e76d90af8b5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-string/Out-String.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-string/Out-String.cs @@ -166,6 +166,6 @@ protected override void EndProcessing() /// /// Buffer used when buffering until the end. /// - private StringBuilder _buffer = new StringBuilder(); + private readonly StringBuilder _buffer = new StringBuilder(); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs index daa870d9b1a..d917271b4fc 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs @@ -132,7 +132,7 @@ public SwitchParameter Force private MshMemberMatchOptions _matchOptions = MshMemberMatchOptions.None; - private HybridDictionary _typesAlreadyDisplayed = new HybridDictionary(); + private readonly HybridDictionary _typesAlreadyDisplayed = new HybridDictionary(); /// /// This method implements the ProcessRecord method for get-member command. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs index 91955c0f26c..d60fccadb2f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs @@ -108,10 +108,10 @@ private void ThrowMinGreaterThanOrEqualMax(object minValue, object maxValue) #region Random generator state - private static ReaderWriterLockSlim s_runspaceGeneratorMapLock = new ReaderWriterLockSlim(); + private static readonly ReaderWriterLockSlim s_runspaceGeneratorMapLock = new ReaderWriterLockSlim(); // 1-to-1 mapping of runspaces and random number generators - private static Dictionary s_runspaceGeneratorMap = new Dictionary(); + private static readonly Dictionary s_runspaceGeneratorMap = new Dictionary(); private static void CurrentRunspace_StateChanged(object sender, RunspaceStateEventArgs e) { @@ -596,8 +596,8 @@ internal PolymorphicRandomNumberGenerator(int seed) _pseudoGenerator = new Random(seed); } - private Random _pseudoGenerator = null; - private RandomNumberGenerator _cryptographicGenerator = null; + private readonly Random _pseudoGenerator = null; + private readonly RandomNumberGenerator _cryptographicGenerator = null; /// /// Generates a random floating-point number that is greater than or equal to 0.0, and less than 1.0. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs index 61b71fe8f45..7fbf1d24e87 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs @@ -793,7 +793,7 @@ private ErrorRecord GetErrorNoResultsFromRemoteEnd(string commandName) return errorRecord; } - private List _commandsSkippedBecauseOfShadowing = new List(); + private readonly List _commandsSkippedBecauseOfShadowing = new List(); private void ReportSkippedCommands() { if (_commandsSkippedBecauseOfShadowing.Count != 0) @@ -1904,9 +1904,9 @@ internal class ImplicitRemotingCodeGenerator #region Constructor and shared private data - private PSSession _remoteRunspaceInfo; + private readonly PSSession _remoteRunspaceInfo; private Guid _moduleGuid; - private InvocationInfo _invocationInfo; + private readonly InvocationInfo _invocationInfo; internal ImplicitRemotingCodeGenerator( PSSession remoteRunspaceInfo, diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MarkdownOptionCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MarkdownOptionCommands.cs index d6cecf471bc..47e1175b8b0 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MarkdownOptionCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MarkdownOptionCommands.cs @@ -271,7 +271,7 @@ protected override void EndProcessing() /// internal static class PSMarkdownOptionInfoCache { - private static ConcurrentDictionary markdownOptionInfoCache; + private static readonly ConcurrentDictionary markdownOptionInfoCache; private const string MarkdownOptionInfoVariableName = "PSMarkdownOptionInfo"; static PSMarkdownOptionInfoCache() diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs index 2ef311e38f3..6e3df0d6326 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs @@ -960,7 +960,7 @@ private TextMeasureInfo CreateTextMeasureInfo(Statistics stat) /// The observed statistics keyed by property name. /// If Property is not set, then the key used will be the value of thisObject. /// - private MeasureObjectDictionary _statistics = new MeasureObjectDictionary(); + private readonly MeasureObjectDictionary _statistics = new MeasureObjectDictionary(); /// /// Whether or not a numeric conversion error occurred. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs index fd69a2011fb..dce7a31cee0 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs @@ -67,7 +67,7 @@ internal CultureInfo Culture internal static readonly ObjectCommandPropertyValue NonExistingProperty = new ObjectCommandPropertyValue(); internal static readonly ObjectCommandPropertyValue ExistingNullProperty = new ObjectCommandPropertyValue(null); - private bool _caseSensitive; + private readonly bool _caseSensitive; internal CultureInfo cultureInfo = null; /// @@ -225,11 +225,11 @@ public int Compare(object first, object second) return _cultureInfo.CompareInfo.Compare(firstString, secondString, _caseSensitive ? CompareOptions.None : CompareOptions.IgnoreCase) * (_ascendingOrder ? 1 : -1); } - private CultureInfo _cultureInfo = null; + private readonly CultureInfo _cultureInfo = null; - private bool _ascendingOrder = true; + private readonly bool _ascendingOrder = true; - private bool _caseSensitive = false; + private readonly bool _caseSensitive = false; } #endregion } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs index c2ebc9261a1..7fa58dadfdb 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs @@ -529,7 +529,7 @@ internal OrderByPropertyEntry CreateOrderByPropertyEntry( #endregion Utils // list of processed parameters obtained from the Expression array - private List _mshParameterList = null; + private readonly List _mshParameterList = null; // list of unprocessed parameters obtained from the Expression array. private List _unexpandedParameterList = null; @@ -698,7 +698,7 @@ internal static OrderByPropertyComparer CreateComparer(List @@ -727,6 +727,6 @@ public int Compare(OrderByPropertyEntry lhs, OrderByPropertyEntry rhs) return result; } - private OrderByPropertyComparer _orderByPropertyComparer = null; + private readonly OrderByPropertyComparer _orderByPropertyComparer = null; } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs index e5405172bee..73c52752443 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs @@ -52,7 +52,7 @@ internal bool IsMatch(PSPropertyExpression expression) return false; } - private WildcardPattern[] _wildcardPatterns; + private readonly WildcardPattern[] _wildcardPatterns; } internal class SelectObjectExpressionParameterDefinition : CommandParameterDefinition @@ -304,8 +304,11 @@ public PSObject StreamingDequeue() } private int _streamedObjectCount; - private int _first, _last, _skip, _skipLast; - private bool _firstOrLastSpecified; + private readonly int _first; + private readonly int _last; + private int _skip; + private readonly int _skipLast; + private readonly bool _firstOrLastSpecified; } /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs index 25da2e8025f..b6243fe0447 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs @@ -159,7 +159,7 @@ public sealed class SendMailMessage : PSCmdlet #region Private variables and methods // Instantiate a new instance of MailMessage - private MailMessage _mMailMessage = new MailMessage(); + private readonly MailMessage _mMailMessage = new MailMessage(); private SmtpClient _mSmtpClient = null; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandProxy.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandProxy.cs index 4a5700bdf7a..a8a9c8f194d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandProxy.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandProxy.cs @@ -20,9 +20,9 @@ internal class ShowCommandProxy { private const string ShowCommandHelperName = "Microsoft.PowerShell.Commands.ShowCommandInternal.ShowCommandHelper"; - private ShowCommandCommand _cmdlet; + private readonly ShowCommandCommand _cmdlet; - private GraphicalHostReflectionWrapper _graphicalHostReflectionWrapper; + private readonly GraphicalHostReflectionWrapper _graphicalHostReflectionWrapper; internal ShowCommandProxy(ShowCommandCommand cmdlet) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs index 4fe5c641ff9..0f8453c503e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs @@ -64,7 +64,7 @@ public void Dispose() // object used for synchronizes pipeline thread and stop thread // access to waitHandle - private object _syncObject = new object(); + private readonly object _syncObject = new object(); // this is set to true by stopProcessing private bool _stopping = false; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TimeExpressionCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TimeExpressionCommand.cs index d7071a06605..cafc9e355ff 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TimeExpressionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TimeExpressionCommand.cs @@ -37,7 +37,7 @@ public sealed class MeasureCommandCommand : PSCmdlet #region private members - private System.Diagnostics.Stopwatch _stopWatch = new System.Diagnostics.Stopwatch(); + private readonly System.Diagnostics.Stopwatch _stopWatch = new System.Diagnostics.Stopwatch(); #endregion diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs index 817c4306b44..d83e8cf2dda 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs @@ -28,7 +28,7 @@ public class UpdateTypeDataCommand : UpdateData private const string DynamicTypeSet = "DynamicTypeSet"; private const string TypeDataSet = "TypeDataSet"; - private static object s_notSpecified = new object(); + private static readonly object s_notSpecified = new object(); private static bool HasBeenSpecified(object obj) { return !System.Object.ReferenceEquals(obj, s_notSpecified); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs index 7aeb864e2ba..77f6283f9fb 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs @@ -60,9 +60,9 @@ public int Timeout #endregion parameters - private AutoResetEvent _eventArrived = new AutoResetEvent(false); + private readonly AutoResetEvent _eventArrived = new AutoResetEvent(false); private PSEventArgs _receivedEvent = null; - private object _receivedEventLock = new object(); + private readonly object _receivedEventLock = new object(); private WildcardPattern _matchPattern; /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs index fc0921d3c63..88bcfd6241c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs @@ -261,9 +261,9 @@ internal BufferingStreamReader(Stream baseStream) _copyBuffer = new byte[4096]; } - private Stream _baseStream; - private MemoryStream _streamBuffer; - private byte[] _copyBuffer; + private readonly Stream _baseStream; + private readonly MemoryStream _streamBuffer; + private readonly byte[] _copyBuffer; public override bool CanRead { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertFromJsonCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertFromJsonCommand.cs index 955786248f7..e0c60ca8f3e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertFromJsonCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertFromJsonCommand.cs @@ -27,7 +27,7 @@ public class ConvertFromJsonCommand : Cmdlet /// /// InputObjectBuffer buffers all InputObject contents available in the pipeline. /// - private List _inputObjectBuffer = new List(); + private readonly List _inputObjectBuffer = new List(); /// /// Returned data structure is a Hashtable instead a CustomPSObject. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs index 6c191fcb6e9..7265df7f7cc 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs @@ -91,7 +91,7 @@ protected override void BeginProcessing() } } - private List _inputObjects = new List(); + private readonly List _inputObjects = new List(); /// /// Caching the input objects for the command. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs index c1df3aa0bf5..98fb5b574da 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs @@ -9,7 +9,7 @@ namespace Microsoft.PowerShell.Commands internal class WebProxy : IWebProxy { private ICredentials _credentials; - private Uri _proxyAddress; + private readonly Uri _proxyAddress; internal WebProxy(Uri address) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs index 58d63c36ca3..7d2eaefcfc1 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs @@ -24,9 +24,9 @@ internal class WebResponseContentMemoryStream : MemoryStream { #region Data - private Stream _originalStreamToProxy; + private readonly Stream _originalStreamToProxy; private bool _isInitialized = false; - private Cmdlet _ownerCmdlet; + private readonly Cmdlet _ownerCmdlet; #endregion diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs index 8736965fd61..ea25082f72e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs @@ -633,7 +633,7 @@ internal class ImportXmlHelper : IDisposable /// Reference to cmdlet which is using this helper class. /// private readonly PSCmdlet _cmdlet; - private bool _isLiteralPath; + private readonly bool _isLiteralPath; internal ImportXmlHelper(string fileName, PSCmdlet cmdlet, bool isLiteralPath) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs index fc91cec91c0..3b3e05042a6 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs @@ -90,7 +90,7 @@ public override void Write(string output) } } - private StringBuilder _cachedWrite = new StringBuilder(); + private readonly StringBuilder _cachedWrite = new StringBuilder(); /// /// Sends the given output string to the host for processing. @@ -119,6 +119,6 @@ public override void WriteLine(string output) /// /// The host interface to write the debug line to. /// - private InternalHostUserInterface _ui; + private readonly InternalHostUserInterface _ui; } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs index c7668903ed4..a3f23a2f9e4 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs @@ -540,9 +540,9 @@ private static ErrorRecord ConvertToErrorRecord(object obj) return result; } - private TraceListenerCommandBase _cmdlet; - private bool _writeError; + private readonly TraceListenerCommandBase _cmdlet; + private readonly bool _writeError; private bool _isOpen = true; - private Collection _matchingSources = new Collection(); + private readonly Collection _matchingSources = new Collection(); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceListenerCommandBase.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceListenerCommandBase.cs index 3eecdd51cba..a58af1b7f87 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceListenerCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceListenerCommandBase.cs @@ -597,7 +597,7 @@ protected void ClearStoredState() _storedTraceSourceState.Clear(); } - private Dictionary>> _storedTraceSourceState = + private readonly Dictionary>> _storedTraceSourceState = new Dictionary>>(); #endregion stored state diff --git a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs index 3b9d73c0f4f..c73d4f42f67 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs @@ -19,10 +19,10 @@ internal sealed class PropVariant : IDisposable { // This is actually a VarEnum value, but the VarEnum type requires 4 bytes instead of the expected 2. [FieldOffset(0)] - ushort _valueType; + readonly ushort _valueType; [FieldOffset(8)] - IntPtr _ptr; + readonly IntPtr _ptr; /// /// Set a string value. diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs index 9907e43c4b0..64eb9041f44 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs @@ -1408,13 +1408,13 @@ private bool CollectArgs(string[] args, ref int i) private bool _sshServerMode; private bool _showVersion; private string _configurationName; - private PSHostUserInterface _hostUI; + private readonly PSHostUserInterface _hostUI; private bool _showHelp; private bool _showExtendedHelp; private bool _showBanner = true; private bool _noInteractive; - private string _bannerText; - private string _helpText; + private readonly string _bannerText; + private readonly string _helpText; private bool _abortStartup; private bool _skipUserInit; private string _customPipeName; @@ -1429,7 +1429,7 @@ private bool CollectArgs(string[] args, ref int i) private Serialization.DataFormat _outFormat = Serialization.DataFormat.Text; private bool _outputFormatSpecified = false; private Serialization.DataFormat _inFormat = Serialization.DataFormat.Text; - private Collection _collectedArgs = new Collection(); + private readonly Collection _collectedArgs = new Collection(); private string _file; private string _executionPolicy; private string _workingDirectory; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs index 8d3eb856bd0..d414a7a0f64 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs @@ -3267,7 +3267,7 @@ internal enum CHAR_INFO_Attributes : uint } [TraceSourceAttribute("ConsoleControl", "Console control methods")] - private static PSTraceSource tracer = PSTraceSource.GetTracer("ConsoleControl", "Console control methods"); + private static readonly PSTraceSource tracer = PSTraceSource.GetTracer("ConsoleControl", "Console control methods"); #endif } } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index eaa0d3d43d9..99a68698e47 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -731,7 +731,7 @@ internal LocalRunspace LocalRunspace public class ConsoleColorProxy { - private ConsoleHostUserInterface _ui; + private readonly ConsoleHostUserInterface _ui; public ConsoleColorProxy(ConsoleHostUserInterface ui) { @@ -2840,12 +2840,12 @@ private string EvaluateDebugPrompt() return promptString; } - private ConsoleHost _parent; - private bool _isNested; + private readonly ConsoleHost _parent; + private readonly bool _isNested; private bool _shouldExit; - private Executor _exec; - private Executor _promptExec; - private object _syncObject = new object(); + private readonly Executor _exec; + private readonly Executor _promptExec; + private readonly object _syncObject = new object(); private bool _isRunspacePushed = false; private bool _runspacePopped = false; @@ -2854,7 +2854,7 @@ private string EvaluateDebugPrompt() // threadsafety guaranteed by enclosing class - private static Stack s_instanceStack = new Stack(); + private static readonly Stack s_instanceStack = new Stack(); } [Serializable] @@ -2909,7 +2909,7 @@ private class ConsoleHostStartupException : Exception // Set to Unknown so that we avoid saving/restoring the console mode if we don't have a console. private ConsoleControl.ConsoleModes _savedConsoleMode = ConsoleControl.ConsoleModes.Unknown; - private ConsoleControl.ConsoleModes _initialConsoleMode = ConsoleControl.ConsoleModes.Unknown; + private readonly ConsoleControl.ConsoleModes _initialConsoleMode = ConsoleControl.ConsoleModes.Unknown; #endif private Thread _breakHandlerThread; private bool _isDisposed; @@ -2918,7 +2918,7 @@ private class ConsoleHostStartupException : Exception internal Lazy ConsoleIn { get; } = new Lazy(() => Console.In); private string _savedWindowTitle = string.Empty; - private Version _ver = PSVersionInfo.PSVersion; + private readonly Version _ver = PSVersionInfo.PSVersion; private int _exitCodeFromRunspace; private bool _noExit = true; private bool _setShouldExitCalled; @@ -2938,7 +2938,7 @@ private class ConsoleHostStartupException : Exception private bool _shouldEndSession; private int _beginApplicationNotifyCount; - private ConsoleTextWriter _consoleWriter; + private readonly ConsoleTextWriter _consoleWriter; private WrappedSerializer _outputSerializer; private WrappedSerializer _errorSerializer; private bool _displayDebuggerBanner; @@ -2954,11 +2954,10 @@ private class ConsoleHostStartupException : Exception internal static InitialSessionState DefaultInitialSessionState; [TraceSource("ConsoleHost", "ConsoleHost subclass of S.M.A.PSHost")] - private static - PSTraceSource s_tracer = PSTraceSource.GetTracer("ConsoleHost", "ConsoleHost subclass of S.M.A.PSHost"); + private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("ConsoleHost", "ConsoleHost subclass of S.M.A.PSHost"); [TraceSource("ConsoleHostRunspaceInit", "Initialization code for ConsoleHost's Runspace")] - private static PSTraceSource s_runspaceInitTracer = + private static readonly PSTraceSource s_runspaceInitTracer = PSTraceSource.GetTracer("ConsoleHostRunspaceInit", "Initialization code for ConsoleHost's Runspace", false); } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs index c1487dead65..4b3aa90d153 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs @@ -1317,17 +1317,16 @@ private static #endregion helpers - private ConsoleColor defaultForeground = ConsoleColor.Gray; + private readonly ConsoleColor defaultForeground = ConsoleColor.Gray; - private ConsoleColor defaultBackground = ConsoleColor.Black; + private readonly ConsoleColor defaultBackground = ConsoleColor.Black; - private ConsoleHostUserInterface parent = null; + private readonly ConsoleHostUserInterface parent = null; private ConsoleControl.KEY_EVENT_RECORD cachedKeyEvent; [TraceSourceAttribute("ConsoleHostRawUserInterface", "Console host's subclass of S.M.A.Host.RawConsole")] - private static - PSTraceSource tracer = PSTraceSource.GetTracer("ConsoleHostRawUserInterface", "Console host's subclass of S.M.A.Host.RawConsole"); + private static readonly PSTraceSource tracer = PSTraceSource.GetTracer("ConsoleHostRawUserInterface", "Console host's subclass of S.M.A.Host.RawConsole"); } } // namespace diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostTranscript.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostTranscript.cs index fd1b91574b4..0931abbf1cd 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostTranscript.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostTranscript.cs @@ -61,7 +61,7 @@ internal void StartTranscribing(string transcriptFilename, bool shouldAppend) } } */ - private string _transcriptFileName = string.Empty; + private readonly string _transcriptFileName = string.Empty; internal string StopTranscribing() { @@ -127,7 +127,7 @@ internal void WriteToTranscript(ReadOnlySpan text, bool newLine) } private StreamWriter _transcriptionWriter; - private object _transcriptionStateLock = new object(); + private readonly object _transcriptionStateLock = new object(); } } // namespace diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs index 402a3a19a25..593f78aaf33 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs @@ -37,7 +37,7 @@ internal partial class ConsoleHostUserInterface : System.Management.Automation.H /// /// This is a test hook for programmatically reading and writing ConsoleHost I/O. /// - private static PSHostUserInterface s_h = null; + private static readonly PSHostUserInterface s_h = null; /// /// Return true if the console supports a VT100 like virtual terminal. @@ -2174,7 +2174,7 @@ private bool TryInvokeUserDefinedReadLine(out string input) // used to serialize access to instance data - private object _instanceLock = new object(); + private readonly object _instanceLock = new object(); // If this is true, class throws on read or prompt method which require // access to console. @@ -2198,16 +2198,15 @@ internal void HandleThrowOnReadAndPrompt() // this is a test hook for the ConsoleInteractiveTestTool, which sets this field to true. - private bool _isInteractiveTestToolListening; + private readonly bool _isInteractiveTestToolListening; // This instance data is "read-only" and need not have access serialized. - private ConsoleHostRawUserInterface _rawui; - private ConsoleHost _parent; + private readonly ConsoleHostRawUserInterface _rawui; + private readonly ConsoleHost _parent; [TraceSourceAttribute("ConsoleHostUserInterface", "Console host's subclass of S.M.A.Host.Console")] - private static - PSTraceSource s_tracer = PSTraceSource.GetTracer("ConsoleHostUserInterface", "Console host's subclass of S.M.A.Host.Console"); + private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("ConsoleHostUserInterface", "Console host's subclass of S.M.A.Host.Console"); } } // namespace diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleTextWriter.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleTextWriter.cs index c875bc0c506..2acb7ab3061 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleTextWriter.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleTextWriter.cs @@ -93,6 +93,6 @@ public override _ui.WriteToConsole(a, transcribeResult: true); } - private ConsoleHostUserInterface _ui; + private readonly ConsoleHostUserInterface _ui; } } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs index bdba911e298..e496c3d36d3 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs @@ -150,7 +150,7 @@ private void PipelineStateChangedHandler(object sender, PipelineStateEventArgs e } } - private System.Threading.ManualResetEvent _eventHandle = new System.Threading.ManualResetEvent(false); + private readonly System.Threading.ManualResetEvent _eventHandle = new System.Threading.ManualResetEvent(false); } internal void ExecuteCommandAsync(string command, out Exception exceptionThrown, ExecutionOptions options) @@ -731,14 +731,14 @@ internal static void CancelCurrentExecutor() // to currentExecutor is guarded by staticStateLock, and static initializers are run by the CLR at program init time. private static Executor s_currentExecutor; - private static object s_staticStateLock = new object(); + private static readonly object s_staticStateLock = new object(); - private ConsoleHost _parent; + private readonly ConsoleHost _parent; private Pipeline _pipeline; private bool _cancelled; internal bool useNestedPipelines; - private object _instanceStateLock = new object(); - private bool _isPromptFunctionExecutor; + private readonly object _instanceStateLock = new object(); + private readonly bool _isPromptFunctionExecutor; } } // namespace diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs index 0d4638cdb6f..b049aede0f0 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs @@ -404,8 +404,8 @@ internal override int IndexWhereFound = -1; - private int _idToFind = -1; - private Int64 _sourceIdToFind; + private readonly int _idToFind = -1; + private readonly Int64 _sourceIdToFind; } /// @@ -686,9 +686,9 @@ internal override return true; } - private PSHostRawUserInterface _rawUi; - private int _maxHeight; - private int _maxWidth; + private readonly PSHostRawUserInterface _rawUi; + private readonly int _maxHeight; + private readonly int _maxWidth; internal int Tally; } @@ -1017,7 +1017,7 @@ internal static #endregion - private ArrayList _topLevelNodes = new ArrayList(); + private readonly ArrayList _topLevelNodes = new ArrayList(); private int _nodeCount; private const int maxNodeCount = 128; } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs index c2a13132e41..8c6aa2e4dcb 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs @@ -240,8 +240,8 @@ class ProgressPane private Size _bufSize; private BufferCell[,] _savedRegion; private BufferCell[,] _progressRegion; - private PSHostRawUserInterface _rawui; - private ConsoleHostUserInterface _ui; + private readonly PSHostRawUserInterface _rawui; + private readonly ConsoleHostUserInterface _ui; } } // namespace diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs index 696e47313d5..7f4f271a7be 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs @@ -141,7 +141,7 @@ class WrappedSerializer : Serialization } internal TextWriter textWriter; - private XmlWriter _xmlWriter; + private readonly XmlWriter _xmlWriter; private Serializer _xmlSerializer; private bool _firstCall = true; } @@ -271,8 +271,8 @@ class WrappedDeserializer : Serialization } internal TextReader textReader; - private XmlReader _xmlReader; - private Deserializer _xmlDeserializer; + private readonly XmlReader _xmlReader; + private readonly Deserializer _xmlDeserializer; private string _firstLine; private bool _atEnd; } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventDescriptor.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventDescriptor.cs index e01249c9bc5..f95ee6002d3 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventDescriptor.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventDescriptor.cs @@ -11,19 +11,19 @@ namespace System.Diagnostics.Eventing public struct EventDescriptor { [FieldOffset(0)] - private ushort _id; + private readonly ushort _id; [FieldOffset(2)] - private byte _version; + private readonly byte _version; [FieldOffset(3)] - private byte _channel; + private readonly byte _channel; [FieldOffset(4)] - private byte _level; + private readonly byte _level; [FieldOffset(5)] - private byte _opcode; + private readonly byte _opcode; [FieldOffset(6)] - private ushort _task; + private readonly ushort _task; [FieldOffset(8)] - private long _keywords; + private readonly long _keywords; [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "opcode", Justification = "matell: Shipped public in 3.5, breaking change to fix now.")] public EventDescriptor( diff --git a/src/Microsoft.PowerShell.MarkdownRender/VT100EscapeSequences.cs b/src/Microsoft.PowerShell.MarkdownRender/VT100EscapeSequences.cs index 83e99298979..aed66caeb84 100644 --- a/src/Microsoft.PowerShell.MarkdownRender/VT100EscapeSequences.cs +++ b/src/Microsoft.PowerShell.MarkdownRender/VT100EscapeSequences.cs @@ -273,11 +273,11 @@ private void SetCodeColor(bool isDarkTheme) public class VT100EscapeSequences { private const char Esc = (char)0x1B; - private string endSequence = Esc + "[0m"; + private readonly string endSequence = Esc + "[0m"; // For code blocks, [500@ make sure that the whole line has background color. private const string LongBackgroundCodeBlock = "[500@"; - private PSMarkdownOptionInfo options; + private readonly PSMarkdownOptionInfo options; /// /// Initializes a new instance of the class. diff --git a/src/Microsoft.PowerShell.Security/security/CatalogCommands.cs b/src/Microsoft.PowerShell.Security/security/CatalogCommands.cs index 5d094413904..895a551e057 100644 --- a/src/Microsoft.PowerShell.Security/security/CatalogCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/CatalogCommands.cs @@ -60,7 +60,7 @@ public string[] Path // // name of this command // - private string commandName; + private readonly string commandName; /// /// Initializes a new instance of the CatalogCommandsBase class, diff --git a/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs b/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs index 28163845d22..7dc5235edd9 100644 --- a/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs @@ -80,7 +80,7 @@ public string[] LiteralPath // // list of files that were not found // - private List _filesNotFound = new List(); + private readonly List _filesNotFound = new List(); /// /// Initializes a new instance of the GetPfxCertificateCommand diff --git a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs index 7bdb8286598..7902dd6a5d1 100644 --- a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs +++ b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs @@ -65,12 +65,12 @@ public struct DnsNameRepresentation /// /// Punycode version of DNS name. /// - private string _punycodeName; + private readonly string _punycodeName; /// /// Unicode version of DNS name. /// - private string _unicodeName; + private readonly string _unicodeName; /// /// Ambiguous constructor of a DnsNameRepresentation. @@ -451,8 +451,8 @@ public bool Valid } private bool _archivedCerts = false; - private X509StoreLocation _storeLocation = null; - private string _storeName = null; + private readonly X509StoreLocation _storeLocation = null; + private readonly string _storeName = null; private CertificateStoreHandle _storeHandle = null; private bool _valid = false; private bool _open = false; @@ -521,7 +521,7 @@ public sealed class CertificateProvider : NavigationCmdletProvider, ICmdletProvi /// -- storeLocations /// -- pathCache. /// - private static object s_staticLock = new object(); + private static readonly object s_staticLock = new object(); /// /// List of store locations. They do not change once initialized. @@ -2893,12 +2893,12 @@ public struct EnhancedKeyUsageRepresentation /// /// Localized friendly name of EKU. /// - private string _friendlyName; + private readonly string _friendlyName; /// /// OID of EKU. /// - private string _oid; + private readonly string _oid; /// /// Constructor of an EnhancedKeyUsageRepresentation. @@ -3131,7 +3131,7 @@ private static string[] GetPathElements(string path) public sealed class EnhancedKeyUsageProperty { - private List _ekuList = new List(); + private readonly List _ekuList = new List(); /// /// Get property of EKUList. @@ -3175,8 +3175,8 @@ public EnhancedKeyUsageProperty(X509Certificate2 cert) public sealed class DnsNameProperty { - private List _dnsList = new List(); - private System.Globalization.IdnMapping idnMapping = new System.Globalization.IdnMapping(); + private readonly List _dnsList = new List(); + private readonly System.Globalization.IdnMapping idnMapping = new System.Globalization.IdnMapping(); private const string dnsNamePrefix = "DNS Name="; private const string distinguishedNamePrefix = "CN="; @@ -3381,7 +3381,7 @@ internal static class Crypt32Helpers /// Lock that guards access to the following static members /// -- storeNames. /// - private static object s_staticLock = new object(); + private static readonly object s_staticLock = new object(); internal static List storeNames = new List(); diff --git a/src/Microsoft.PowerShell.Security/security/CmsCommands.cs b/src/Microsoft.PowerShell.Security/security/CmsCommands.cs index 4c90c02e941..c879ac74a05 100644 --- a/src/Microsoft.PowerShell.Security/security/CmsCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/CmsCommands.cs @@ -43,7 +43,7 @@ public PSObject Content set; } - private PSDataCollection _inputObjects = new PSDataCollection(); + private readonly PSDataCollection _inputObjects = new PSDataCollection(); /// /// Gets or sets the content of the CMS Message by path. @@ -206,7 +206,7 @@ public string Content set; } - private StringBuilder _contentBuffer = new StringBuilder(); + private readonly StringBuilder _contentBuffer = new StringBuilder(); /// /// Gets or sets the CMS Message by path. @@ -351,7 +351,7 @@ public string Content set; } - private StringBuilder _contentBuffer = new StringBuilder(); + private readonly StringBuilder _contentBuffer = new StringBuilder(); /// /// Gets or sets the Windows Event Log Message with contents to be decrypted. diff --git a/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs b/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs index 74dee890cdf..5f7c819fc5e 100644 --- a/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs @@ -35,7 +35,7 @@ protected SecureString SecureStringData // // name of this command // - private string _commandName; + private readonly string _commandName; /// /// Initializes a new instance of the SecureStringCommandBase diff --git a/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs b/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs index ae9004f8dcf..fa4c3dd2c13 100644 --- a/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs @@ -124,7 +124,7 @@ public byte[] Content // // name of this command // - private string _commandName; + private readonly string _commandName; /// /// Initializes a new instance of the SignatureCommandsBase class, diff --git a/src/Microsoft.WSMan.Management/ConfigProvider.cs b/src/Microsoft.WSMan.Management/ConfigProvider.cs index 414b70c8403..88a295ac4e0 100644 --- a/src/Microsoft.WSMan.Management/ConfigProvider.cs +++ b/src/Microsoft.WSMan.Management/ConfigProvider.cs @@ -43,12 +43,12 @@ public sealed partial class WSManConfigProvider : NavigationCmdletProvider, ICmd /// /// Object contains the cache of the enumerate results for the cmdlet to execute. /// - Dictionary enumerateMapping = new Dictionary(); + readonly Dictionary enumerateMapping = new Dictionary(); /// /// Mapping of ResourceURI with the XML returned by the Get call. /// - Dictionary getMapping = new Dictionary(); + readonly Dictionary getMapping = new Dictionary(); #region ICmdletProviderSupportsHelp Members diff --git a/src/Microsoft.WSMan.Management/CurrentConfigurations.cs b/src/Microsoft.WSMan.Management/CurrentConfigurations.cs index 42709bc8337..fb0ebd10911 100644 --- a/src/Microsoft.WSMan.Management/CurrentConfigurations.cs +++ b/src/Microsoft.WSMan.Management/CurrentConfigurations.cs @@ -21,7 +21,7 @@ internal class CurrentConfigurations /// /// This holds the current configurations XML. /// - private XmlDocument rootDocument; + private readonly XmlDocument rootDocument; /// /// Holds the reference to the current document element. @@ -36,7 +36,7 @@ internal class CurrentConfigurations /// /// Session of the WsMan sserver. /// - private IWSManSession serverSession; + private readonly IWSManSession serverSession; /// /// Gets the server session associated with the configuration. diff --git a/src/Microsoft.WSMan.Management/InvokeWSManAction.cs b/src/Microsoft.WSMan.Management/InvokeWSManAction.cs index f237a0f740b..f82b9f5942d 100644 --- a/src/Microsoft.WSMan.Management/InvokeWSManAction.cs +++ b/src/Microsoft.WSMan.Management/InvokeWSManAction.cs @@ -245,7 +245,7 @@ public Uri ResourceURI private Uri resourceuri; private WSManHelper helper; - IWSManEx m_wsmanObject = (IWSManEx)new WSManClass(); + readonly IWSManEx m_wsmanObject = (IWSManEx)new WSManClass(); IWSManSession m_session = null; string connectionStr = string.Empty; diff --git a/src/Microsoft.WSMan.Management/WSManInstance.cs b/src/Microsoft.WSMan.Management/WSManInstance.cs index fabac20ec78..2bb7cd97326 100644 --- a/src/Microsoft.WSMan.Management/WSManInstance.cs +++ b/src/Microsoft.WSMan.Management/WSManInstance.cs @@ -1474,7 +1474,7 @@ public Hashtable ValueSet private Hashtable valueset; private WSManHelper helper; - IWSManEx m_wsmanObject = (IWSManEx)new WSManClass(); + readonly IWSManEx m_wsmanObject = (IWSManEx)new WSManClass(); IWSManSession m_session = null; string connectionStr = string.Empty; diff --git a/src/Microsoft.WSMan.Management/WsManHelper.cs b/src/Microsoft.WSMan.Management/WsManHelper.cs index 32e1f88e57b..4adcf802848 100644 --- a/src/Microsoft.WSMan.Management/WsManHelper.cs +++ b/src/Microsoft.WSMan.Management/WsManHelper.cs @@ -78,13 +78,13 @@ internal class WSManHelper // string for operation internal string WSManOp = null; - private PSCmdlet cmdletname; - private NavigationCmdletProvider _provider; + private readonly PSCmdlet cmdletname; + private readonly NavigationCmdletProvider _provider; private FileStream _fs; private StreamReader _sr; - private static ResourceManager _resourceMgr = new ResourceManager("Microsoft.WSMan.Management.resources.WsManResources", typeof(WSManHelper).GetTypeInfo().Assembly); + private static readonly ResourceManager _resourceMgr = new ResourceManager("Microsoft.WSMan.Management.resources.WsManResources", typeof(WSManHelper).GetTypeInfo().Assembly); // // @@ -1139,6 +1139,6 @@ internal static string GetResourceString(string Key) /// /// - private static Dictionary ResourceValueCache = new Dictionary(); + private static readonly Dictionary ResourceValueCache = new Dictionary(); } } diff --git a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs index 96ba4cd28fb..25600786669 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs @@ -563,8 +563,8 @@ internal static int NonWindowsGetProcessParentPid(int pid) /// Unix specific implementations of required functionality. internal static class Unix { - private static Dictionary usernameCache = new Dictionary(); - private static Dictionary groupnameCache = new Dictionary(); + private static readonly Dictionary usernameCache = new Dictionary(); + private static readonly Dictionary groupnameCache = new Dictionary(); /// The type of a Unix file system item. public enum ItemType @@ -696,7 +696,7 @@ public class CommonStat private const char CanExecute = 'x'; // helper for getting unix mode - private Dictionary modeMap = new Dictionary() + private readonly Dictionary modeMap = new Dictionary() { { StatMask.OwnerRead, CanRead }, { StatMask.OwnerWrite, CanWrite }, @@ -709,7 +709,7 @@ public class CommonStat { StatMask.OtherExecute, CanExecute }, }; - private StatMask[] permissions = new StatMask[] + private readonly StatMask[] permissions = new StatMask[] { StatMask.OwnerRead, StatMask.OwnerWrite, @@ -723,7 +723,7 @@ public class CommonStat }; // The item type and the character representation for the first element in the stat string - private Dictionary itemTypeTable = new Dictionary() + private readonly Dictionary itemTypeTable = new Dictionary() { { ItemType.BlockDevice, 'b' }, { ItemType.CharacterDevice, 'c' }, diff --git a/src/System.Management.Automation/DscSupport/CimDSCParser.cs b/src/System.Management.Automation/DscSupport/CimDSCParser.cs index db7f2c8eba1..99a0173cdcc 100644 --- a/src/System.Management.Automation/DscSupport/CimDSCParser.cs +++ b/src/System.Management.Automation/DscSupport/CimDSCParser.cs @@ -320,8 +320,8 @@ public override object Transform(EngineIntrinsics engineIntrinsics, object input /// internal class CimDSCParser { - private CimMofDeserializer _deserializer; - private CimMofDeserializer.OnClassNeeded _onClassNeeded; + private readonly CimMofDeserializer _deserializer; + private readonly CimMofDeserializer.OnClassNeeded _onClassNeeded; /// /// internal CimDSCParser(CimMofDeserializer.OnClassNeeded onClassNeeded) @@ -531,7 +531,7 @@ public static class DscClassCache private const string reservedProperties = "^(Require|Trigger|Notify|Before|After|Subscribe)$"; - private static PSTraceSource s_tracer = PSTraceSource.GetTracer("DSC", "DSC Class Cache"); + private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("DSC", "DSC Class Cache"); // Constants for items in the module qualified name (Module\Version\ClassName) private const int IndexModuleName = 0; diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseCommand.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseCommand.cs index 6574914c396..6494c53434e 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseCommand.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseCommand.cs @@ -27,7 +27,7 @@ internal void ThrowTerminatingError(ErrorRecord errorRecord) _command.ThrowTerminatingError(errorRecord); } - private PSCmdlet _command; + private readonly PSCmdlet _command; } /// @@ -133,7 +133,7 @@ public void Dispose() private string _commandName = null; private Type _commandType; - private List _commandParameterList = new List(); + private readonly List _commandParameterList = new List(); private ExecutionContext _context = null; } diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommand.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommand.cs index bb6e6cb50aa..de051865959 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommand.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommand.cs @@ -497,7 +497,7 @@ private void PopGroup() /// /// The formatting shape this formatter emits. /// - private FormatShape _shape; + private readonly FormatShape _shape; #region expression factory @@ -517,7 +517,7 @@ internal ScriptBlock CreateScriptBlock(string scriptText) private TypeInfoDataBase _typeInfoDataBase = null; private FormattingCommandLineParameters _parameters = null; - private FormatViewManager _viewManager = new FormatViewManager(); + private readonly FormatViewManager _viewManager = new FormatViewManager(); private int _enumerationLimit = InitialSessionState.DefaultFormatEnumerationLimit; } diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommandParameters.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommandParameters.cs index 26e62bc8a79..bee90355652 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommandParameters.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommandParameters.cs @@ -249,7 +249,7 @@ private void ProcessGlobbingCharactersError(bool originalParameterWasHashTable, #endregion - private bool _noGlobbing; + private readonly bool _noGlobbing; } internal class AlignmentEntryDefinition : HashtableEntryDefinition diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs index 5025fc6c381..b8d26fb512f 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs @@ -639,7 +639,7 @@ private FormatOutputContext FormatContext /// /// Context manager instance to guide the message traversal. /// - private FormatMessagesContextManager _ctxManager = new FormatMessagesContextManager(); + private readonly FormatMessagesContextManager _ctxManager = new FormatMessagesContextManager(); private FormattedObjectsCache _cache = null; @@ -942,7 +942,7 @@ internal TableOutputContextBase(OutCommandInner cmd, /// /// Helper class to properly write a table using text output. /// - private TableWriter _tableWriter = new TableWriter(); + private readonly TableWriter _tableWriter = new TableWriter(); } private sealed class TableOutputContext : TableOutputContextBase @@ -951,7 +951,7 @@ private sealed class TableOutputContext : TableOutputContextBase private int _consoleHeight = -1; private int _consoleWidth = -1; private const int WhitespaceAndPagerLineCount = 2; - private bool _repeatHeader = false; + private readonly bool _repeatHeader = false; /// /// Construct a context to push on the stack. @@ -1174,7 +1174,7 @@ internal override void ProcessPayload(FormatEntryData fed) /// /// Writer to do the actual formatting. /// - private ListWriter _listWriter = new ListWriter(); + private readonly ListWriter _listWriter = new ListWriter(); } private sealed class WideOutputContext : TableOutputContextBase @@ -1357,7 +1357,7 @@ internal void Reset() _arr[k] = null; } - private string[] _arr; + private readonly string[] _arr; private int _lastEmptySpot; } } @@ -1395,7 +1395,7 @@ internal override void ProcessPayload(FormatEntryData fed) _writer.WriteObject(cve.formatValueList); } - private ComplexWriter _writer = new ComplexWriter(); + private readonly ComplexWriter _writer = new ComplexWriter(); } } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/ColumnWidthManager.cs b/src/System.Management.Automation/FormatAndOutput/common/ColumnWidthManager.cs index d2e44c4ad60..68ccc7ebc59 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/ColumnWidthManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/ColumnWidthManager.cs @@ -201,8 +201,8 @@ private static int GetLastVisibleColumn(Span columnWidths) return columnWidths.Length - 1; } - private int _tableWidth; - private int _minimumColumnWidth; - private int _separatorWidth; + private readonly int _tableWidth; + private readonly int _minimumColumnWidth; + private readonly int _separatorWidth; } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs b/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs index 74031dc515c..eaec4f7b31c 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs @@ -206,7 +206,7 @@ private void WriteToScreen() /// /// Helper object to manage the frame-based indentation and margins. /// - private IndentationManager _indentationManager = new IndentationManager(); + private readonly IndentationManager _indentationManager = new IndentationManager(); /// /// Buffer to accumulate partially constructed text. @@ -243,7 +243,7 @@ public void Dispose() } } - private IndentationManager _mgr; + private readonly IndentationManager _mgr; } internal void Clear() @@ -311,7 +311,7 @@ private int ComputeLeftIndentation() return val; } - private Stack _frameInfoStack = new Stack(); + private readonly Stack _frameInfoStack = new Stack(); } /// @@ -331,7 +331,7 @@ internal sealed class StringManipulationHelper private static readonly char s_softHyphen = '\u00AD'; private static readonly char s_hardHyphen = '\u2011'; private static readonly char s_nonBreakingSpace = '\u00A0'; - private static Collection s_cultureCollection = new Collection(); + private static readonly Collection s_cultureCollection = new Collection(); static StringManipulationHelper() { @@ -510,10 +510,10 @@ internal int ActiveLen } } - private StringCollection _retVal; + private readonly StringCollection _retVal; private bool _addedFirstLine; - private int _firstLineLen; - private int _followingLinesLen; + private readonly int _firstLineLen; + private readonly int _followingLinesLen; } private static StringCollection GenerateLinesWithWordWrap(DisplayCells displayCells, string val, int firstLineLen, int followingLinesLen) diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/FormatTable.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/FormatTable.cs index da440d8f628..537169e779c 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/FormatTable.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/FormatTable.cs @@ -25,7 +25,7 @@ namespace System.Management.Automation.Runspaces [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "FormatTable")] public class FormatTableLoadException : RuntimeException { - private Collection _errors; + private readonly Collection _errors; #region Constructors @@ -161,7 +161,7 @@ public sealed class FormatTable { #region Private Data - private TypeInfoDataBaseManager _formatDBMgr; + private readonly TypeInfoDataBaseManager _formatDBMgr; #endregion diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs index 02d60731e43..773eb9d3777 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs @@ -81,7 +81,7 @@ internal class XmlLoaderLogger : IDisposable #region tracer // PSS/end-user tracer [TraceSource("FormatFileLoading", "Loading format files")] - private static PSTraceSource s_formatFileLoadingtracer = PSTraceSource.GetTracer("FormatFileLoading", "Loading format files", false); + private static readonly PSTraceSource s_formatFileLoadingtracer = PSTraceSource.GetTracer("FormatFileLoading", "Loading format files", false); #endregion tracer /// @@ -149,12 +149,12 @@ internal bool HasErrors /// /// If true, log entries to memory. /// - private bool _saveInMemory = true; + private readonly bool _saveInMemory = true; /// /// List of entries logged if saveInMemory is true. /// - private List _entries = new List(); + private readonly List _entries = new List(); /// /// True if we ever logged an error. @@ -170,7 +170,7 @@ internal abstract class XmlLoaderBase : IDisposable { #region tracer [TraceSource("XmlLoaderBase", "XmlLoaderBase")] - private static PSTraceSource s_tracer = PSTraceSource.GetTracer("XmlLoaderBase", "XmlLoaderBase"); + private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("XmlLoaderBase", "XmlLoaderBase"); #endregion tracer /// @@ -690,7 +690,7 @@ protected void SetLoadingInfoIsProductCode(bool isProductCode) _loadingInfo.isProductCode = isProductCode; } - private DatabaseLoadingInfo _loadingInfo = new DatabaseLoadingInfo(); + private readonly DatabaseLoadingInfo _loadingInfo = new DatabaseLoadingInfo(); protected DatabaseLoadingInfo LoadingInfo { @@ -711,13 +711,13 @@ protected DatabaseLoadingInfo LoadingInfo internal bool VerifyStringResources { get; } = true; - private int _maxNumberOfErrors = 30; + private readonly int _maxNumberOfErrors = 30; private int _currentErrorCount = 0; - private bool _logStackActivity = false; + private readonly bool _logStackActivity = false; - private Stack _executionStack = new Stack(); + private readonly Stack _executionStack = new Stack(); private XmlLoaderLogger _logger = new XmlLoaderLogger(); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs index 1892a87668b..e30fb9781a6 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs @@ -216,11 +216,11 @@ private Assembly ResolveAssemblyNameInLoadedAssemblies(string assemblyName, bool return result; } - private Hashtable _assemblyReferences = new Hashtable(StringComparer.OrdinalIgnoreCase); + private readonly Hashtable _assemblyReferences = new Hashtable(StringComparer.OrdinalIgnoreCase); } - private AssemblyNameResolver _assemblyNameResolver = new AssemblyNameResolver(); - private Hashtable _resourceReferenceToAssemblyCache = new Hashtable(); + private readonly AssemblyNameResolver _assemblyNameResolver = new AssemblyNameResolver(); + private readonly Hashtable _resourceReferenceToAssemblyCache = new Hashtable(); } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs index d03d2eb1ad3..19cb9184388 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs @@ -33,7 +33,7 @@ internal sealed class TypeInfoDataBaseManager internal object updateDatabaseLock = new object(); // this is used to throw errors when updating a shared TypeTable. internal bool isShared; - private List _formatFileList; + private readonly List _formatFileList; internal bool DisableFormatTableUpdates { get; set; } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs index 470832670a9..168c3d1498f 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs @@ -230,10 +230,10 @@ private bool MatchCondition(PSObject currentObject, PSPropertyExpression ex) return retVal; } - private PSPropertyExpressionFactory _expressionFactory; - private TypeInfoDataBase _db; - private Collection _typeNameHierarchy; - private bool _useInheritance; + private readonly PSPropertyExpressionFactory _expressionFactory; + private readonly TypeInfoDataBase _db; + private readonly Collection _typeNameHierarchy; + private readonly bool _useInheritance; private int _bestMatchIndex = BestMatchIndexUndefined; private TypeMatchItem _bestMatchItem; diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs index 82277eeebd1..f11d4759c8c 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs @@ -43,7 +43,7 @@ internal sealed partial class TypeInfoDataBaseLoader : XmlLoaderBase #region tracer [TraceSource("TypeInfoDataBaseLoader", "TypeInfoDataBaseLoader")] - private static PSTraceSource s_tracer = PSTraceSource.GetTracer("TypeInfoDataBaseLoader", "TypeInfoDataBaseLoader"); + private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("TypeInfoDataBaseLoader", "TypeInfoDataBaseLoader"); #endregion tracer /// @@ -2035,7 +2035,7 @@ internal ExpressionToken GenerateExpressionToken() return _token; } - private TypeInfoDataBaseLoader _loader; + private readonly TypeInfoDataBaseLoader _loader; private ExpressionToken _token; private bool _fatalError = false; } @@ -2175,7 +2175,7 @@ internal bool ProcessExpressionDirectives(XmlNode containerNode, List u private TextToken _textToken; private ExpressionToken _expression; - private TypeInfoDataBaseLoader _loader; + private readonly TypeInfoDataBaseLoader _loader; } #endregion @@ -2228,7 +2228,7 @@ internal ControlBase Control } private ControlBase _control; - private TypeInfoDataBaseLoader _loader; + private readonly TypeInfoDataBaseLoader _loader; } #endregion diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatMsgCtxManager.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatMsgCtxManager.cs index 0aaf16a9a28..5ccfada75fa 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatMsgCtxManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatMsgCtxManager.cs @@ -135,6 +135,6 @@ internal OutputContext ActiveOutputContext /// /// Internal stack to manage context. /// - private Stack _stack = new Stack(); + private readonly Stack _stack = new Stack(); } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs index eeacaad4520..5fe426ba15e 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs @@ -383,13 +383,13 @@ private bool EvaluateDisplayCondition(PSObject so, ExpressionToken conditionToke return retVal; } - private TypeInfoDataBase _db; - private DatabaseLoadingInfo _loadingInfo; - private PSPropertyExpressionFactory _expressionFactory; - private List _controlDefinitionList; - private FormatErrorManager _errorManager; - private TerminatingErrorContext _errorContext; - private int _enumerationLimit; + private readonly TypeInfoDataBase _db; + private readonly DatabaseLoadingInfo _loadingInfo; + private readonly PSPropertyExpressionFactory _expressionFactory; + private readonly List _controlDefinitionList; + private readonly FormatErrorManager _errorManager; + private readonly TerminatingErrorContext _errorContext; + private readonly int _enumerationLimit; } internal class TraversalInfo @@ -412,8 +412,8 @@ internal TraversalInfo NextLevel } } - private int _level; - private int _maxDepth; + private readonly int _level; + private readonly int _maxDepth; } /// @@ -771,13 +771,13 @@ private List AddIndentationLevel(List formatValueList) /// /// Indentation added to each level in the recursion. /// - private int _indentationStep = 2; + private readonly int _indentationStep = 2; - private FormatErrorManager _errorManager; + private readonly FormatErrorManager _errorManager; - private PSPropertyExpressionFactory _expressionFactory; + private readonly PSPropertyExpressionFactory _expressionFactory; - private int _enumerationLimit; + private readonly int _enumerationLimit; } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs index 40ca2e18a80..9101f22e740 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs @@ -70,7 +70,7 @@ internal sealed class FormatViewManager { #region tracer [TraceSource("FormatViewBinding", "Format view binding")] - private static PSTraceSource s_formatViewBindingTracer = PSTraceSource.GetTracer("FormatViewBinding", "Format view binding", false); + private static readonly PSTraceSource s_formatViewBindingTracer = PSTraceSource.GetTracer("FormatViewBinding", "Format view binding", false); #endregion tracer private static string PSObjectTypeName(PSObject so) @@ -677,12 +677,12 @@ private static ErrorRecord GenerateErrorRecord(FormattingError error) return errorRecord; } - private FormatErrorPolicy _formatErrorPolicy; + private readonly FormatErrorPolicy _formatErrorPolicy; /// /// Current list of failed PSPropertyExpression evaluations. /// - private List _formattingErrorList = new List(); + private readonly List _formattingErrorList = new List(); } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/ILineOutput.cs b/src/System.Management.Automation/FormatAndOutput/common/ILineOutput.cs index 03cd5a1a2a2..8f1fd9d3742 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/ILineOutput.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/ILineOutput.cs @@ -258,17 +258,17 @@ internal class WriteLineHelper /// Instance of the delegate previously defined /// for line that has EXACTLY this.ncols characters. /// - private WriteCallback _writeCall = null; + private readonly WriteCallback _writeCall = null; /// /// Instance of the delegate previously defined /// for generic line, less that this.ncols characters. /// - private WriteCallback _writeLineCall = null; + private readonly WriteCallback _writeLineCall = null; #endregion - private bool _lineWrap; + private readonly bool _lineWrap; /// /// Construct an instance, given the two callbacks @@ -367,7 +367,7 @@ private void WriteLineInternal(string val, int cols) } } - private DisplayCells _displayCells; + private readonly DisplayCells _displayCells; } /// @@ -447,11 +447,11 @@ internal TextWriterLineOutput(TextWriter writer, int columns, bool suppressNewli _suppressNewline = suppressNewline; } - private int _columns = 0; + private readonly int _columns = 0; - private TextWriter _writer = null; + private readonly TextWriter _writer = null; - private bool _suppressNewline = false; + private readonly bool _suppressNewline = false; } /// @@ -462,7 +462,7 @@ internal class StreamingTextWriter : TextWriter { #region tracer [TraceSource("StreamingTextWriter", "StreamingTextWriter")] - private static PSTraceSource s_tracer = PSTraceSource.GetTracer("StreamingTextWriter", "StreamingTextWriter"); + private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("StreamingTextWriter", "StreamingTextWriter"); #endregion tracer /// @@ -499,6 +499,6 @@ public override void WriteLine(string s) /// /// Instance of the delegate previously defined. /// - private WriteLineCallback _writeCall = null; + private readonly WriteLineCallback _writeCall = null; } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/OutputManager.cs b/src/System.Management.Automation/FormatAndOutput/common/OutputManager.cs index 861a3ab6405..105527249f6 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/OutputManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/OutputManager.cs @@ -135,7 +135,7 @@ protected override void InternalDispose() /// /// Lock object. /// - private object _syncRoot = new object(); + private readonly object _syncRoot = new object(); } /// @@ -185,7 +185,7 @@ public void Dispose() /// /// Ordered list of ETS type names this object is handling. /// - private StringCollection _applicableTypes = new StringCollection(); + private readonly StringCollection _applicableTypes = new StringCollection(); } /// @@ -322,7 +322,7 @@ private CommandEntry GetActiveCommandEntry(PSObject so) /// /// List of command entries, each with a set of applicable types. /// - private List _commandEntryList = new List(); + private readonly List _commandEntryList = new List(); /// /// Default command entry to be executed when all type matches fail. diff --git a/src/System.Management.Automation/FormatAndOutput/common/OutputQueue.cs b/src/System.Management.Automation/FormatAndOutput/common/OutputQueue.cs index 1545f456e12..11817de4ab2 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/OutputQueue.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/OutputQueue.cs @@ -164,28 +164,28 @@ internal PacketInfoData Dequeue() /// /// Queue to store the currently cached objects. /// - private Queue _queue = new Queue(); + private readonly Queue _queue = new Queue(); /// /// Number of objects to compute the best fit. /// Zero: all the objects /// a positive number N: use the first N. /// - private int _objectCount = 0; + private readonly int _objectCount = 0; /// /// Maximum amount of time for record processing to compute the best fit. /// MaxValue: all the objects. /// A positive timespan: use all objects that have been processed within the timeframe. /// - private TimeSpan _groupingDuration = TimeSpan.MinValue; + private readonly TimeSpan _groupingDuration = TimeSpan.MinValue; private Stopwatch _groupingTimer = null; /// /// Notification callback to be called when we have accumulated enough /// data to compute a hint. /// - private FormattedObjectsCache.ProcessCachedGroupNotification _notificationCallBack = null; + private readonly FormattedObjectsCache.ProcessCachedGroupNotification _notificationCallBack = null; /// /// Reference kept to be used during notification. @@ -327,7 +327,7 @@ internal List Drain() /// /// Front end queue (if present, cache ALL, if not, bypass) /// - private Queue _frontEndQueue; + private readonly Queue _frontEndQueue; /// /// Back end grouping queue. diff --git a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameter.cs b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameter.cs index 3de036f35da..4ced8de5de0 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameter.cs @@ -523,7 +523,7 @@ internal static string CatenateStringArray(string[] arr) #endregion - private CommandParameterDefinition _paramDef = null; + private readonly CommandParameterDefinition _paramDef = null; } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs b/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs index dd9f18a2502..c057265c490 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs @@ -357,7 +357,7 @@ private PSObject IfHashtableWrapAsPSCustomObject(PSObject target) } // private members - private string _stringValue; + private readonly string _stringValue; private bool _isResolved = false; #endregion Private Members diff --git a/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs b/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs index 0b2dfe2f721..4ef55625cfc 100644 --- a/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs +++ b/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs @@ -143,7 +143,7 @@ internal override int GetTailSplitLength(string str, int offset, int displayCell return GetSplitLengthInternalHelper(str, offset, displayCells, false); } - private PSHostRawUserInterface _rawUserInterface; + private readonly PSHostRawUserInterface _rawUserInterface; } /// @@ -555,12 +555,12 @@ internal PromptResponse PromptUser(PSHostUserInterface console) /// /// Prompt string as passed at initialization. /// - private string _promptString; + private readonly string _promptString; /// /// The cmdlet that uses this prompt helper. /// - private ConsoleLineOutput _callingCmdlet = null; + private readonly ConsoleLineOutput _callingCmdlet = null; } /// @@ -568,25 +568,25 @@ internal PromptResponse PromptUser(PSHostUserInterface console) /// usable width to N-1 (e.g. 80-1) and forcing a call /// to WriteLine() /// - private bool _forceNewLine = true; + private readonly bool _forceNewLine = true; /// /// Use this if IRawConsole is null; /// - private int _fallbackRawConsoleColumnNumber = 80; + private readonly int _fallbackRawConsoleColumnNumber = 80; /// /// Use this if IRawConsole is null; /// - private int _fallbackRawConsoleRowNumber = 40; + private readonly int _fallbackRawConsoleRowNumber = 40; - private WriteLineHelper _writeLineHelper; + private readonly WriteLineHelper _writeLineHelper; /// /// Handler to prompt the user for page breaks /// if this handler is not null, we have prompting. /// - private PromptHandler _prompt = null; + private readonly PromptHandler _prompt = null; /// /// Conter for the # of lines written when prompting is on. @@ -601,17 +601,17 @@ internal PromptResponse PromptUser(PSHostUserInterface console) /// /// Refecence to the PSHostUserInterface interface we use. /// - private PSHostUserInterface _console = null; + private readonly PSHostUserInterface _console = null; /// /// Msh host specific string manipulation helper. /// - private DisplayCells _displayCellsPSHost; + private readonly DisplayCells _displayCellsPSHost; /// /// Reference to error context to throw Msh exceptions. /// - private TerminatingErrorContext _errorContext = null; + private readonly TerminatingErrorContext _errorContext = null; #endregion } diff --git a/src/System.Management.Automation/cimSupport/cmdletization/EnumWriter.cs b/src/System.Management.Automation/cimSupport/cmdletization/EnumWriter.cs index 23c7a09c4f2..7adca75b17d 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/EnumWriter.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/EnumWriter.cs @@ -23,8 +23,8 @@ private static ModuleBuilder CreateModuleBuilder() return mb; } - private static Lazy s_moduleBuilder = new Lazy(CreateModuleBuilder, isThreadSafe: true); - private static object s_moduleBuilderUsageLock = new object(); + private static readonly Lazy s_moduleBuilder = new Lazy(CreateModuleBuilder, isThreadSafe: true); + private static readonly object s_moduleBuilderUsageLock = new object(); internal static string GetEnumFullName(EnumMetadataEnum enumMetadata) { diff --git a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs index f14eae396f8..41f84178b72 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs @@ -386,7 +386,7 @@ private List GetMethodParameterSets(StaticCmdletMetadata staticCmdlet) return new List(parameterSetNames.Keys); } - private Dictionary _staticMethodMetadataToUniqueId = new Dictionary(); + private readonly Dictionary _staticMethodMetadataToUniqueId = new Dictionary(); private string GetMethodParameterSet(CommonMethodMetadata methodMetadata) { @@ -2100,7 +2100,7 @@ private void WriteGetCmdlet(TextWriter output) /* 1 */ CodeGeneration.EscapeSingleQuotedStringContent(commandMetadata.Name)); } - private static object s_enumCompilationLock = new object(); + private static readonly object s_enumCompilationLock = new object(); private static void CompileEnum(EnumMetadataEnum enumMetadata) { try diff --git a/src/System.Management.Automation/engine/ApplicationInfo.cs b/src/System.Management.Automation/engine/ApplicationInfo.cs index 308cea39b64..79ef77b6ce3 100644 --- a/src/System.Management.Automation/engine/ApplicationInfo.cs +++ b/src/System.Management.Automation/engine/ApplicationInfo.cs @@ -52,7 +52,7 @@ internal ApplicationInfo(string name, string path, ExecutionContext context) : b _context = context; } - private ExecutionContext _context; + private readonly ExecutionContext _context; #endregion ctor /// diff --git a/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs b/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs index e9b6be3caff..25cd6a2e8bc 100644 --- a/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs +++ b/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs @@ -25,7 +25,7 @@ internal ArgumentTypeConverterAttribute(params Type[] types) _convertTypes = types; } - private Type[] _convertTypes; + private readonly Type[] _convertTypes; internal Type TargetType { diff --git a/src/System.Management.Automation/engine/Attributes.cs b/src/System.Management.Automation/engine/Attributes.cs index 99433b32d0f..87af21b99ca 100644 --- a/src/System.Management.Automation/engine/Attributes.cs +++ b/src/System.Management.Automation/engine/Attributes.cs @@ -938,27 +938,27 @@ public sealed class ValidateRangeAttribute : ValidateEnumeratedArgumentsAttribut /// public object MinRange { get; } - private IComparable _minComparable; + private readonly IComparable _minComparable; /// /// Gets the attribute's maximum range. /// public object MaxRange { get; } - private IComparable _maxComparable; + private readonly IComparable _maxComparable; /// /// The range values and the value to validate will all be converted to the promoted type. /// If minRange and maxRange are the same type, /// - private Type _promotedType; + private readonly Type _promotedType; /// /// Gets the name of the predefined range. /// internal ValidateRangeKind? RangeKind { get => _rangeKind; } - private ValidateRangeKind? _rangeKind; + private readonly ValidateRangeKind? _rangeKind; /// /// Validates that each parameter argument falls in the range specified by @@ -1532,7 +1532,7 @@ public abstract class CachedValidValuesGeneratorBase : IValidateSetValuesGenerat { // Cached valid values. private string[] _validValues; - private int _validValuesCacheExpiration; + private readonly int _validValuesCacheExpiration; /// /// Initializes a new instance of the class. @@ -1591,11 +1591,11 @@ public sealed class ValidateSetAttribute : ValidateEnumeratedArgumentsAttribute { // We can use either static '_validValues' or dynamic valid values list generated by instance // of 'validValuesGenerator'. - private string[] _validValues; - private IValidateSetValuesGenerator validValuesGenerator = null; + private readonly string[] _validValues; + private readonly IValidateSetValuesGenerator validValuesGenerator = null; // The valid values generator cache works across 'ValidateSetAttribute' instances. - private static ConcurrentDictionary s_ValidValuesGeneratorCache = + private static readonly ConcurrentDictionary s_ValidValuesGeneratorCache = new ConcurrentDictionary(); /// @@ -1821,7 +1821,7 @@ public AllowEmptyCollectionAttribute() { } [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class ValidateDriveAttribute : ValidateArgumentsAttribute { - private string[] _validRootDrives; + private readonly string[] _validRootDrives; /// /// Gets the values in the set. diff --git a/src/System.Management.Automation/engine/COM/ComMethod.cs b/src/System.Management.Automation/engine/COM/ComMethod.cs index 32552c6bd14..39882a2cdb8 100644 --- a/src/System.Management.Automation/engine/COM/ComMethod.cs +++ b/src/System.Management.Automation/engine/COM/ComMethod.cs @@ -30,8 +30,8 @@ internal ComMethodInformation(bool hasvarargs, bool hasoptional, ParameterInform /// internal class ComMethod { - private Collection _methods = new Collection(); - private COM.ITypeInfo _typeInfo; + private readonly Collection _methods = new Collection(); + private readonly COM.ITypeInfo _typeInfo; /// /// Initializes new instance of ComMethod class. diff --git a/src/System.Management.Automation/engine/COM/ComProperty.cs b/src/System.Management.Automation/engine/COM/ComProperty.cs index 2de108a872e..0a3498384e8 100644 --- a/src/System.Management.Automation/engine/COM/ComProperty.cs +++ b/src/System.Management.Automation/engine/COM/ComProperty.cs @@ -22,7 +22,7 @@ internal class ComProperty private int _setterIndex; private int _setterByRefIndex; private int _getterIndex; - private COM.ITypeInfo _typeInfo; + private readonly COM.ITypeInfo _typeInfo; /// /// Initializes a new instance of ComProperty. diff --git a/src/System.Management.Automation/engine/COM/ComTypeInfo.cs b/src/System.Management.Automation/engine/COM/ComTypeInfo.cs index 6a03f31c9ac..d3b4f70e1a0 100644 --- a/src/System.Management.Automation/engine/COM/ComTypeInfo.cs +++ b/src/System.Management.Automation/engine/COM/ComTypeInfo.cs @@ -30,9 +30,9 @@ internal class ComTypeInfo /// /// Member variables. /// - private Dictionary _properties = null; - private Dictionary _methods = null; - private COM.ITypeInfo _typeinfo = null; + private readonly Dictionary _properties = null; + private readonly Dictionary _methods = null; + private readonly COM.ITypeInfo _typeinfo = null; private Guid _guid = Guid.Empty; /// diff --git a/src/System.Management.Automation/engine/COM/ComUtil.cs b/src/System.Management.Automation/engine/COM/ComUtil.cs index 4d5a9964339..b8f77e56334 100644 --- a/src/System.Management.Automation/engine/COM/ComUtil.cs +++ b/src/System.Management.Automation/engine/COM/ComUtil.cs @@ -371,8 +371,8 @@ internal static ComMethodInformation[] GetMethodInformationArray(COM.ITypeInfo t /// internal class ComEnumerator : IEnumerator { - private COM.IEnumVARIANT _enumVariant; - private object[] _element; + private readonly COM.IEnumVARIANT _enumVariant; + private readonly object[] _element; private ComEnumerator(COM.IEnumVARIANT enumVariant) { diff --git a/src/System.Management.Automation/engine/ChildrenCmdletProviderInterfaces.cs b/src/System.Management.Automation/engine/ChildrenCmdletProviderInterfaces.cs index 7fafdf84503..a9cc640f79c 100644 --- a/src/System.Management.Automation/engine/ChildrenCmdletProviderInterfaces.cs +++ b/src/System.Management.Automation/engine/ChildrenCmdletProviderInterfaces.cs @@ -761,8 +761,8 @@ internal bool HasChild( #region private data - private Cmdlet _cmdlet; - private SessionStateInternal _sessionState; + private readonly Cmdlet _cmdlet; + private readonly SessionStateInternal _sessionState; #endregion private data } diff --git a/src/System.Management.Automation/engine/CmdletFamilyProviderInterfaces.cs b/src/System.Management.Automation/engine/CmdletFamilyProviderInterfaces.cs index 2ce58a04afb..0df0ead4a13 100644 --- a/src/System.Management.Automation/engine/CmdletFamilyProviderInterfaces.cs +++ b/src/System.Management.Automation/engine/CmdletFamilyProviderInterfaces.cs @@ -102,7 +102,7 @@ internal ProviderIntrinsics(SessionStateInternal sessionState) #region private data - private InternalCommand _cmdlet; + private readonly InternalCommand _cmdlet; #endregion private data } diff --git a/src/System.Management.Automation/engine/CmdletInfo.cs b/src/System.Management.Automation/engine/CmdletInfo.cs index 896763d9d74..43d85df17ca 100644 --- a/src/System.Management.Automation/engine/CmdletInfo.cs +++ b/src/System.Management.Automation/engine/CmdletInfo.cs @@ -149,7 +149,7 @@ public string Verb } } - private string _verb = string.Empty; + private readonly string _verb = string.Empty; /// /// Gets the noun of the cmdlet. @@ -162,7 +162,7 @@ public string Noun } } - private string _noun = string.Empty; + private readonly string _noun = string.Empty; internal static bool SplitCmdletName(string name, out string verb, out string noun) { @@ -224,7 +224,7 @@ public PSSnapInInfo PSSnapIn } } - private PSSnapInInfo _PSSnapin; + private readonly PSSnapInInfo _PSSnapin; /// /// Gets the name of the PSSnapin the cmdlet is implemented in. @@ -279,7 +279,7 @@ public Type ImplementingType } } - private Type _implementingType = null; + private readonly Type _implementingType = null; /// /// Gets the synopsis of the cmdlet. diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index 70027d06c43..0164cd5a56c 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -479,7 +479,7 @@ internal static List CompleteModuleName(CompletionContext cont #endregion Module Names #region Command Parameters - private static string[] s_parameterNamesOfImportDSCResource = { "Name", "ModuleName", "ModuleVersion" }; + private static readonly string[] s_parameterNamesOfImportDSCResource = { "Name", "ModuleName", "ModuleVersion" }; internal static List CompleteCommandParameter(CompletionContext context) { @@ -2569,7 +2569,7 @@ private static void NativeCompletionCimCommands( } } - private static ConcurrentDictionary> s_cimNamespaceAndClassNameToAssociationResultClassNames = + private static readonly ConcurrentDictionary> s_cimNamespaceAndClassNameToAssociationResultClassNames = new ConcurrentDictionary>(StringComparer.OrdinalIgnoreCase); private static IEnumerable NativeCompletionCimAssociationResultClassName_GetResultClassNames( @@ -2704,7 +2704,7 @@ private static void NativeCompletionCimMethodName( result.AddRange(localResults.OrderBy(x => x.ListItemText, StringComparer.OrdinalIgnoreCase)); } - private static ConcurrentDictionary> s_cimNamespaceToClassNames = + private static readonly ConcurrentDictionary> s_cimNamespaceToClassNames = new ConcurrentDictionary>(StringComparer.OrdinalIgnoreCase); private static IEnumerable NativeCompletionCimClassName_GetClassNames(string targetNamespace) @@ -4505,7 +4505,7 @@ private struct SHARE_INFO_1 private const int ERROR_MORE_DATA = 234; private const int STYPE_DISKTREE = 0; private const int STYPE_MASK = 0x000000FF; - private static System.IO.EnumerationOptions _enumerationOptions = new System.IO.EnumerationOptions + private static readonly System.IO.EnumerationOptions _enumerationOptions = new System.IO.EnumerationOptions { MatchCasing = MatchCasing.CaseInsensitive, AttributesToSkip = 0 // Default is to skip Hidden and System files, so we clear this to retain existing behavior diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionResult.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionResult.cs index 763f54b60fa..24d48ddf152 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionResult.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionResult.cs @@ -65,22 +65,22 @@ public class CompletionResult /// /// Text to be used as the auto completion result. /// - private string _completionText; + private readonly string _completionText; /// /// Text to be displayed in a list. /// - private string _listItemText; + private readonly string _listItemText; /// /// The text for the tooltip with details to be displayed about the object. /// - private string _toolTip; + private readonly string _toolTip; /// /// Type of completion result. /// - private CompletionResultType _resultType; + private readonly CompletionResultType _resultType; /// /// Private member for null instance. diff --git a/src/System.Management.Automation/engine/CommandCompletion/ExtensibleCompletion.cs b/src/System.Management.Automation/engine/CommandCompletion/ExtensibleCompletion.cs index 71c76b3ce67..8e1061b0df2 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/ExtensibleCompletion.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/ExtensibleCompletion.cs @@ -164,7 +164,7 @@ protected override void EndProcessing() [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class ArgumentCompletionsAttribute : Attribute { - private string[] _completions; + private readonly string[] _completions; /// /// Initializes a new instance of the ArgumentCompletionsAttribute class. diff --git a/src/System.Management.Automation/engine/CommandDiscovery.cs b/src/System.Management.Automation/engine/CommandDiscovery.cs index c194a2f40f6..54b8d7728f6 100644 --- a/src/System.Management.Automation/engine/CommandDiscovery.cs +++ b/src/System.Management.Automation/engine/CommandDiscovery.cs @@ -37,7 +37,7 @@ internal CommandLookupEventArgs(string commandName, CommandOrigin commandOrigin, _context = context; } - private ExecutionContext _context; + private readonly ExecutionContext _context; /// /// The name of the command we're looking for. @@ -1281,10 +1281,10 @@ internal void UnregisterLookupCommandInfoAction(string currentAction, string com currentActionSet.Remove(command); } - private HashSet _activePreLookup = new HashSet(StringComparer.OrdinalIgnoreCase); - private HashSet _activeModuleSearch = new HashSet(StringComparer.OrdinalIgnoreCase); - private HashSet _activeCommandNotFound = new HashSet(StringComparer.OrdinalIgnoreCase); - private HashSet _activePostCommand = new HashSet(StringComparer.OrdinalIgnoreCase); + private readonly HashSet _activePreLookup = new HashSet(StringComparer.OrdinalIgnoreCase); + private readonly HashSet _activeModuleSearch = new HashSet(StringComparer.OrdinalIgnoreCase); + private readonly HashSet _activeCommandNotFound = new HashSet(StringComparer.OrdinalIgnoreCase); + private readonly HashSet _activePostCommand = new HashSet(StringComparer.OrdinalIgnoreCase); /// /// Gets the resolved paths contained in the PATH environment @@ -1428,7 +1428,7 @@ private static void InitPathExtCache(string pathExt) #region private members - private static object s_lockObject = new object(); + private static readonly object s_lockObject = new object(); private static string s_pathExtCacheKey; private static string[] s_cachedPathExtCollection; private static string[] s_cachedPathExtCollectionWithPs1; diff --git a/src/System.Management.Automation/engine/CommandMetadata.cs b/src/System.Management.Automation/engine/CommandMetadata.cs index 02f4f23c3cc..d6766256667 100644 --- a/src/System.Management.Automation/engine/CommandMetadata.cs +++ b/src/System.Management.Automation/engine/CommandMetadata.cs @@ -1532,7 +1532,7 @@ private static Collection GetRestrictedJobCommands() /// The command metadata cache. This is separate from the parameterMetadata cache /// because it is specific to cmdlets. /// - private static System.Collections.Concurrent.ConcurrentDictionary s_commandMetadataCache = + private static readonly System.Collections.Concurrent.ConcurrentDictionary s_commandMetadataCache = new System.Collections.Concurrent.ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); #endregion diff --git a/src/System.Management.Automation/engine/CommandPathSearch.cs b/src/System.Management.Automation/engine/CommandPathSearch.cs index 415736b8561..3dedb840d17 100644 --- a/src/System.Management.Automation/engine/CommandPathSearch.cs +++ b/src/System.Management.Automation/engine/CommandPathSearch.cs @@ -18,7 +18,7 @@ namespace System.Management.Automation internal class CommandPathSearch : IEnumerable, IEnumerator { [TraceSource("CommandSearch", "CommandSearch")] - private static PSTraceSource s_tracer = PSTraceSource.GetTracer("CommandSearch", "CommandSearch"); + private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("CommandSearch", "CommandSearch"); /// /// Constructs a command searching enumerator that resolves the location @@ -531,7 +531,7 @@ private void GetNewDirectoryResults(string pattern, string directory) /// The directory paths in which to look for commands. /// This is derived from the PATH environment variable. /// - private LookupPathCollection _lookupPaths; + private readonly LookupPathCollection _lookupPaths; /// /// The enumerator for the lookup paths. @@ -552,7 +552,7 @@ private void GetNewDirectoryResults(string pattern, string directory) /// /// The command name to search for. /// - private IEnumerable _patterns; + private readonly IEnumerable _patterns; /// /// The enumerator for the patterns. @@ -562,7 +562,7 @@ private void GetNewDirectoryResults(string pattern, string directory) /// /// A reference to the execution context for this runspace. /// - private ExecutionContext _context; + private readonly ExecutionContext _context; /// /// When reset is called, this gets set to true. Once MoveNext @@ -573,12 +573,12 @@ private void GetNewDirectoryResults(string pattern, string directory) /// /// If not null, called with the enumerated files for further processing. /// - private Func?> _postProcessEnumeratedFiles; + private readonly Func?> _postProcessEnumeratedFiles; - private string[] _orderedPathExt; - private Collection? _acceptableCommandNames; + private readonly string[] _orderedPathExt; + private readonly Collection? _acceptableCommandNames; - private bool _useFuzzyMatch = false; + private readonly bool _useFuzzyMatch = false; #endregion private members } diff --git a/src/System.Management.Automation/engine/CommandSearcher.cs b/src/System.Management.Automation/engine/CommandSearcher.cs index 093a2fbe993..0acedc407ba 100644 --- a/src/System.Management.Automation/engine/CommandSearcher.cs +++ b/src/System.Management.Automation/engine/CommandSearcher.cs @@ -1483,7 +1483,7 @@ private static CanDoPathLookupResult CanDoPathLookup(string possiblePath) /// /// Determines which command types will be globbed. /// - private SearchResolutionOptions _commandResolutionOptions; + private readonly SearchResolutionOptions _commandResolutionOptions; /// /// Determines which types of commands to look for. @@ -1499,7 +1499,7 @@ private static CanDoPathLookupResult CanDoPathLookup(string possiblePath) /// /// The execution context instance for the current engine... /// - private ExecutionContext _context; + private readonly ExecutionContext _context; /// /// A routine to initialize the path searcher... diff --git a/src/System.Management.Automation/engine/CommonCommandParameters.cs b/src/System.Management.Automation/engine/CommonCommandParameters.cs index 19c693551a2..c23875c0e80 100644 --- a/src/System.Management.Automation/engine/CommonCommandParameters.cs +++ b/src/System.Management.Automation/engine/CommonCommandParameters.cs @@ -234,7 +234,7 @@ public string PipelineVariable #endregion parameters - private MshCommandRuntime _commandRuntime; + private readonly MshCommandRuntime _commandRuntime; internal class ValidateVariableName : ValidateArgumentsAttribute { diff --git a/src/System.Management.Automation/engine/ContentCmdletProviderInterfaces.cs b/src/System.Management.Automation/engine/ContentCmdletProviderInterfaces.cs index a2997a77b72..83064c082e1 100644 --- a/src/System.Management.Automation/engine/ContentCmdletProviderInterfaces.cs +++ b/src/System.Management.Automation/engine/ContentCmdletProviderInterfaces.cs @@ -586,8 +586,8 @@ internal object ClearContentDynamicParameters(string path, CmdletProviderContext #region private data - private Cmdlet _cmdlet; - private SessionStateInternal _sessionState; + private readonly Cmdlet _cmdlet; + private readonly SessionStateInternal _sessionState; #endregion private data } diff --git a/src/System.Management.Automation/engine/CoreAdapter.cs b/src/System.Management.Automation/engine/CoreAdapter.cs index 6bf9d0c52aa..6c8e6be3e8f 100644 --- a/src/System.Management.Automation/engine/CoreAdapter.cs +++ b/src/System.Management.Automation/engine/CoreAdapter.cs @@ -2014,7 +2014,7 @@ internal class CacheTable /// . /// internal Collection memberCollection; - private Dictionary _indexes; + private readonly Dictionary _indexes; internal CacheTable() { @@ -2214,7 +2214,7 @@ internal object Invoke(object target, object[] arguments) return method.Invoke(target, arguments); } - private static OpCode[] s_ldc = new OpCode[] { + private static readonly OpCode[] s_ldc = new OpCode[] { OpCodes.Ldc_I4_0, OpCodes.Ldc_I4_1, OpCodes.Ldc_I4_2, OpCodes.Ldc_I4_3, OpCodes.Ldc_I4_4, OpCodes.Ldc_I4_5, OpCodes.Ldc_I4_6, OpCodes.Ldc_I4_7, OpCodes.Ldc_I4_8 }; @@ -2557,7 +2557,7 @@ internal class DotNetAdapter : Adapter BindingFlags.IgnoreCase | BindingFlags.Instance); private const BindingFlags staticBindingFlags = (BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Static); - private bool _isStatic; + private readonly bool _isStatic; internal DotNetAdapter() { } @@ -2570,25 +2570,25 @@ internal DotNetAdapter(bool isStatic) /// /// CLR reflection property cache for instance properties. /// - private static Dictionary s_instancePropertyCacheTable = new Dictionary(); + private static readonly Dictionary s_instancePropertyCacheTable = new Dictionary(); // This static is thread safe based on the lock in GetStaticPropertyReflectionTable /// /// CLR reflection property cache for static properties. /// - private static Dictionary s_staticPropertyCacheTable = new Dictionary(); + private static readonly Dictionary s_staticPropertyCacheTable = new Dictionary(); // This static is thread safe based on the lock in GetInstanceMethodReflectionTable /// /// CLR reflection method cache for instance methods. /// - private static Dictionary s_instanceMethodCacheTable = new Dictionary(); + private static readonly Dictionary s_instanceMethodCacheTable = new Dictionary(); // This static is thread safe based on the lock in GetStaticMethodReflectionTable /// /// CLR reflection method cache for static methods. /// - private static Dictionary s_staticMethodCacheTable = new Dictionary(); + private static readonly Dictionary s_staticMethodCacheTable = new Dictionary(); // This static is thread safe based on the lock in GetInstanceMethodReflectionTable /// @@ -3887,7 +3887,7 @@ private static bool PropertyIsStatic(PSProperty property) internal override bool CanSiteBinderOptimize(MemberTypes typeToOperateOn) { return true; } - private static ConcurrentDictionary s_typeToTypeNameDictionary = + private static readonly ConcurrentDictionary s_typeToTypeNameDictionary = new ConcurrentDictionary(); internal static ConsolidatedString GetInternedTypeNameHierarchy(Type type) @@ -4748,7 +4748,7 @@ protected override T GetFirstMemberOrDefault(object obj, MemberNamePredicate /// internal class DotNetAdapterWithComTypeName : DotNetAdapter { - private ComTypeInfo _comTypeInfo; + private readonly ComTypeInfo _comTypeInfo; internal DotNetAdapterWithComTypeName(ComTypeInfo comTypeInfo) { _comTypeInfo = comTypeInfo; diff --git a/src/System.Management.Automation/engine/Credential.cs b/src/System.Management.Automation/engine/Credential.cs index df17c38a884..c11778c9ee0 100644 --- a/src/System.Management.Automation/engine/Credential.cs +++ b/src/System.Management.Automation/engine/Credential.cs @@ -177,8 +177,8 @@ private PSCredential(SerializationInfo info, StreamingContext context) } } - private string _userName; - private SecureString _password; + private readonly string _userName; + private readonly SecureString _password; /// /// User's name. diff --git a/src/System.Management.Automation/engine/DataStoreAdapter.cs b/src/System.Management.Automation/engine/DataStoreAdapter.cs index 3b01bae2934..2a0aac8993a 100644 --- a/src/System.Management.Automation/engine/DataStoreAdapter.cs +++ b/src/System.Management.Automation/engine/DataStoreAdapter.cs @@ -29,7 +29,7 @@ public class PSDriveInfo : IComparable [Dbg.TraceSourceAttribute( "PSDriveInfo", "The namespace navigation tracer")] - private static Dbg.PSTraceSource s_tracer = + private static readonly Dbg.PSTraceSource s_tracer = Dbg.PSTraceSource.GetTracer("PSDriveInfo", "The namespace navigation tracer"); diff --git a/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs b/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs index d341b2803dd..c8ab8a0a23e 100644 --- a/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs +++ b/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs @@ -34,7 +34,7 @@ public class ProviderInfo /// /// The instance of session state the provider belongs to. /// - private SessionState _sessionState; + private readonly SessionState _sessionState; private string _fullName; private string _cachedModuleName; @@ -221,7 +221,7 @@ public Collection Drives /// A hidden drive for the provider that is used for setting /// the location to a provider-qualified path. /// - private PSDriveInfo _hiddenDrive; + private readonly PSDriveInfo _hiddenDrive; /// /// Gets the hidden drive for the provider that is used diff --git a/src/System.Management.Automation/engine/DefaultCommandRuntime.cs b/src/System.Management.Automation/engine/DefaultCommandRuntime.cs index 4df5c39fe15..fb6c608ab0f 100644 --- a/src/System.Management.Automation/engine/DefaultCommandRuntime.cs +++ b/src/System.Management.Automation/engine/DefaultCommandRuntime.cs @@ -13,7 +13,7 @@ namespace System.Management.Automation /// internal class DefaultCommandRuntime : ICommandRuntime2 { - private List _output; + private readonly List _output; /// /// Constructs an instance of the default ICommandRuntime object /// that will write objects into the list that was passed. diff --git a/src/System.Management.Automation/engine/DriveInterfaces.cs b/src/System.Management.Automation/engine/DriveInterfaces.cs index 8d605e7313a..1ad5d922177 100644 --- a/src/System.Management.Automation/engine/DriveInterfaces.cs +++ b/src/System.Management.Automation/engine/DriveInterfaces.cs @@ -387,7 +387,7 @@ public Collection GetAllForProvider(string providerName) #region private data // A private reference to the internal session state of the engine. - private SessionStateInternal _sessionState; + private readonly SessionStateInternal _sessionState; #endregion private data } diff --git a/src/System.Management.Automation/engine/DscResourceSearcher.cs b/src/System.Management.Automation/engine/DscResourceSearcher.cs index 8bb4f5bd267..bfd406f56ff 100644 --- a/src/System.Management.Automation/engine/DscResourceSearcher.cs +++ b/src/System.Management.Automation/engine/DscResourceSearcher.cs @@ -27,8 +27,8 @@ internal DscResourceSearcher( #region private properties - private string _resourceName = null; - private ExecutionContext _context = null; + private readonly string _resourceName = null; + private readonly ExecutionContext _context = null; private DscResourceInfo _currentMatch = null; private IEnumerator _matchingResource = null; private Collection _matchingResourceList = null; diff --git a/src/System.Management.Automation/engine/EngineIntrinsics.cs b/src/System.Management.Automation/engine/EngineIntrinsics.cs index ca322dbff06..0bc31124bcf 100644 --- a/src/System.Management.Automation/engine/EngineIntrinsics.cs +++ b/src/System.Management.Automation/engine/EngineIntrinsics.cs @@ -108,8 +108,8 @@ public CommandInvocationIntrinsics InvokeCommand #region private data - private ExecutionContext _context; - private PSHost _host; + private readonly ExecutionContext _context; + private readonly PSHost _host; private CommandInvocationIntrinsics _invokeCommand; #endregion private data } diff --git a/src/System.Management.Automation/engine/EnumExpressionEvaluator.cs b/src/System.Management.Automation/engine/EnumExpressionEvaluator.cs index 092500c0af7..3ca45201528 100644 --- a/src/System.Management.Automation/engine/EnumExpressionEvaluator.cs +++ b/src/System.Management.Automation/engine/EnumExpressionEvaluator.cs @@ -318,7 +318,7 @@ private bool isUnsigned(Type type) #region private members - private Type _underType = null; + private readonly Type _underType = null; #endregion diff --git a/src/System.Management.Automation/engine/EnumMinimumDisambiguation.cs b/src/System.Management.Automation/engine/EnumMinimumDisambiguation.cs index 543d920418f..18332cc37c6 100644 --- a/src/System.Management.Automation/engine/EnumMinimumDisambiguation.cs +++ b/src/System.Management.Automation/engine/EnumMinimumDisambiguation.cs @@ -122,6 +122,6 @@ internal static string EnumAllValues(Type enumType) return returnValue.ToString(); } - private static Dictionary s_specialDisambiguateCases = new Dictionary(); + private static readonly Dictionary s_specialDisambiguateCases = new Dictionary(); } } diff --git a/src/System.Management.Automation/engine/ErrorPackage.cs b/src/System.Management.Automation/engine/ErrorPackage.cs index cf02b7db8d1..e127cc710b0 100644 --- a/src/System.Management.Automation/engine/ErrorPackage.cs +++ b/src/System.Management.Automation/engine/ErrorPackage.cs @@ -477,7 +477,7 @@ public override string ToString() #region Private // back-reference for facade class - private ErrorRecord _errorRecord; + private readonly ErrorRecord _errorRecord; /// /// The Activity, Reason, TargetName and TargetType strings in @@ -757,7 +757,7 @@ public string Message get { return ErrorRecord.NotNull(_message); } } - private string _message = string.Empty; + private readonly string _message = string.Empty; /// /// Text describing the recommended action in the event that this error @@ -1635,7 +1635,7 @@ internal bool SerializeExtendedInfo #endregion Public Properties #region Private - private string _errorId; + private readonly string _errorId; #region Exposed by ErrorCategoryInfo internal ErrorCategory _category; diff --git a/src/System.Management.Automation/engine/EventManager.cs b/src/System.Management.Automation/engine/EventManager.cs index 86c639ab9af..117dbc606c0 100644 --- a/src/System.Management.Automation/engine/EventManager.cs +++ b/src/System.Management.Automation/engine/EventManager.cs @@ -331,12 +331,12 @@ internal PSLocalEventManager(ExecutionContext context) _context = context; } - private Dictionary _eventSubscribers; - private Dictionary> _engineEventSubscribers; - private Queue _actionQueue; - private ExecutionContext _context; + private readonly Dictionary _eventSubscribers; + private readonly Dictionary> _engineEventSubscribers; + private readonly Queue _actionQueue; + private readonly ExecutionContext _context; private int _nextSubscriptionId = 1; - private double _throttleLimit = 1; + private readonly double _throttleLimit = 1; private int _throttleChecks = 0; // The assembly and module to hold our event registrations @@ -640,7 +640,7 @@ private void EnableTimer() #endregion OnIdleProcessing - private static Dictionary s_generatedEventHandlers = new Dictionary(); + private static readonly Dictionary s_generatedEventHandlers = new Dictionary(); private void ProcessNewSubscriber(PSEventSubscriber subscriber, object source, string eventName, string sourceIdentifier, PSObject data, bool supportEvent, bool forwardEvent) { Delegate handlerDelegate = null; @@ -1167,7 +1167,7 @@ private void AutoUnregisterEventIfNecessary(PSEventSubscriber subscriber) } } - private object _actionProcessingLock = new object(); + private readonly object _actionProcessingLock = new object(); private EventAction _processingAction = null; /// @@ -1568,7 +1568,7 @@ public void Dispose(bool disposing) internal class PSRemoteEventManager : PSEventManager { /// Computer on which the event was generated - private string _computerName; + private readonly string _computerName; /// Runspace on which the event was generated private Guid _runspaceId; @@ -1944,7 +1944,7 @@ internal PSEventSubscriber(ExecutionContext context, int id, object source, HandlerDelegate = handlerDelegate; } - private ExecutionContext _context; + private readonly ExecutionContext _context; /// /// Create a bound script block. @@ -2349,7 +2349,7 @@ public class PSEventArgsCollection : IEnumerable /// The event generated when a new event is received. /// public event PSEventReceivedEventHandler PSEventReceived; - private List _eventCollection = new List(); + private readonly List _eventCollection = new List(); /// /// Add add an event to the collection. @@ -2489,8 +2489,8 @@ public PSEventJob(PSEventManager eventManager, PSEventSubscriber subscriber, Scr _subscriber = subscriber; } - private PSEventManager _eventManager = null; - private PSEventSubscriber _subscriber = null; + private readonly PSEventManager _eventManager = null; + private readonly PSEventSubscriber _subscriber = null; private int _highestErrorIndex = 0; /// diff --git a/src/System.Management.Automation/engine/ExecutionContext.cs b/src/System.Management.Automation/engine/ExecutionContext.cs index 592b4554811..34e17ba21c2 100644 --- a/src/System.Management.Automation/engine/ExecutionContext.cs +++ b/src/System.Management.Automation/engine/ExecutionContext.cs @@ -772,11 +772,11 @@ internal EngineIntrinsics EngineIntrinsics internal class SavedContextData { - private bool _stepScript; - private bool _ignoreScriptDebug; - private int _PSDebug; + private readonly bool _stepScript; + private readonly bool _ignoreScriptDebug; + private readonly int _PSDebug; - private Pipe _shellFunctionErrorOutputPipe; + private readonly Pipe _shellFunctionErrorOutputPipe; public SavedContextData(ExecutionContext context) { @@ -1637,7 +1637,7 @@ private void InitializeCommon(AutomationEngine engine, PSHost hostInterface) Modules = new ModuleIntrinsics(this); } - private static object lockObject = new object(); + private static readonly object lockObject = new object(); #if !CORECLR // System.AppDomain is not in CoreCLR private static bool _assemblyEventHandlerSet = false; diff --git a/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs b/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs index 4866316efdc..7f4fd93364b 100644 --- a/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs +++ b/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs @@ -605,7 +605,7 @@ public ErrorRecord ErrorRecord } private ErrorRecord _errorRecord; - private string _errorId = "PSInvalidCastException"; + private readonly string _errorId = "PSInvalidCastException"; } } diff --git a/src/System.Management.Automation/engine/GetCommandCommand.cs b/src/System.Management.Automation/engine/GetCommandCommand.cs index 709c84b973c..bb28b8b7d4b 100644 --- a/src/System.Management.Automation/engine/GetCommandCommand.cs +++ b/src/System.Management.Automation/engine/GetCommandCommand.cs @@ -350,7 +350,7 @@ public PSTypeName[] ParameterType [Parameter(ParameterSetName = "AllCommandSet")] public SwitchParameter UseFuzzyMatching { get; set; } - private List _commandScores = new List(); + private readonly List _commandScores = new List(); /// /// Gets or sets the parameter that determines if return cmdlets based on abbreviation expansion. @@ -1515,7 +1515,7 @@ private bool IsCommandInResult(CommandInfo command) #region Members - private Dictionary _commandsWritten = + private readonly Dictionary _commandsWritten = new Dictionary(StringComparer.OrdinalIgnoreCase); private List _accumulatedResults = new List(); diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index 80fbfcc4b5f..c01bc184b67 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -1250,10 +1250,10 @@ IEnumerator System.Collections.Generic.IEnumerable.GetEnumerator() return _internalCollection.GetEnumerator(); } - private Collection _internalCollection; + private readonly Collection _internalCollection; // object to use for locking - private object _syncObject = new object(); + private readonly object _syncObject = new object(); } /// @@ -1438,7 +1438,7 @@ private static InitialSessionState CreateRestrictedForRemoteServer() } // Porting note: moved to Platform so we have one list to maintain - private static string[] s_PSCoreFormatFileNames = Platform.FormatFileNames.ToArray(); + private static readonly string[] s_PSCoreFormatFileNames = Platform.FormatFileNames.ToArray(); private static void IncludePowerShellCoreFormats(InitialSessionState iss) { @@ -2118,7 +2118,7 @@ public virtual HashSet StartupScripts private HashSet _startupScripts = new HashSet(); - private object _syncObject = new object(); + private readonly object _syncObject = new object(); internal void Bind(ExecutionContext context, bool updateOnly, PSModuleInfo module, bool noClobber, bool local, bool setLocation) { @@ -4100,7 +4100,7 @@ internal void ImportCmdletsFromAssembly(Assembly assembly, PSModuleInfo module) /// /// This is the default function to use for tab expansion. /// - private static string s_tabExpansionFunctionText = @" + private static readonly string s_tabExpansionFunctionText = @" <# Options include: RelativeFilePaths - [bool] Always resolve file paths using Resolve-Path -Relative. @@ -4773,7 +4773,7 @@ internal static SessionStateAliasEntry[] BuiltInAliases internal const string DefaultSetDriveFunctionText = "Set-Location $MyInvocation.MyCommand.Name"; internal static ScriptBlock SetDriveScriptBlock = ScriptBlock.CreateDelayParsedScriptBlock(DefaultSetDriveFunctionText, isProductCode: true); - private static PSLanguageMode systemLanguageMode = (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) ? PSLanguageMode.ConstrainedLanguage : PSLanguageMode.FullLanguage; + private static readonly PSLanguageMode systemLanguageMode = (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) ? PSLanguageMode.ConstrainedLanguage : PSLanguageMode.FullLanguage; internal static SessionStateFunctionEntry[] BuiltInFunctions = new SessionStateFunctionEntry[] { // Functions that don't require full language mode @@ -4839,7 +4839,7 @@ internal static void RemoveAllDrivesForProvider(ProviderInfo pi, SessionStateInt } } - private static PSTraceSource s_PSSnapInTracer = PSTraceSource.GetTracer("PSSnapInLoadUnload", "Loading and unloading mshsnapins", false); + private static readonly PSTraceSource s_PSSnapInTracer = PSTraceSource.GetTracer("PSSnapInLoadUnload", "Loading and unloading mshsnapins", false); internal static string CoreSnapin = "Microsoft.PowerShell.Core"; internal static string CoreModule = "Microsoft.PowerShell.Core"; @@ -5482,7 +5482,7 @@ private static string GetHelpFile(string assemblyPath) return Path.GetFileName(assemblyPath).Replace(".ni.dll", ".dll") + StringLiterals.HelpFileExtension; } - private static PSTraceSource s_PSSnapInTracer = PSTraceSource.GetTracer("PSSnapInLoadUnload", "Loading and unloading mshsnapins", false); + private static readonly PSTraceSource s_PSSnapInTracer = PSTraceSource.GetTracer("PSSnapInLoadUnload", "Loading and unloading mshsnapins", false); } // Guid is {15d4c170-2f29-5689-a0e2-d95b0c7b4ea0} diff --git a/src/System.Management.Automation/engine/InternalCommands.cs b/src/System.Management.Automation/engine/InternalCommands.cs index 348f4b33277..11470259f3c 100644 --- a/src/System.Management.Automation/engine/InternalCommands.cs +++ b/src/System.Management.Automation/engine/InternalCommands.cs @@ -91,7 +91,7 @@ public PSObject InputObject #region ScriptBlockSet - private List _scripts = new List(); + private readonly List _scripts = new List(); /// /// Gets or sets the script block to apply in begin processing. diff --git a/src/System.Management.Automation/engine/ItemCmdletProviderInterfaces.cs b/src/System.Management.Automation/engine/ItemCmdletProviderInterfaces.cs index 63f4bbaffcb..da01715e6d7 100644 --- a/src/System.Management.Automation/engine/ItemCmdletProviderInterfaces.cs +++ b/src/System.Management.Automation/engine/ItemCmdletProviderInterfaces.cs @@ -2082,8 +2082,8 @@ internal bool IsContainer( #region private data - private Cmdlet _cmdlet; - private SessionStateInternal _sessionState; + private readonly Cmdlet _cmdlet; + private readonly SessionStateInternal _sessionState; #endregion private data } diff --git a/src/System.Management.Automation/engine/LanguagePrimitives.cs b/src/System.Management.Automation/engine/LanguagePrimitives.cs index 50b2e7950f7..5f306b86d9d 100644 --- a/src/System.Management.Automation/engine/LanguagePrimitives.cs +++ b/src/System.Management.Automation/engine/LanguagePrimitives.cs @@ -299,7 +299,7 @@ internal enum ConversionRank public static class LanguagePrimitives { [TraceSource("ETS", "Extended Type System")] - private static PSTraceSource s_tracer = PSTraceSource.GetTracer("ETS", "Extended Type System"); + private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("ETS", "Extended Type System"); internal delegate void MemberNotFoundError(PSObject pso, DictionaryEntry property, Type resultType); @@ -364,8 +364,8 @@ internal static void UpdateTypeConvertFromTypeTable(string typeName) /// private class EnumerableTWrapper : IEnumerable { - private object _enumerable; - private Type _enumerableType; + private readonly object _enumerable; + private readonly Type _enumerableType; private DynamicMethod _getEnumerator; internal EnumerableTWrapper(object enumerable, Type enumerableType) @@ -413,7 +413,7 @@ private static IEnumerable GetEnumerableFromIEnumerableT(object obj) } private delegate IEnumerable GetEnumerableDelegate(object obj); - private static Dictionary s_getEnumerableCache = new Dictionary(32); + private static readonly Dictionary s_getEnumerableCache = new Dictionary(32); private static GetEnumerableDelegate GetOrCalculateEnumerable(Type type) { @@ -1587,7 +1587,7 @@ public static string ConvertTypeNameToPSTypeName(string typeName) // CIM name string to .NET namestring mapping table // (Considered using the MI routines but they didn't do quite the right thing. // - private static Dictionary s_nameMap = new Dictionary(StringComparer.OrdinalIgnoreCase) { + private static readonly Dictionary s_nameMap = new Dictionary(StringComparer.OrdinalIgnoreCase) { { "SInt8", "SByte" }, { "UInt8", "Byte" }, { "SInt16", "Int16" }, @@ -4344,7 +4344,7 @@ public object Invoke(object valueToConvert, Type resultType, bool recurse, PSObj } } - private static Dictionary s_converterCache = new Dictionary(256); + private static readonly Dictionary s_converterCache = new Dictionary(256); private static IConversionData CacheConversion(Type fromType, Type toType, PSConverter converter, ConversionRank rank) { @@ -4382,7 +4382,7 @@ internal static ConversionRank GetConversionRank(Type fromType, Type toType) return FigureConversion(fromType, toType).Rank; } - private static Type[] s_numericTypes = new Type[] { + private static readonly Type[] s_numericTypes = new Type[] { typeof(Int16), typeof(Int32), typeof(Int64), typeof(UInt16), typeof(UInt32), typeof(UInt64), typeof(sbyte), typeof(byte), @@ -4390,17 +4390,17 @@ internal static ConversionRank GetConversionRank(Type fromType, Type toType) typeof(BigInteger) }; - private static Type[] s_integerTypes = new Type[] { + private static readonly Type[] s_integerTypes = new Type[] { typeof(Int16), typeof(Int32), typeof(Int64), typeof(UInt16), typeof(UInt32), typeof(UInt64), typeof(sbyte), typeof(byte) }; // Do not reorder the elements of these arrays, we depend on them being ordered by increasing size. - private static Type[] s_signedIntegerTypes = new Type[] { typeof(sbyte), typeof(Int16), typeof(Int32), typeof(Int64) }; - private static Type[] s_unsignedIntegerTypes = new Type[] { typeof(byte), typeof(UInt16), typeof(UInt32), typeof(UInt64) }; + private static readonly Type[] s_signedIntegerTypes = new Type[] { typeof(sbyte), typeof(Int16), typeof(Int32), typeof(Int64) }; + private static readonly Type[] s_unsignedIntegerTypes = new Type[] { typeof(byte), typeof(UInt16), typeof(UInt32), typeof(UInt64) }; - private static Type[] s_realTypes = new Type[] { typeof(Single), typeof(double), typeof(decimal) }; + private static readonly Type[] s_realTypes = new Type[] { typeof(Single), typeof(double), typeof(decimal) }; internal static void RebuildConversionCache() { @@ -5527,7 +5527,7 @@ private static bool TypeConverterPossiblyExists(Type type) return false; } - private static Dictionary s_possibleTypeConverter = new Dictionary(16); + private static readonly Dictionary s_possibleTypeConverter = new Dictionary(16); // This is the internal dummy type used when an IDictionary is converted to a pscustomobject // PS C:\> $ps = [pscustomobject]@{a=10;b=5} diff --git a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs index 522a69f11ed..c46d0e43847 100644 --- a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs +++ b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs @@ -945,7 +945,7 @@ protected abstract PSProperty DoGetProperty(ManagementBaseObject wmiObject, #region Private Data - private static HybridDictionary s_instanceMethodCacheTable = new HybridDictionary(); + private static readonly HybridDictionary s_instanceMethodCacheTable = new HybridDictionary(); #endregion } diff --git a/src/System.Management.Automation/engine/Modules/AnalysisCache.cs b/src/System.Management.Automation/engine/Modules/AnalysisCache.cs index 324922e9daa..a1641823b76 100644 --- a/src/System.Management.Automation/engine/Modules/AnalysisCache.cs +++ b/src/System.Management.Automation/engine/Modules/AnalysisCache.cs @@ -29,10 +29,10 @@ namespace System.Management.Automation /// internal class AnalysisCache { - private static AnalysisCacheData s_cacheData = AnalysisCacheData.Get(); + private static readonly AnalysisCacheData s_cacheData = AnalysisCacheData.Get(); // This dictionary shouldn't see much use, so low concurrency and capacity - private static ConcurrentDictionary s_modulesBeingAnalyzed = + private static readonly ConcurrentDictionary s_modulesBeingAnalyzed = new ConcurrentDictionary( /*concurrency*/1, /*capacity*/2, StringComparer.OrdinalIgnoreCase); internal static char[] InvalidCommandNameCharacters = new[] diff --git a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs index a4b30616132..4043dbbe16d 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs @@ -274,7 +274,7 @@ internal List MatchAll "DefaultCommandPrefix" }; - private static string[] s_moduleVersionMembers = new string[] { + private static readonly string[] s_moduleVersionMembers = new string[] { "ModuleName", "GUID", "ModuleVersion" @@ -305,7 +305,7 @@ internal List MatchAll /// internal static object s_WindowsPowerShellCompatSyncObject = new object(); - private Dictionary _currentlyProcessingModules = new Dictionary(); + private readonly Dictionary _currentlyProcessingModules = new Dictionary(); internal bool LoadUsingModulePath(bool found, IEnumerable modulePath, string name, SessionState ss, ImportModuleOptions options, ManifestProcessingFlags manifestProcessingFlags, out PSModuleInfo module) @@ -6071,7 +6071,7 @@ private static bool ShouldProcessScriptModule(PSModuleInfo parentModule, ref boo return shouldProcessModule; } - private static object s_lockObject = new object(); + private static readonly object s_lockObject = new object(); private void ClearAnalysisCaches() { @@ -6083,7 +6083,7 @@ private void ClearAnalysisCaches() } // Analyzes a binary module implementation for its cmdlets. - private static Dictionary> s_binaryAnalysisCache = + private static readonly Dictionary> s_binaryAnalysisCache = new Dictionary>(); #if CORECLR @@ -6277,7 +6277,7 @@ private static void AnalyzeSnapinDomainHelper() #endif // Analyzes a script module implementation for its exports. - private static Dictionary s_scriptAnalysisCache = new Dictionary(); + private static readonly Dictionary s_scriptAnalysisCache = new Dictionary(); private PSModuleInfo AnalyzeScriptFile(string filename, bool force, ExecutionContext context) { diff --git a/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs b/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs index 29bc54a6798..7295948e627 100644 --- a/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs +++ b/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs @@ -876,7 +876,7 @@ public IEnumerable CompatiblePSEditions get { return _compatiblePSEditions; } } - private List _compatiblePSEditions = new List(); + private readonly List _compatiblePSEditions = new List(); internal void AddToCompatiblePSEditions(string psEdition) { diff --git a/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs b/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs index 870c564244b..5dfbc1a0a7f 100644 --- a/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs +++ b/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs @@ -546,7 +546,7 @@ private Hashtable DoPsuedoParameterBinding(CommandAst commandAst, string command return result; } - private static Dictionary s_parameterBindingInfoTable; + private static readonly Dictionary s_parameterBindingInfoTable; private class ParameterBindingInfo { diff --git a/src/System.Management.Automation/engine/MshCmdlet.cs b/src/System.Management.Automation/engine/MshCmdlet.cs index 839ea1c005f..c00e211d3ec 100644 --- a/src/System.Management.Automation/engine/MshCmdlet.cs +++ b/src/System.Management.Automation/engine/MshCmdlet.cs @@ -70,7 +70,7 @@ public interface IDynamicParameters /// public struct SwitchParameter { - private bool _isPresent; + private readonly bool _isPresent; /// /// Returns true if the parameter was specified on the command line, false otherwise. /// @@ -233,9 +233,9 @@ public override string ToString() /// public class CommandInvocationIntrinsics { - private ExecutionContext _context; - private PSCmdlet _cmdlet; - private MshCommandRuntime _commandRuntime; + private readonly ExecutionContext _context; + private readonly PSCmdlet _cmdlet; + private readonly MshCommandRuntime _commandRuntime; internal CommandInvocationIntrinsics(ExecutionContext context, PSCmdlet cmdlet) { diff --git a/src/System.Management.Automation/engine/MshCommandRuntime.cs b/src/System.Management.Automation/engine/MshCommandRuntime.cs index a40ebced867..0e18a0037c3 100644 --- a/src/System.Management.Automation/engine/MshCommandRuntime.cs +++ b/src/System.Management.Automation/engine/MshCommandRuntime.cs @@ -91,8 +91,8 @@ internal bool IsPipelineInputExpected internal PipelineProcessor PipelineProcessor { get; set; } - private CommandInfo _commandInfo; - private InternalCommand _thisCommand; + private readonly CommandInfo _commandInfo; + private readonly InternalCommand _thisCommand; #endregion private_members @@ -2350,10 +2350,10 @@ public void Dispose() // There is no finalizer, by design. This class relies on always // being disposed and always following stack semantics. - private PipelineProcessor _pp = null; - private InternalCommand _wasPermittedToWrite = null; - private bool _wasPermittedToWriteToPipeline = false; - private Thread _wasPermittedToWriteThread = null; + private readonly PipelineProcessor _pp = null; + private readonly InternalCommand _wasPermittedToWrite = null; + private readonly bool _wasPermittedToWriteToPipeline = false; + private readonly Thread _wasPermittedToWriteThread = null; } /// @@ -3020,7 +3020,7 @@ internal ActionPreference DebugPreference } } - private bool _isVerbosePreferenceCached = false; + private readonly bool _isVerbosePreferenceCached = false; private ActionPreference _verbosePreference = InitialSessionState.DefaultVerbosePreference; /// /// Preference setting. @@ -3069,7 +3069,7 @@ internal ActionPreference VerbosePreference internal bool IsWarningActionSet { get; private set; } = false; - private bool _isWarningPreferenceCached = false; + private readonly bool _isWarningPreferenceCached = false; private ActionPreference _warningPreference = InitialSessionState.DefaultWarningPreference; /// /// Preference setting. diff --git a/src/System.Management.Automation/engine/MshSecurityException.cs b/src/System.Management.Automation/engine/MshSecurityException.cs index 878de10e2b4..814ed4b7e4c 100644 --- a/src/System.Management.Automation/engine/MshSecurityException.cs +++ b/src/System.Management.Automation/engine/MshSecurityException.cs @@ -118,7 +118,7 @@ public override string Message get { return _message; } } - private string _message; + private readonly string _message; } } diff --git a/src/System.Management.Automation/engine/MshSnapinQualifiedName.cs b/src/System.Management.Automation/engine/MshSnapinQualifiedName.cs index 42f73df2a46..1674b3fd2d7 100644 --- a/src/System.Management.Automation/engine/MshSnapinQualifiedName.cs +++ b/src/System.Management.Automation/engine/MshSnapinQualifiedName.cs @@ -91,7 +91,7 @@ internal string FullName } } - private string _fullName; + private readonly string _fullName; /// /// Gets the command's PSSnapin name. @@ -104,7 +104,7 @@ internal string PSSnapInName } } - private string _psSnapinName; + private readonly string _psSnapinName; /// /// Gets the command's short name. @@ -117,7 +117,7 @@ internal string ShortName } } - private string _shortName; + private readonly string _shortName; /// /// The full name. diff --git a/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs b/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs index 0091596a443..7e6e660e9d4 100644 --- a/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs +++ b/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs @@ -472,7 +472,7 @@ private static string GetEnumerableArgSeparator(ArrayLiteralAst arrayLiteralAst, /// /// The native command to bind to. /// - private NativeCommand _nativeCommand; + private readonly NativeCommand _nativeCommand; private static readonly string TildeDirectorySeparator = $"~{Path.DirectorySeparatorChar}"; private static readonly string TildeAltDirectorySeparator = $"~{Path.AltDirectorySeparatorChar}"; diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index 45fb9582599..3089a7c306f 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -142,7 +142,7 @@ internal class NativeCommandProcessor : CommandProcessorBase /// Information about application which is invoked by this instance of /// NativeCommandProcessor. /// - private ApplicationInfo _applicationInfo; + private readonly ApplicationInfo _applicationInfo; /// /// Initializes the new instance of NativeCommandProcessor class. @@ -342,7 +342,7 @@ internal override void ProcessRecord() /// /// This is used for writing input to the process. /// - private ProcessInputWriter _inputWriter = null; + private readonly ProcessInputWriter _inputWriter = null; /// /// Is true if this command is to be run "standalone" - that is, with @@ -370,14 +370,14 @@ internal override void ProcessRecord() private BlockingCollection _nativeProcessOutputQueue; private static bool? s_supportScreenScrape = null; - private bool _isTranscribing; + private readonly bool _isTranscribing; private Host.Coordinates _startPosition; /// /// Object used for synchronization between StopProcessing thread and /// Pipeline thread. /// - private object _sync = new object(); + private readonly object _sync = new object(); /// /// Executes the native command once all of the input has been gathered. @@ -1459,12 +1459,12 @@ internal class ProcessOutputHandler internal const string XmlCliTag = "#< CLIXML"; private int _refCount; - private BlockingCollection _queue; + private readonly BlockingCollection _queue; private bool _isFirstOutput; private bool _isFirstError; private bool _isXmlCliOutput; private bool _isXmlCliError; - private string _processFileName; + private readonly string _processFileName; public ProcessOutputHandler(Process process, BlockingCollection queue) { @@ -1705,7 +1705,7 @@ internal class ProcessInputWriter { #region constructor - private InternalCommand _command; + private readonly InternalCommand _command; /// /// Creates an instance of ProcessInputWriter. /// @@ -2138,9 +2138,9 @@ protected RemoteException(SerializationInfo info, StreamingContext context) #endregion [NonSerialized] - private PSObject _serializedRemoteException; + private readonly PSObject _serializedRemoteException; [NonSerialized] - private PSObject _serializedRemoteInvocationInfo; + private readonly PSObject _serializedRemoteInvocationInfo; /// /// Original Serialized Exception from remote msh. diff --git a/src/System.Management.Automation/engine/PSClassSearcher.cs b/src/System.Management.Automation/engine/PSClassSearcher.cs index 613035820d0..82c96c8a350 100644 --- a/src/System.Management.Automation/engine/PSClassSearcher.cs +++ b/src/System.Management.Automation/engine/PSClassSearcher.cs @@ -33,14 +33,14 @@ internal PSClassSearcher( #region private properties - private string _className = null; - private ExecutionContext _context = null; + private readonly string _className = null; + private readonly ExecutionContext _context = null; private PSClassInfo _currentMatch = null; private IEnumerator _matchingClass = null; private Collection _matchingClassList = null; - private bool _useWildCards = false; - private Dictionary _moduleInfoCache = null; - private object _lockObject = new object(); + private readonly bool _useWildCards = false; + private readonly Dictionary _moduleInfoCache = null; + private readonly object _lockObject = new object(); #endregion diff --git a/src/System.Management.Automation/engine/ParameterBinderBase.cs b/src/System.Management.Automation/engine/ParameterBinderBase.cs index e50395003fe..4a9accdfa9b 100644 --- a/src/System.Management.Automation/engine/ParameterBinderBase.cs +++ b/src/System.Management.Automation/engine/ParameterBinderBase.cs @@ -58,7 +58,7 @@ internal abstract class ParameterBinderBase { #region tracer [TraceSource("ParameterBinderBase", "A abstract helper class for the CommandProcessor that binds parameters to the specified object.")] - private static PSTraceSource s_tracer = PSTraceSource.GetTracer("ParameterBinderBase", "A abstract helper class for the CommandProcessor that binds parameters to the specified object."); + private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("ParameterBinderBase", "A abstract helper class for the CommandProcessor that binds parameters to the specified object."); [TraceSource("ParameterBinding", "Traces the process of binding the arguments to the parameters of cmdlets, scripts, and applications.")] internal static PSTraceSource bindingTracer = @@ -903,7 +903,7 @@ private bool ShouldContinueUncoercedBind( /// /// The invocation information for the code that is being bound. /// - private InvocationInfo _invocationInfo; + private readonly InvocationInfo _invocationInfo; internal InvocationInfo InvocationInfo { get @@ -915,7 +915,7 @@ internal InvocationInfo InvocationInfo /// /// The context of the currently running engine. /// - private ExecutionContext _context; + private readonly ExecutionContext _context; internal ExecutionContext Context { get @@ -927,7 +927,7 @@ internal ExecutionContext Context /// /// An instance of InternalCommand that the binder is binding to. /// - private InternalCommand _command; + private readonly InternalCommand _command; internal InternalCommand Command { get @@ -939,9 +939,9 @@ internal InternalCommand Command /// /// The engine APIs that need to be passed the attributes when evaluated. /// - private EngineIntrinsics _engine; + private readonly EngineIntrinsics _engine; - private bool _isTranscribing; + private readonly bool _isTranscribing; #endregion internal members diff --git a/src/System.Management.Automation/engine/ParameterSetSpecificMetadata.cs b/src/System.Management.Automation/engine/ParameterSetSpecificMetadata.cs index 7ffba7fd0dd..8eaa769afc6 100644 --- a/src/System.Management.Automation/engine/ParameterSetSpecificMetadata.cs +++ b/src/System.Management.Automation/engine/ParameterSetSpecificMetadata.cs @@ -209,7 +209,7 @@ internal string GetHelpMessage(Cmdlet cmdlet) return helpInfo; } - private ParameterAttribute _attribute; + private readonly ParameterAttribute _attribute; } } diff --git a/src/System.Management.Automation/engine/PathInterfaces.cs b/src/System.Management.Automation/engine/PathInterfaces.cs index 342aec3cba0..a05d06b5beb 100644 --- a/src/System.Management.Automation/engine/PathInterfaces.cs +++ b/src/System.Management.Automation/engine/PathInterfaces.cs @@ -1407,7 +1407,7 @@ private LocationGlobber PathResolver } private LocationGlobber _pathResolver; - private SessionStateInternal _sessionState; + private readonly SessionStateInternal _sessionState; #endregion private data } diff --git a/src/System.Management.Automation/engine/Pipe.cs b/src/System.Management.Automation/engine/Pipe.cs index ac9350487a0..c60ae52c9fa 100644 --- a/src/System.Management.Automation/engine/Pipe.cs +++ b/src/System.Management.Automation/engine/Pipe.cs @@ -28,7 +28,7 @@ internal enum VariableStreamKind /// internal class Pipe { - private ExecutionContext _context; + private readonly ExecutionContext _context; // If a pipeline object has been added, then // write objects to it, stepping one at a time... @@ -349,7 +349,7 @@ internal Pipe(System.Collections.ObjectModel.Collection resultCollecti _resultCollection = resultCollection; } - private System.Collections.ObjectModel.Collection _resultCollection; + private readonly System.Collections.ObjectModel.Collection _resultCollection; /// /// This pipe writes into another pipeline processor allowing @@ -380,7 +380,7 @@ internal Pipe(IEnumerator enumeratorToProcess) _enumeratorToProcessIsEmpty = false; } - private IEnumerator _enumeratorToProcess; + private readonly IEnumerator _enumeratorToProcess; private bool _enumeratorToProcessIsEmpty; #endregion ctor diff --git a/src/System.Management.Automation/engine/ProgressRecord.cs b/src/System.Management.Automation/engine/ProgressRecord.cs index 086815105ef..c3b63cd48e4 100644 --- a/src/System.Management.Automation/engine/ProgressRecord.cs +++ b/src/System.Management.Automation/engine/ProgressRecord.cs @@ -429,7 +429,7 @@ internal static int GetPercentageComplete(DateTime startTime, TimeSpan expectedD #region DO NOT REMOVE OR RENAME THESE FIELDS - it will break remoting compatibility with Windows PowerShell [DataMemberAttribute()] - private int id; + private readonly int id; [DataMemberAttribute()] private int parentId = -1; diff --git a/src/System.Management.Automation/engine/PropertyCmdletProviderInterfaces.cs b/src/System.Management.Automation/engine/PropertyCmdletProviderInterfaces.cs index e249a2b7d0c..0d8a72f20f2 100644 --- a/src/System.Management.Automation/engine/PropertyCmdletProviderInterfaces.cs +++ b/src/System.Management.Automation/engine/PropertyCmdletProviderInterfaces.cs @@ -1824,8 +1824,8 @@ internal object MovePropertyDynamicParameters( #region private data - private Cmdlet _cmdlet; - private SessionStateInternal _sessionState; + private readonly Cmdlet _cmdlet; + private readonly SessionStateInternal _sessionState; #endregion private data } diff --git a/src/System.Management.Automation/engine/ProviderInterfaces.cs b/src/System.Management.Automation/engine/ProviderInterfaces.cs index c74b1336184..018dacc54b3 100644 --- a/src/System.Management.Automation/engine/ProviderInterfaces.cs +++ b/src/System.Management.Automation/engine/ProviderInterfaces.cs @@ -160,7 +160,7 @@ internal int Count #region private data - private SessionStateInternal _sessionState; + private readonly SessionStateInternal _sessionState; #endregion private data } diff --git a/src/System.Management.Automation/engine/ScopedItemSearcher.cs b/src/System.Management.Automation/engine/ScopedItemSearcher.cs index 27710417123..e214a6681f3 100644 --- a/src/System.Management.Automation/engine/ScopedItemSearcher.cs +++ b/src/System.Management.Automation/engine/ScopedItemSearcher.cs @@ -231,7 +231,7 @@ private void InitializeScopeEnumerator() private T _current; protected SessionStateInternal sessionState; - private VariablePath _lookupPath; + private readonly VariablePath _lookupPath; private SessionStateScopeEnumerator _scopeEnumerable; private bool _isSingleScopeLookup; private bool _isInitialized; diff --git a/src/System.Management.Automation/engine/SecurityDescriptorCmdletProviderInterfaces.cs b/src/System.Management.Automation/engine/SecurityDescriptorCmdletProviderInterfaces.cs index 404eb940b0b..d71464df4ed 100644 --- a/src/System.Management.Automation/engine/SecurityDescriptorCmdletProviderInterfaces.cs +++ b/src/System.Management.Automation/engine/SecurityDescriptorCmdletProviderInterfaces.cs @@ -239,8 +239,8 @@ public ObjectSecurity NewOfType(string providerId, string type, AccessControlSec #region private data - private Cmdlet _cmdlet; - private SessionStateInternal _sessionState; + private readonly Cmdlet _cmdlet; + private readonly SessionStateInternal _sessionState; #endregion private data } diff --git a/src/System.Management.Automation/engine/SecurityManagerBase.cs b/src/System.Management.Automation/engine/SecurityManagerBase.cs index 3cb4c9e7a70..a247c65ed30 100644 --- a/src/System.Management.Automation/engine/SecurityManagerBase.cs +++ b/src/System.Management.Automation/engine/SecurityManagerBase.cs @@ -55,7 +55,7 @@ public AuthorizationManager(string shellId) #endregion constructor - private object _policyCheckLock = new object(); + private readonly object _policyCheckLock = new object(); #region methods to use internally diff --git a/src/System.Management.Automation/engine/SessionState.cs b/src/System.Management.Automation/engine/SessionState.cs index 3b3f606e79f..30bea1d39fe 100644 --- a/src/System.Management.Automation/engine/SessionState.cs +++ b/src/System.Management.Automation/engine/SessionState.cs @@ -31,7 +31,7 @@ internal sealed partial class SessionStateInternal [Dbg.TraceSourceAttribute( "SessionState", "SessionState Class")] - private static Dbg.PSTraceSource s_tracer = + private static readonly Dbg.PSTraceSource s_tracer = Dbg.PSTraceSource.GetTracer("SessionState", "SessionState Class"); diff --git a/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs b/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs index abc6b867ae5..5be9dd37528 100644 --- a/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs @@ -251,7 +251,7 @@ private static bool IsValidDriveName(string name) return result; } - private static char[] s_charactersInvalidInDriveName = new char[] { ':', '/', '\\', '.', '~' }; + private static readonly char[] s_charactersInvalidInDriveName = new char[] { ':', '/', '\\', '.', '~' }; /// /// Tries to resolve the drive root as an MSH path. If it successfully resolves diff --git a/src/System.Management.Automation/engine/SessionStateLocationAPIs.cs b/src/System.Management.Automation/engine/SessionStateLocationAPIs.cs index 591c20f184a..1ca2528157b 100644 --- a/src/System.Management.Automation/engine/SessionStateLocationAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateLocationAPIs.cs @@ -799,7 +799,7 @@ CmdletProviderContext normalizePathContext /// /// A stack of the most recently pushed locations. /// - private Dictionary> _workingLocationStack; + private readonly Dictionary> _workingLocationStack; private const string startingDefaultStackName = "default"; /// diff --git a/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs b/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs index 61d21413604..43da43bcfbb 100644 --- a/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs @@ -52,7 +52,7 @@ internal Dictionary ProvidersCurrentWorkingDrive } } - private Dictionary _providersCurrentWorkingDrive = new Dictionary(); + private readonly Dictionary _providersCurrentWorkingDrive = new Dictionary(); /// /// Entrypoint used by to add a provider to the current session state diff --git a/src/System.Management.Automation/engine/SessionStatePublic.cs b/src/System.Management.Automation/engine/SessionStatePublic.cs index de23eff9479..901f5adee90 100644 --- a/src/System.Management.Automation/engine/SessionStatePublic.cs +++ b/src/System.Management.Automation/engine/SessionStatePublic.cs @@ -311,7 +311,7 @@ internal SessionStateInternal Internal #region private data - private SessionStateInternal _sessionState; + private readonly SessionStateInternal _sessionState; private DriveManagementIntrinsics _drive; private CmdletProviderManagementIntrinsics _provider; private PathIntrinsics _path; diff --git a/src/System.Management.Automation/engine/SessionStateScope.cs b/src/System.Management.Automation/engine/SessionStateScope.cs index aac49ab5a4c..f42019f9e8b 100644 --- a/src/System.Management.Automation/engine/SessionStateScope.cs +++ b/src/System.Management.Automation/engine/SessionStateScope.cs @@ -1890,7 +1890,7 @@ private Dictionary GetAllScopeFunctions() #region Alias mapping - private Dictionary> _commandsToAliasesCache = new Dictionary>(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary> _commandsToAliasesCache = new Dictionary>(StringComparer.OrdinalIgnoreCase); /// /// Gets the aliases by command name (used by metadata-driven help) diff --git a/src/System.Management.Automation/engine/ThirdPartyAdapter.cs b/src/System.Management.Automation/engine/ThirdPartyAdapter.cs index 75e958693d9..331c125a042 100644 --- a/src/System.Management.Automation/engine/ThirdPartyAdapter.cs +++ b/src/System.Management.Automation/engine/ThirdPartyAdapter.cs @@ -279,7 +279,7 @@ protected override string PropertyType(PSProperty property, bool forDisplay) return propertyTypeName ?? "System.Object"; } - private PSPropertyAdapter _externalAdapter; + private readonly PSPropertyAdapter _externalAdapter; } /// diff --git a/src/System.Management.Automation/engine/TypeMetadata.cs b/src/System.Management.Automation/engine/TypeMetadata.cs index 76f22734f8a..4616de29eff 100644 --- a/src/System.Management.Automation/engine/TypeMetadata.cs +++ b/src/System.Management.Automation/engine/TypeMetadata.cs @@ -1274,7 +1274,7 @@ internal InternalParameterMetadata(Type type, bool processingDynamicParameters) /// This member is null in all cases except when constructed with using reflection /// against the Type. /// - private Type _type; + private readonly Type _type; /// /// The flags used when reflecting against the object to create the metadata. @@ -1544,7 +1544,7 @@ private static bool IsMemberAParameter(MemberInfo member) /// The cache of the type metadata. The key for the cache is the Type.FullName. /// Note, this is a case-sensitive dictionary because Type names are case sensitive. /// - private static System.Collections.Concurrent.ConcurrentDictionary s_parameterMetadataCache = + private static readonly System.Collections.Concurrent.ConcurrentDictionary s_parameterMetadataCache = new System.Collections.Concurrent.ConcurrentDictionary(StringComparer.Ordinal); #endregion Metadata cache diff --git a/src/System.Management.Automation/engine/TypeTable.cs b/src/System.Management.Automation/engine/TypeTable.cs index c6d52a7ff1b..69fcfed470a 100644 --- a/src/System.Management.Automation/engine/TypeTable.cs +++ b/src/System.Management.Automation/engine/TypeTable.cs @@ -1752,7 +1752,7 @@ internal void AddError(string typeName, int errorLineNumber, string resourceStri [Serializable] public class TypeTableLoadException : RuntimeException { - private Collection _errors; + private readonly Collection _errors; #region Constructors diff --git a/src/System.Management.Automation/engine/UserFeedbackParameters.cs b/src/System.Management.Automation/engine/UserFeedbackParameters.cs index e74e309b3b1..277436b26d7 100644 --- a/src/System.Management.Automation/engine/UserFeedbackParameters.cs +++ b/src/System.Management.Automation/engine/UserFeedbackParameters.cs @@ -162,7 +162,7 @@ public SwitchParameter Confirm } #endregion parameters - private MshCommandRuntime _commandRuntime; + private readonly MshCommandRuntime _commandRuntime; } /// @@ -208,7 +208,7 @@ public SwitchParameter UseTransaction #endregion parameters - private MshCommandRuntime _commandRuntime; + private readonly MshCommandRuntime _commandRuntime; } } diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index a188a091e34..1a5dcd2bf2b 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -2228,7 +2228,7 @@ internal T Pop() /// internal sealed class ReadOnlyBag : IEnumerable { - private HashSet _hashset; + private readonly HashSet _hashset; /// /// Constructor for the readonly Hashset. diff --git a/src/System.Management.Automation/engine/VariableAttributeCollection.cs b/src/System.Management.Automation/engine/VariableAttributeCollection.cs index 918b040a0f6..0f4e1e72b87 100644 --- a/src/System.Management.Automation/engine/VariableAttributeCollection.cs +++ b/src/System.Management.Automation/engine/VariableAttributeCollection.cs @@ -154,7 +154,7 @@ private object VerifyNewAttribute(Attribute item) /// The variable whose value needs to be verified anytime /// the attributes change. /// - private PSVariable _variable; + private readonly PSVariable _variable; #endregion private data } } diff --git a/src/System.Management.Automation/engine/VariableInterfaces.cs b/src/System.Management.Automation/engine/VariableInterfaces.cs index 60d23f9e12a..eea116c3e85 100644 --- a/src/System.Management.Automation/engine/VariableInterfaces.cs +++ b/src/System.Management.Automation/engine/VariableInterfaces.cs @@ -441,7 +441,7 @@ internal void RemoveAtScope(PSVariable variable, string scope) #region private data - private SessionStateInternal _sessionState; + private readonly SessionStateInternal _sessionState; #endregion private data } diff --git a/src/System.Management.Automation/engine/cmdlet.cs b/src/System.Management.Automation/engine/cmdlet.cs index 4a330b34ed0..dfb8326e687 100644 --- a/src/System.Management.Automation/engine/cmdlet.cs +++ b/src/System.Management.Automation/engine/cmdlet.cs @@ -46,7 +46,7 @@ public static HashSet CommonParameters } } - private static Lazy> s_commonParameters = new Lazy>( + private static readonly Lazy> s_commonParameters = new Lazy>( () => { return new HashSet(StringComparer.OrdinalIgnoreCase) { @@ -68,7 +68,7 @@ public static HashSet OptionalCommonParameters } } - private static Lazy> s_optionalCommonParameters = new Lazy>( + private static readonly Lazy> s_optionalCommonParameters = new Lazy>( () => { return new HashSet(StringComparer.OrdinalIgnoreCase) { diff --git a/src/System.Management.Automation/engine/debugger/debugger.cs b/src/System.Management.Automation/engine/debugger/debugger.cs index ab715b053ff..0f23a2bba6f 100644 --- a/src/System.Management.Automation/engine/debugger/debugger.cs +++ b/src/System.Management.Automation/engine/debugger/debugger.cs @@ -1709,27 +1709,27 @@ internal void Clear() // Job debugger integration. private bool _nestedDebuggerStop; - private Dictionary _runningJobs; - private ConcurrentStack _activeDebuggers; - private ConcurrentStack _debuggerStopEventArgs; + private readonly Dictionary _runningJobs; + private readonly ConcurrentStack _activeDebuggers; + private readonly ConcurrentStack _debuggerStopEventArgs; private DebuggerResumeAction _lastActiveDebuggerAction; private DebuggerResumeAction _currentDebuggerAction; private DebuggerResumeAction _previousDebuggerAction; private CallStackInfo _nestedRunningFrame; - private object _syncObject; - private object _syncActiveDebuggerStopObject; + private readonly object _syncObject; + private readonly object _syncActiveDebuggerStopObject; private int _processingOutputCount; private ManualResetEventSlim _processingOutputCompleteEvent = new ManualResetEventSlim(true); // Runspace debugger integration. - private Dictionary _runningRunspaces; + private readonly Dictionary _runningRunspaces; private const int _jobCallStackOffset = 2; private const int _runspaceCallStackOffset = 1; private bool _preserveUnhandledDebugStopEvent; private ManualResetEventSlim _preserveDebugStopEvent; // Process runspace debugger - private Lazy> _runspaceDebugQueue = new Lazy>(); + private readonly Lazy> _runspaceDebugQueue = new Lazy>(); private volatile int _processingRunspaceDebugQueue; private ManualResetEventSlim _runspaceDebugCompleteEvent; @@ -5077,13 +5077,13 @@ internal class DebuggerCommandProcessor private const int DefaultListLineCount = 16; // table of debugger commands - private Dictionary _commandTable; + private readonly Dictionary _commandTable; // the Help command - private DebuggerCommand _helpCommand; + private readonly DebuggerCommand _helpCommand; // the List command - private DebuggerCommand _listCommand; + private readonly DebuggerCommand _listCommand; // last command processed private DebuggerCommand _lastCommand; @@ -5663,7 +5663,7 @@ namespace System.Management.Automation.Internal [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes", Justification = "Needed Internal use only")] public static class DebuggerUtils { - private static SortedSet s_noHistoryCommandNames = new SortedSet(StringComparer.OrdinalIgnoreCase) + private static readonly SortedSet s_noHistoryCommandNames = new SortedSet(StringComparer.OrdinalIgnoreCase) { "prompt", "Set-PSDebuggerAction", diff --git a/src/System.Management.Automation/engine/hostifaces/Command.cs b/src/System.Management.Automation/engine/hostifaces/Command.cs index 08f323d809a..4dee709ad30 100644 --- a/src/System.Management.Automation/engine/hostifaces/Command.cs +++ b/src/System.Management.Automation/engine/hostifaces/Command.cs @@ -568,7 +568,7 @@ CommandOrigin origin /// property is bool, not bool? (from V1), so it should probably /// be deprecated, at least for internal use. /// - private bool? _useLocalScope; + private readonly bool? _useLocalScope; #endregion Private fields diff --git a/src/System.Management.Automation/engine/hostifaces/Connection.cs b/src/System.Management.Automation/engine/hostifaces/Connection.cs index 89d04fa515b..cdcdc1458bd 100644 --- a/src/System.Management.Automation/engine/hostifaces/Connection.cs +++ b/src/System.Management.Automation/engine/hostifaces/Connection.cs @@ -450,9 +450,9 @@ public abstract class Runspace : IDisposable #region Private Data private static int s_globalId; - private Stack _runningPowerShells; + private readonly Stack _runningPowerShells; private PowerShell _baseRunningPowerShell; - private object _syncObject; + private readonly object _syncObject; #endregion @@ -805,8 +805,8 @@ internal static ReadOnlyDictionary> RunspaceDiction } } - private static SortedDictionary> s_runspaceDictionary; - private static object s_syncObject; + private static readonly SortedDictionary> s_runspaceDictionary; + private static readonly object s_syncObject; /// /// Returns a read only list of runspaces. @@ -1671,7 +1671,7 @@ internal SessionStateProxy() { } - private RunspaceBase _runspace; + private readonly RunspaceBase _runspace; internal SessionStateProxy(RunspaceBase runspace) { Dbg.Assert(runspace != null, "Caller should validate the parameter"); diff --git a/src/System.Management.Automation/engine/hostifaces/History.cs b/src/System.Management.Automation/engine/hostifaces/History.cs index b6138df546c..3737a5ff0e1 100644 --- a/src/System.Management.Automation/engine/hostifaces/History.cs +++ b/src/System.Management.Automation/engine/hostifaces/History.cs @@ -139,7 +139,7 @@ public override string ToString() /// /// Id of the pipeline corresponding to this history entry. /// - private long _pipelineId; + private readonly long _pipelineId; /// @@ -808,7 +808,7 @@ private int GetHistorySize() /// /// Private object for synchronization. /// - private object _syncRoot = new object(); + private readonly object _syncRoot = new object(); #endregion private diff --git a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs index 66f0d841bfb..9f33110eef4 100644 --- a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs +++ b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs @@ -42,7 +42,7 @@ public static class HostUtilities { #region Internal Access - private static string s_checkForCommandInCurrentDirectoryScript = @" + private static readonly string s_checkForCommandInCurrentDirectoryScript = @" [System.Diagnostics.DebuggerHidden()] param() @@ -58,21 +58,21 @@ public static class HostUtilities $foundSuggestion "; - private static string s_createCommandExistsInCurrentDirectoryScript = @" + private static readonly string s_createCommandExistsInCurrentDirectoryScript = @" [System.Diagnostics.DebuggerHidden()] param([string] $formatString) $formatString -f $lastError.TargetObject,"".\$($lastError.TargetObject)"" "; - private static string s_getFuzzyMatchedCommands = @" + private static readonly string s_getFuzzyMatchedCommands = @" [System.Diagnostics.DebuggerHidden()] param([string] $formatString) $formatString -f [string]::Join(', ', (Get-Command $lastError.TargetObject -UseFuzzyMatch | Select-Object -First 10 -Unique -ExpandProperty Name)) "; - private static List s_suggestions = InitializeSuggestions(); + private static readonly List s_suggestions = InitializeSuggestions(); private static List InitializeSuggestions() { diff --git a/src/System.Management.Automation/engine/hostifaces/InformationalRecord.cs b/src/System.Management.Automation/engine/hostifaces/InformationalRecord.cs index c8d997d0808..7db9ecfc3b1 100644 --- a/src/System.Management.Automation/engine/hostifaces/InformationalRecord.cs +++ b/src/System.Management.Automation/engine/hostifaces/InformationalRecord.cs @@ -216,7 +216,7 @@ public string FullyQualifiedWarningId } } - private string _fullyQualifiedWarningId; + private readonly string _fullyQualifiedWarningId; } /// diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHost.cs b/src/System.Management.Automation/engine/hostifaces/InternalHost.cs index e170a3792e4..724b975e516 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHost.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHost.cs @@ -565,14 +565,14 @@ internal PSHost ExternalHost internal int NestedPromptCount { get; private set; } // Masked variables. - private ObjectRef _externalHostRef; - private ObjectRef _internalUIRef; + private readonly ObjectRef _externalHostRef; + private readonly ObjectRef _internalUIRef; // Private variables. private string _nameResult; private Version _versionResult; private Guid _idResult; - private Stack _contextStack = new Stack(); + private readonly Stack _contextStack = new Stack(); private readonly Guid _zeroGuid; } diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHostRawUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/InternalHostRawUserInterface.cs index d182ef6302a..1e8f9f78311 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHostRawUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHostRawUserInterface.cs @@ -624,7 +624,7 @@ public override return _externalRawUI.LengthInBufferCells(character); } - private PSHostRawUserInterface _externalRawUI; - private InternalHost _parentHost; + private readonly PSHostRawUserInterface _externalRawUI; + private readonly InternalHost _parentHost; } } diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs index f0185900bbb..9a6e3d2e68c 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs @@ -1035,9 +1035,9 @@ private Collection EmulatePromptForMultipleChoice(string caption, return result; } - private PSHostUserInterface _externalUI = null; - private InternalHostRawUserInterface _internalRawUI = null; - private InternalHost _parent = null; + private readonly PSHostUserInterface _externalUI = null; + private readonly InternalHostRawUserInterface _internalRawUI = null; + private readonly InternalHost _parent = null; private PSInformationalBuffers _informationalBuffers = null; } } diff --git a/src/System.Management.Automation/engine/hostifaces/ListModifier.cs b/src/System.Management.Automation/engine/hostifaces/ListModifier.cs index bc25d928ef3..797beef7041 100644 --- a/src/System.Management.Automation/engine/hostifaces/ListModifier.cs +++ b/src/System.Management.Automation/engine/hostifaces/ListModifier.cs @@ -151,7 +151,7 @@ public Collection Add get { return _itemsToAdd; } } - private Collection _itemsToAdd; + private readonly Collection _itemsToAdd; /// /// The list of items to remove when AppyTo is called. @@ -161,7 +161,7 @@ public Collection Remove get { return _itemsToRemove; } } - private Collection _itemsToRemove; + private readonly Collection _itemsToRemove; /// /// The list of items to replace an existing list with. @@ -171,7 +171,7 @@ public Collection Replace get { return _replacementItems; } } - private Collection _replacementItems; + private readonly Collection _replacementItems; /// /// Update the given collection with the items in Add and Remove. diff --git a/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs b/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs index f924985fb5c..5411955afde 100644 --- a/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs +++ b/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs @@ -363,8 +363,8 @@ public override Debugger Debugger } } - private static string s_debugPreferenceCachePath = Path.Combine(Path.Combine(Platform.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "WindowsPowerShell"), "DebugPreference.clixml"); - private static object s_debugPreferenceLockObject = new object(); + private static readonly string s_debugPreferenceCachePath = Path.Combine(Path.Combine(Platform.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "WindowsPowerShell"), "DebugPreference.clixml"); + private static readonly object s_debugPreferenceLockObject = new object(); /// /// DebugPreference serves as a property bag to keep @@ -1312,14 +1312,13 @@ internal AutomationEngine Engine private History _history; [TraceSource("RunspaceInit", "Initialization code for Runspace")] - private static - PSTraceSource s_runspaceInitTracer = + private static readonly PSTraceSource s_runspaceInitTracer = PSTraceSource.GetTracer("RunspaceInit", "Initialization code for Runspace", false); /// /// This ensures all processes have a server/listener. /// - private static RemoteSessionNamedPipeServer s_IPCNamedPipeServer = RemoteSessionNamedPipeServer.IPCNamedPipeServer; + private static readonly RemoteSessionNamedPipeServer s_IPCNamedPipeServer = RemoteSessionNamedPipeServer.IPCNamedPipeServer; #endregion private fields } @@ -1331,7 +1330,7 @@ private static /// internal sealed class StopJobOperationHelper : IThrottleOperation { - private Job _job; + private readonly Job _job; /// /// Internal constructor. @@ -1408,7 +1407,7 @@ private void RaiseOperationCompleteEvent() /// internal sealed class CloseOrDisconnectRunspaceOperationHelper : IThrottleOperation { - private RemoteRunspace _remoteRunspace; + private readonly RemoteRunspace _remoteRunspace; /// /// Internal constructor. @@ -1569,7 +1568,7 @@ public PSDataCollection ErrorRecords get { return _errors; } } - private PSDataCollection _errors; + private readonly PSDataCollection _errors; #region Serialization /// diff --git a/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs b/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs index 48ab16c579a..96fe32380e9 100644 --- a/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs +++ b/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs @@ -760,7 +760,7 @@ private void StopThreadProc() StopHelper(); } - private PipelineStopper _stopper; + private readonly PipelineStopper _stopper; /// /// Gets PipelineStopper object which maintains stack of PipelineProcessor @@ -1120,7 +1120,7 @@ private LocalRunspace LocalRunspace /// This is list of HistoryInfo ids which have been executed in /// this pipeline. /// - private List _invokeHistoryIds = new List(); + private readonly List _invokeHistoryIds = new List(); internal bool PresentInInvokeHistoryEntryList(HistoryInfo entry) { @@ -1283,9 +1283,9 @@ public void Dispose() Dispose(); } - private Thread _worker; + private readonly Thread _worker; private ThreadStart _workItem; - private AutoResetEvent _workItemReady; + private readonly AutoResetEvent _workItemReady; private bool _closed; } @@ -1300,13 +1300,13 @@ internal class PipelineStopper /// /// Stack of current executing pipeline processor. /// - private Stack _stack = new Stack(); + private readonly Stack _stack = new Stack(); /// /// Object used for synchronization. /// - private object _syncRoot = new object(); - private LocalPipeline _localPipeline; + private readonly object _syncRoot = new object(); + private readonly LocalPipeline _localPipeline; /// /// Default constructor. diff --git a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs index 1f3b857af21..5e8b5aa9a56 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs @@ -395,7 +395,7 @@ internal void IgnoreCommand(string commandText, InvocationInfo invocation) internal IDisposable SetTranscribeOnly() => new TranscribeOnlyCookie(this); private sealed class TranscribeOnlyCookie : IDisposable { - private PSHostUserInterface _ui; + private readonly PSHostUserInterface _ui; private bool _disposed = false; public TranscribeOnlyCookie(PSHostUserInterface ui) { @@ -949,8 +949,8 @@ internal static TranscriptionOption GetSystemTranscriptOption(TranscriptionOptio } internal static TranscriptionOption systemTranscript = null; - private static object s_systemTranscriptLock = new object(); - private static Lazy s_transcriptionSettingCache = new Lazy( + private static readonly object s_systemTranscriptLock = new object(); + private static readonly Lazy s_transcriptionSettingCache = new Lazy( () => Utils.GetPolicySetting(Utils.SystemWideThenCurrentUserConfig), isThreadSafe: true); diff --git a/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs b/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs index 5d6fc8578ca..dc154c567be 100644 --- a/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs +++ b/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs @@ -121,7 +121,7 @@ public class PSDataCollection : IList, ICollection, IEnumerable, ILi { #region Private Data - private IList _data; + private readonly IList _data; private ManualResetEvent _readWaitHandle; private bool _isOpen = true; private bool _releaseOnEnumeration; @@ -1843,8 +1843,8 @@ internal sealed class PSDataCollectionEnumerator : IBlockingEnumerator private W _currentElement; private int _index; - private PSDataCollection _collToEnumerate; - private bool _neverBlock; + private readonly PSDataCollection _collToEnumerate; + private readonly bool _neverBlock; #endregion diff --git a/src/System.Management.Automation/engine/hostifaces/Pipeline.cs b/src/System.Management.Automation/engine/hostifaces/Pipeline.cs index 7c20c17f194..84ccfa310cc 100644 --- a/src/System.Management.Automation/engine/hostifaces/Pipeline.cs +++ b/src/System.Management.Automation/engine/hostifaces/Pipeline.cs @@ -113,13 +113,13 @@ public PipelineState ExpectedState /// State of pipeline when exception was thrown. /// [NonSerialized] - private PipelineState _currentState = 0; + private readonly PipelineState _currentState = 0; /// /// States of the pipeline expected in method which throws this exception. /// [NonSerialized] - private PipelineState _expectedState = 0; + private readonly PipelineState _expectedState = 0; } #endregion Exceptions diff --git a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs index 0bb95d30d55..a92de93c204 100644 --- a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs +++ b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs @@ -120,7 +120,7 @@ public PSInvocationState CurrentState /// State of powershell when exception was thrown. /// [NonSerialized] - private PSInvocationState _currState = 0; + private readonly PSInvocationState _currState = 0; } #endregion @@ -263,12 +263,12 @@ internal PSInvocationStateInfo Clone() /// /// The current execution state. /// - private PSInvocationState _executionState; + private readonly PSInvocationState _executionState; /// /// Non-null exception if the execution state change was due to an error. /// - private Exception _exceptionReason; + private readonly Exception _exceptionReason; #endregion } @@ -419,7 +419,7 @@ public bool ExposeFlowControlExceptions /// internal class BatchInvocationContext { - private AutoResetEvent _completionEvent; + private readonly AutoResetEvent _completionEvent; /// /// Class constructor. @@ -589,7 +589,7 @@ public sealed class PowerShell : IDisposable private PSDataCollection _errorBuffer; private bool _isDisposed; - private object _syncObject = new object(); + private readonly object _syncObject = new object(); // client remote powershell if the powershell // is executed with a remote runspace pool @@ -5315,13 +5315,13 @@ private RemoteRunspacePoolInternal GetRemoteRunspacePoolInternal() /// private sealed class Worker { - private ObjectStreamBase _inputStream; - private ObjectStreamBase _outputStream; - private ObjectStreamBase _errorStream; - private PSInvocationSettings _settings; + private readonly ObjectStreamBase _inputStream; + private readonly ObjectStreamBase _outputStream; + private readonly ObjectStreamBase _errorStream; + private readonly PSInvocationSettings _settings; private bool _isNotActive; - private PowerShell _shell; - private object _syncObject = new object(); + private readonly PowerShell _shell; + private readonly object _syncObject = new object(); /// /// @@ -6126,7 +6126,7 @@ public void ClearStreams() this.Warning.Clear(); } - private PowerShell _powershell; + private readonly PowerShell _powershell; } /// @@ -6145,8 +6145,8 @@ public void ClearStreams() /// internal class PowerShellStopper : IDisposable { - private PipelineBase _pipeline; - private PowerShell _powerShell; + private readonly PipelineBase _pipeline; + private readonly PowerShell _powerShell; private EventHandler _eventHandler; internal PowerShellStopper(ExecutionContext context, PowerShell powerShell) diff --git a/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs b/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs index 58268db59e5..f5383743c48 100644 --- a/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs +++ b/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs @@ -182,13 +182,13 @@ private static RunspaceState RunspacePoolStateToRunspaceState(RunspacePoolState /// State of the runspace pool when exception was thrown. /// [NonSerialized] - private RunspacePoolState _currentState = 0; + private readonly RunspacePoolState _currentState = 0; /// /// State of the runspace pool expected in method which throws this exception. /// [NonSerialized] - private RunspacePoolState _expectedState = 0; + private readonly RunspacePoolState _expectedState = 0; } #endregion @@ -504,8 +504,8 @@ public sealed class RunspacePool : IDisposable { #region Private Data - private RunspacePoolInternal _internalPool; - private object _syncObject = new object(); + private readonly RunspacePoolInternal _internalPool; + private readonly object _syncObject = new object(); private event EventHandler InternalStateChanged = null; private event EventHandler InternalForwardEvent = null; private event EventHandler InternalRunspaceCreated = null; diff --git a/src/System.Management.Automation/engine/hostifaces/RunspacePoolInternal.cs b/src/System.Management.Automation/engine/hostifaces/RunspacePoolInternal.cs index 49950ac0fa1..9e8e6e32f05 100644 --- a/src/System.Management.Automation/engine/hostifaces/RunspacePoolInternal.cs +++ b/src/System.Management.Automation/engine/hostifaces/RunspacePoolInternal.cs @@ -40,7 +40,7 @@ internal class RunspacePoolInternal private static readonly TimeSpan s_defaultCleanupPeriod = new TimeSpan(0, 15, 0); // 15 minutes. private TimeSpan _cleanupInterval; - private Timer _cleanupTimer; + private readonly Timer _cleanupTimer; #endregion diff --git a/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs b/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs index 1c2523874c1..aeb95c116f0 100644 --- a/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs +++ b/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs @@ -553,7 +553,7 @@ public override int Run(InterpretedFrame frame) /// internal sealed class LeaveExceptionHandlerInstruction : IndexedBranchInstruction { - private static LeaveExceptionHandlerInstruction[] s_cache = new LeaveExceptionHandlerInstruction[2 * CacheSize]; + private static readonly LeaveExceptionHandlerInstruction[] s_cache = new LeaveExceptionHandlerInstruction[2 * CacheSize]; private readonly bool _hasValue; diff --git a/src/System.Management.Automation/engine/interpreter/InstructionList.cs b/src/System.Management.Automation/engine/interpreter/InstructionList.cs index 9617c746359..79aca5b48ba 100644 --- a/src/System.Management.Automation/engine/interpreter/InstructionList.cs +++ b/src/System.Management.Automation/engine/interpreter/InstructionList.cs @@ -1063,7 +1063,7 @@ public void EmitDynamic> s_factories = + private static readonly Dictionary> s_factories = new Dictionary>(); internal static Instruction CreateDynamicInstruction(Type delegateType, CallSiteBinder binder) diff --git a/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs b/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs index 3e15b1fbba4..f0cd679a093 100644 --- a/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs +++ b/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs @@ -34,7 +34,7 @@ internal sealed class InterpretedFrame internal InterpretedFrame _parent; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly")] - private int[] _continuations; + private readonly int[] _continuations; private int _continuationIndex; private int _pendingContinuation; private object _pendingValue; diff --git a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs index e05965cb8ff..0ff4d6ff32b 100644 --- a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs +++ b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs @@ -288,7 +288,7 @@ internal sealed class LightCompiler private readonly LightCompiler _parent; - private static LocalDefinition[] s_emptyLocals = Array.Empty(); + private static readonly LocalDefinition[] s_emptyLocals = Array.Empty(); public LightCompiler(int compilationThreshold) { diff --git a/src/System.Management.Automation/engine/lang/interface/PSToken.cs b/src/System.Management.Automation/engine/lang/interface/PSToken.cs index b0b34ec0544..35f9d54ea36 100644 --- a/src/System.Management.Automation/engine/lang/interface/PSToken.cs +++ b/src/System.Management.Automation/engine/lang/interface/PSToken.cs @@ -68,7 +68,7 @@ public string Content } } - private string _content; + private readonly string _content; #region Token Type diff --git a/src/System.Management.Automation/engine/lang/parserutils.cs b/src/System.Management.Automation/engine/lang/parserutils.cs index 180a1fe0f69..c89d66282a4 100644 --- a/src/System.Management.Automation/engine/lang/parserutils.cs +++ b/src/System.Management.Automation/engine/lang/parserutils.cs @@ -1638,13 +1638,13 @@ internal static object CallMethod( /// internal class RangeEnumerator : IEnumerator { - private int _lowerBound; + private readonly int _lowerBound; internal int LowerBound { get { return _lowerBound; } } - private int _upperBound; + private readonly int _upperBound; internal int UpperBound { get { return _upperBound; } @@ -1667,7 +1667,7 @@ internal int CurrentValue get { return _current; } } - private int _increment = 1; + private readonly int _increment = 1; private bool _firstElement = true; @@ -1708,7 +1708,7 @@ public bool MoveNext() /// internal class CharRangeEnumerator : IEnumerator { - private int _increment = 1; + private readonly int _increment = 1; private bool _firstElement = true; diff --git a/src/System.Management.Automation/engine/lang/scriptblock.cs b/src/System.Management.Automation/engine/lang/scriptblock.cs index 539be28fe2d..4941ce11a3c 100644 --- a/src/System.Management.Automation/engine/lang/scriptblock.cs +++ b/src/System.Management.Automation/engine/lang/scriptblock.cs @@ -1114,8 +1114,8 @@ internal SteppablePipeline(ExecutionContext context, PipelineProcessor pipeline) _context = context; } - private PipelineProcessor _pipeline; - private ExecutionContext _context; + private readonly PipelineProcessor _pipeline; + private readonly ExecutionContext _context; private bool _expectInput; /// diff --git a/src/System.Management.Automation/engine/parser/PSType.cs b/src/System.Management.Automation/engine/parser/PSType.cs index 1feb951d7b4..3686767b434 100644 --- a/src/System.Management.Automation/engine/parser/PSType.cs +++ b/src/System.Management.Automation/engine/parser/PSType.cs @@ -1435,7 +1435,7 @@ private static string GetClassNameInAssembly(TypeDefinitionAst typeDefinitionAst return string.Join(".", nameParts); } - private static OpCode[] s_ldc = + private static readonly OpCode[] s_ldc = { OpCodes.Ldc_I4_0, OpCodes.Ldc_I4_1, OpCodes.Ldc_I4_2, OpCodes.Ldc_I4_3, OpCodes.Ldc_I4_4, OpCodes.Ldc_I4_5, OpCodes.Ldc_I4_6, OpCodes.Ldc_I4_7, OpCodes.Ldc_I4_8 @@ -1453,7 +1453,7 @@ private static void EmitLdc(ILGenerator emitter, int c) } } - private static OpCode[] s_ldarg = + private static readonly OpCode[] s_ldarg = { OpCodes.Ldarg_0, OpCodes.Ldarg_1, OpCodes.Ldarg_2, OpCodes.Ldarg_3 }; diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index f135fadfd54..e940f1d1461 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -2367,7 +2367,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) /// public class StatementBlockAst : Ast { - private static ReadOnlyCollection s_emptyStatementCollection = Utils.EmptyReadOnlyCollection(); + private static readonly ReadOnlyCollection s_emptyStatementCollection = Utils.EmptyReadOnlyCollection(); /// /// Construct a statement block. diff --git a/src/System.Management.Automation/engine/parser/tokenizer.cs b/src/System.Management.Automation/engine/parser/tokenizer.cs index 64cd02d4185..0f445b5974a 100644 --- a/src/System.Management.Automation/engine/parser/tokenizer.cs +++ b/src/System.Management.Automation/engine/parser/tokenizer.cs @@ -377,7 +377,7 @@ internal static bool IsCompatibleWithConfigurationType(this DynamicKeyword keywo (ConfigurationType != ConfigurationType.Meta && !keyword.IsMetaDSCResource())); } - private static Dictionary> s_excludeKeywords = new Dictionary>(StringComparer.OrdinalIgnoreCase) + private static readonly Dictionary> s_excludeKeywords = new Dictionary>(StringComparer.OrdinalIgnoreCase) { {@"Node", new List {@"Node"}}, }; diff --git a/src/System.Management.Automation/engine/pipeline.cs b/src/System.Management.Automation/engine/pipeline.cs index d963afffad1..20342b2ff8f 100644 --- a/src/System.Management.Automation/engine/pipeline.cs +++ b/src/System.Management.Automation/engine/pipeline.cs @@ -1383,7 +1383,7 @@ private void DisposeCommands() _redirectionPipes = null; } - private object _stopReasonLock = new object(); + private readonly object _stopReasonLock = new object(); /// /// Makes an internal note of the exception, but only if this is /// the first error. diff --git a/src/System.Management.Automation/engine/regex.cs b/src/System.Management.Automation/engine/regex.cs index 2a62a8a543e..0046b06dabd 100644 --- a/src/System.Management.Automation/engine/regex.cs +++ b/src/System.Management.Automation/engine/regex.cs @@ -456,7 +456,7 @@ internal WildcardPatternException(ErrorRecord errorRecord) } [NonSerialized] - private ErrorRecord _errorRecord; + private readonly ErrorRecord _errorRecord; /// /// Constructs an instance of the WildcardPatternException object. diff --git a/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs b/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs index ccee756d654..5e18fa0ef9b 100644 --- a/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs +++ b/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs @@ -18,12 +18,12 @@ internal class ClientMethodExecutor /// /// Transport manager. /// - private BaseClientTransportManager _transportManager; + private readonly BaseClientTransportManager _transportManager; /// /// Client host. /// - private PSHost _clientHost; + private readonly PSHost _clientHost; /// /// Client runspace pool id. @@ -38,7 +38,7 @@ internal class ClientMethodExecutor /// /// Remote host call. /// - private RemoteHostCall _remoteHostCall; + private readonly RemoteHostCall _remoteHostCall; /// /// Remote host call. diff --git a/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs b/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs index 5ae081bc3a7..17b3d9fc8df 100644 --- a/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs +++ b/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs @@ -20,7 +20,7 @@ internal class ClientRemotePowerShell : IDisposable #region Tracer [TraceSourceAttribute("CRPS", "ClientRemotePowerShell")] - private static PSTraceSource s_tracer = PSTraceSource.GetTracer("CRPS", "ClientRemotePowerShellBase"); + private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("CRPS", "ClientRemotePowerShellBase"); #endregion Tracer @@ -934,7 +934,7 @@ private void HandleRobustConnectionNotification( /// datastructure handler. We cannot send the state back to the upper layers until /// close is completed from the datastructure/transport layer. /// - private Queue _stateInfoQueue = new Queue(); + private readonly Queue _stateInfoQueue = new Queue(); private PSConnectionRetryStatus _connectionRetryStatus = PSConnectionRetryStatus.None; diff --git a/src/System.Management.Automation/engine/remoting/client/Job.cs b/src/System.Management.Automation/engine/remoting/client/Job.cs index 7cbf139d361..46947e9e322 100644 --- a/src/System.Management.Automation/engine/remoting/client/Job.cs +++ b/src/System.Management.Automation/engine/remoting/client/Job.cs @@ -214,7 +214,7 @@ public JobState CurrentState /// State of job when exception was thrown. /// [NonSerialized] - private JobState _currState = 0; + private readonly JobState _currState = 0; } /// @@ -2054,7 +2054,7 @@ private void SubmitAndWaitForConnect(List connectJobOperatio /// private class ConnectJobOperation : IThrottleOperation { - private PSRemotingChildJob _psRemoteChildJob; + private readonly PSRemotingChildJob _psRemoteChildJob; internal ConnectJobOperation(PSRemotingChildJob job) { @@ -2666,7 +2666,7 @@ private void HandleJobUnblocked(object sender, EventArgs eventArgs) #region Private Members - private ThrottleManager _throttleManager = new ThrottleManager(); + private readonly ThrottleManager _throttleManager = new ThrottleManager(); private readonly object _syncObject = new object(); // sync object @@ -3834,7 +3834,7 @@ private void HandleRunspaceAvailabilityChanged(object sender, RunspaceAvailabili #region Private Members // helper associated with this job object - private RemotePipeline _remotePipeline = null; + private readonly RemotePipeline _remotePipeline = null; // object used for synchronization protected object SyncObject = new object(); @@ -3859,9 +3859,9 @@ internal sealed class RemotingJobDebugger : Debugger { #region Members - private Debugger _wrappedDebugger; - private Runspace _runspace; - private string _jobName; + private readonly Debugger _wrappedDebugger; + private readonly Runspace _runspace; + private readonly string _jobName; #endregion @@ -4181,9 +4181,9 @@ internal class PSInvokeExpressionSyncJob : PSRemotingChildJob { #region Private Members - private List _helpers = new List(); - private ThrottleManager _throttleManager; - private Dictionary _powershells = new Dictionary(); + private readonly List _helpers = new List(); + private readonly ThrottleManager _throttleManager; + private readonly Dictionary _powershells = new Dictionary(); private int _pipelineFinishedCount; private int _pipelineDisconnectedCount; diff --git a/src/System.Management.Automation/engine/remoting/client/Job2.cs b/src/System.Management.Automation/engine/remoting/client/Job2.cs index b97243651fb..1326d22629b 100644 --- a/src/System.Management.Automation/engine/remoting/client/Job2.cs +++ b/src/System.Management.Automation/engine/remoting/client/Job2.cs @@ -883,7 +883,7 @@ public override void StartJob() _tracer.WriteMessage(TraceClassName, "StartJob", Guid.Empty, this, "Exiting method", null); } - private static Tracer s_structuredTracer = new Tracer(); + private static readonly Tracer s_structuredTracer = new Tracer(); /// /// Starts all child jobs asynchronously. @@ -2164,14 +2164,14 @@ protected JobFailedException(SerializationInfo serializationInfo, StreamingConte /// public Exception Reason { get { return _reason; } } - private Exception _reason; + private readonly Exception _reason; /// /// The user-focused location from where this error originated. /// public ScriptExtent DisplayScriptPosition { get { return _displayScriptPosition; } } - private ScriptExtent _displayScriptPosition; + private readonly ScriptExtent _displayScriptPosition; /// /// Gets the information for serialization. diff --git a/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs b/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs index 640bbb11f33..d5d0b90adb2 100644 --- a/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs +++ b/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs @@ -692,7 +692,7 @@ internal override void PropagateApplicationPrivateData(Runspace runspace) } private PSPrimitiveDictionary _applicationPrivateData; - private ManualResetEvent _applicationPrivateDataReceived = new ManualResetEvent(false); + private readonly ManualResetEvent _applicationPrivateDataReceived = new ManualResetEvent(false); /// /// This event is raised, when a host call is for a remote runspace @@ -1894,7 +1894,7 @@ private void WaitAndRaiseConnectEventsProc(object state) #region Private Members - private RunspaceConnectionInfo _connectionInfo; // connection info with which this + private readonly RunspaceConnectionInfo _connectionInfo; // connection info with which this // runspace is created // data structure handler handling private RunspacePoolAsyncResult _openAsyncResult;// async result object generated on @@ -1911,7 +1911,7 @@ private void WaitAndRaiseConnectEventsProc(object state) private bool _canReconnect; private string _friendlyName = string.Empty; - private System.Collections.Concurrent.ConcurrentStack _runningPowerShells; + private readonly System.Collections.Concurrent.ConcurrentStack _runningPowerShells; #endregion Private Members diff --git a/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs b/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs index 5665a0e3be0..8c578a13284 100644 --- a/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs +++ b/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs @@ -25,7 +25,7 @@ public OriginInfo OriginInfo } } - private OriginInfo _originInfo; + private readonly OriginInfo _originInfo; /// /// Constructor. @@ -303,7 +303,7 @@ public string PSComputerName } [DataMemberAttribute()] - private string _computerName; + private readonly string _computerName; /// /// Runspace instance ID. diff --git a/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs b/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs index 852579e0c88..df52ca1835f 100644 --- a/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs +++ b/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs @@ -869,20 +869,20 @@ private void HandleSessionCreateCompleted(object sender, CreateCompleteEventArgs #region Private Members private Guid _clientRunspacePoolId; - private object _syncObject = new object(); + private readonly object _syncObject = new object(); private bool _createRunspaceCalled = false; private Exception _closingReason; - private int _minRunspaces; - private int _maxRunspaces; - private PSHost _host; - private PSPrimitiveDictionary _applicationArguments; - private Dictionary _associatedPowerShellDSHandlers + private readonly int _minRunspaces; + private readonly int _maxRunspaces; + private readonly PSHost _host; + private readonly PSPrimitiveDictionary _applicationArguments; + private readonly Dictionary _associatedPowerShellDSHandlers = new Dictionary(); // data structure handlers of all ClientRemotePowerShell which are // associated with this runspace pool - private object _associationSyncObject = new object(); + private readonly object _associationSyncObject = new object(); // object to synchronize operations to above - private BaseClientSessionTransportManager _transportManager; + private readonly BaseClientSessionTransportManager _transportManager; // session transport manager associated with this runspace private List _preparingForDisconnectList; @@ -1609,7 +1609,7 @@ private void SetupTransportManager(bool inDisconnectMode) // object for synchronizing input to be sent // to server powershell - private object _inputSyncObject = new object(); + private readonly object _inputSyncObject = new object(); private enum connectionStates { diff --git a/src/System.Management.Automation/engine/remoting/client/RunspaceRef.cs b/src/System.Management.Automation/engine/remoting/client/RunspaceRef.cs index acf5d8cee8c..a5b2e576294 100644 --- a/src/System.Management.Automation/engine/remoting/client/RunspaceRef.cs +++ b/src/System.Management.Automation/engine/remoting/client/RunspaceRef.cs @@ -22,10 +22,10 @@ internal class RunspaceRef /// /// Runspace ref. /// - private ObjectRef _runspaceRef; + private readonly ObjectRef _runspaceRef; private bool _stopInvoke; - private object _localSyncObject; - private static RobustConnectionProgress s_RCProgress = new RobustConnectionProgress(); + private readonly object _localSyncObject; + private static readonly RobustConnectionProgress s_RCProgress = new RobustConnectionProgress(); /// /// Constructor for RunspaceRef. diff --git a/src/System.Management.Automation/engine/remoting/client/clientremotesession.cs b/src/System.Management.Automation/engine/remoting/client/clientremotesession.cs index fc7e4ffa8c9..3434f6e1ab8 100644 --- a/src/System.Management.Automation/engine/remoting/client/clientremotesession.cs +++ b/src/System.Management.Automation/engine/remoting/client/clientremotesession.cs @@ -56,7 +56,7 @@ internal class ClientRemoteSessionContext internal abstract class ClientRemoteSession : RemoteSession { [TraceSourceAttribute("CRSession", "ClientRemoteSession")] - private static PSTraceSource s_trace = PSTraceSource.GetTracer("CRSession", "ClientRemoteSession"); + private static readonly PSTraceSource s_trace = PSTraceSource.GetTracer("CRSession", "ClientRemoteSession"); #region Public_Method_API @@ -178,7 +178,7 @@ internal RemoteRunspacePoolInternal GetRunspacePool(Guid clientRunspacePoolId) internal class ClientRemoteSessionImpl : ClientRemoteSession, IDisposable { [TraceSourceAttribute("CRSessionImpl", "ClientRemoteSessionImpl")] - private static PSTraceSource s_trace = PSTraceSource.GetTracer("CRSessionImpl", "ClientRemoteSessionImpl"); + private static readonly PSTraceSource s_trace = PSTraceSource.GetTracer("CRSessionImpl", "ClientRemoteSessionImpl"); private PSRemotingCryptoHelperClient _cryptoHelper = null; diff --git a/src/System.Management.Automation/engine/remoting/client/clientremotesessionprotocolstatemachine.cs b/src/System.Management.Automation/engine/remoting/client/clientremotesessionprotocolstatemachine.cs index 63713c2c200..3317bff80a1 100644 --- a/src/System.Management.Automation/engine/remoting/client/clientremotesessionprotocolstatemachine.cs +++ b/src/System.Management.Automation/engine/remoting/client/clientremotesessionprotocolstatemachine.cs @@ -32,25 +32,25 @@ namespace System.Management.Automation.Remoting internal class ClientRemoteSessionDSHandlerStateMachine { [TraceSourceAttribute("CRSessionFSM", "CRSessionFSM")] - private static PSTraceSource s_trace = PSTraceSource.GetTracer("CRSessionFSM", "CRSessionFSM"); + private static readonly PSTraceSource s_trace = PSTraceSource.GetTracer("CRSessionFSM", "CRSessionFSM"); /// /// Event handling matrix. It defines what action to take when an event occur. /// [State,Event]=>Action. /// - private EventHandler[,] _stateMachineHandle; - private Queue _clientRemoteSessionStateChangeQueue; + private readonly EventHandler[,] _stateMachineHandle; + private readonly Queue _clientRemoteSessionStateChangeQueue; /// /// Current state of session. /// private RemoteSessionState _state; - private Queue _processPendingEventsQueue + private readonly Queue _processPendingEventsQueue = new Queue(); // all events raised through the state machine // will be queued in this - private object _syncObject = new object(); + private readonly object _syncObject = new object(); // object for synchronizing access to the above // queue diff --git a/src/System.Management.Automation/engine/remoting/client/remotepipeline.cs b/src/System.Management.Automation/engine/remoting/client/remotepipeline.cs index 5b7ddd301ee..63085a5a294 100644 --- a/src/System.Management.Automation/engine/remoting/client/remotepipeline.cs +++ b/src/System.Management.Automation/engine/remoting/client/remotepipeline.cs @@ -20,18 +20,18 @@ internal class RemotePipeline : Pipeline #region Private Members private PowerShell _powershell; - private bool _addToHistory; + private readonly bool _addToHistory; private bool _isNested; private bool _isSteppable; - private Runspace _runspace; - private object _syncRoot = new object(); + private readonly Runspace _runspace; + private readonly object _syncRoot = new object(); private bool _disposed = false; private string _historyString; private PipelineStateInfo _pipelineStateInfo = new PipelineStateInfo(PipelineState.NotStarted); - private CommandCollection _commands = new CommandCollection(); - private string _computerName; + private readonly CommandCollection _commands = new CommandCollection(); + private readonly string _computerName; private Guid _runspaceId; - private ConnectCommandInfo _connectCmdInfo = null; + private readonly ConnectCommandInfo _connectCmdInfo = null; /// /// This is queue of all the state change event which have occured for @@ -56,7 +56,7 @@ public ExecutionEventQueueItem(PipelineStateInfo pipelineStateInfo, RunspaceAvai public RunspaceAvailability NewRunspaceAvailability; } - private bool _performNestedCheck = true; + private readonly bool _performNestedCheck = true; #endregion Private Members @@ -362,12 +362,12 @@ public bool AddToHistory // Stream and Collection go together...a stream wraps // a corresponding collection to support // streaming behavior of the pipeline. - private PSDataCollection _outputCollection; - private PSDataCollectionStream _outputStream; - private PSDataCollection _errorCollection; - private PSDataCollectionStream _errorStream; - private PSDataCollection _inputCollection; - private PSDataCollectionStream _inputStream; + private readonly PSDataCollection _outputCollection; + private readonly PSDataCollectionStream _outputStream; + private readonly PSDataCollection _errorCollection; + private readonly PSDataCollectionStream _errorStream; + private readonly PSDataCollection _inputCollection; + private readonly PSDataCollectionStream _inputStream; /// /// Stream for providing input to PipelineProcessor. Host will write on diff --git a/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs b/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs index 0b8cd69e2de..d3426d92349 100644 --- a/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs +++ b/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs @@ -32,11 +32,11 @@ internal class RemoteRunspace : Runspace, IDisposable { #region Private Members - private List _runningPipelines = new List(); - private object _syncRoot = new object(); + private readonly List _runningPipelines = new List(); + private readonly object _syncRoot = new object(); private RunspaceStateInfo _runspaceStateInfo = new RunspaceStateInfo(RunspaceState.BeforeOpen); - private bool _bSessionStateProxyCallInProgress = false; - private RunspaceConnectionInfo _connectionInfo; + private readonly bool _bSessionStateProxyCallInProgress = false; + private readonly RunspaceConnectionInfo _connectionInfo; private RemoteDebugger _remoteDebugger; private PSPrimitiveDictionary _applicationPrivateData; @@ -1804,7 +1804,7 @@ internal sealed class RemoteDebugger : Debugger, IDisposable { #region Members - private RemoteRunspace _runspace; + private readonly RemoteRunspace _runspace; private PowerShell _psDebuggerCommand; private bool _remoteDebugSupported; private bool _isActive; @@ -2945,7 +2945,7 @@ private void CheckRemoteBreakpointManagementSupport(string breakpointCommandName internal class RemoteSessionStateProxy : SessionStateProxy { - private RemoteRunspace _runspace; + private readonly RemoteRunspace _runspace; internal RemoteSessionStateProxy(RemoteRunspace runspace) { Dbg.Assert(runspace != null, "Caller should validate the parameter"); diff --git a/src/System.Management.Automation/engine/remoting/client/remotingprotocolimplementation.cs b/src/System.Management.Automation/engine/remoting/client/remotingprotocolimplementation.cs index 486b9c4cf13..f40aab1bd2c 100644 --- a/src/System.Management.Automation/engine/remoting/client/remotingprotocolimplementation.cs +++ b/src/System.Management.Automation/engine/remoting/client/remotingprotocolimplementation.cs @@ -16,21 +16,21 @@ namespace System.Management.Automation.Remoting internal class ClientRemoteSessionDSHandlerImpl : ClientRemoteSessionDataStructureHandler, IDisposable { [TraceSourceAttribute("CRSDSHdlerImpl", "ClientRemoteSessionDSHandlerImpl")] - private static PSTraceSource s_trace = PSTraceSource.GetTracer("CRSDSHdlerImpl", "ClientRemoteSessionDSHandlerImpl"); + private static readonly PSTraceSource s_trace = PSTraceSource.GetTracer("CRSDSHdlerImpl", "ClientRemoteSessionDSHandlerImpl"); private const string resBaseName = "remotingerroridstrings"; - private BaseClientSessionTransportManager _transportManager; - private ClientRemoteSessionDSHandlerStateMachine _stateMachine; - private ClientRemoteSession _session; - private RunspaceConnectionInfo _connectionInfo; + private readonly BaseClientSessionTransportManager _transportManager; + private readonly ClientRemoteSessionDSHandlerStateMachine _stateMachine; + private readonly ClientRemoteSession _session; + private readonly RunspaceConnectionInfo _connectionInfo; // used for connection redirection. private Uri _redirectUri; private int _maxUriRedirectionCount; private bool _isCloseCalled; - private object _syncObject = new object(); - private PSRemotingCryptoHelper _cryptoHelper; + private readonly object _syncObject = new object(); + private readonly PSRemotingCryptoHelper _cryptoHelper; - private ClientRemoteSession.URIDirectionReported _uriRedirectionHandler; + private readonly ClientRemoteSession.URIDirectionReported _uriRedirectionHandler; internal override BaseClientSessionTransportManager TransportManager { diff --git a/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs b/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs index 452a6b10b75..099612761df 100644 --- a/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs +++ b/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs @@ -476,11 +476,11 @@ private class ConnectRunspaceOperation : IThrottleOperation { private PSSession _session; private PSSession _oldSession; - private ObjectStream _writeStream; - private Collection _retryList; - private PSHost _host; - private QueryRunspaces _queryRunspaces; - private static object s_LockObject = new object(); + private readonly ObjectStream _writeStream; + private readonly Collection _retryList; + private readonly PSHost _host; + private readonly QueryRunspaces _queryRunspaces; + private static readonly object s_LockObject = new object(); internal ConnectRunspaceOperation( PSSession session, @@ -1084,24 +1084,24 @@ private void Dispose(bool disposing) #region Private Members // Collection of PSSessions to be connected. - private Collection _allSessions = new Collection(); + private readonly Collection _allSessions = new Collection(); // Object used to perform network disconnect operations in a limited manner. - private ThrottleManager _throttleManager = new ThrottleManager(); + private readonly ThrottleManager _throttleManager = new ThrottleManager(); // Event indicating that all disconnect operations through the ThrottleManager // are complete. - private ManualResetEvent _operationsComplete = new ManualResetEvent(true); + private readonly ManualResetEvent _operationsComplete = new ManualResetEvent(true); // Object used for querying remote runspaces. - private QueryRunspaces _queryRunspaces = new QueryRunspaces(); + private readonly QueryRunspaces _queryRunspaces = new QueryRunspaces(); // Object to collect output data from multiple threads. - private ObjectStream _stream = new ObjectStream(); + private readonly ObjectStream _stream = new ObjectStream(); // Support for connection retry on failure. - private ThrottleManager _retryThrottleManager = new ThrottleManager(); - private Collection _failedSessions = new Collection(); + private readonly ThrottleManager _retryThrottleManager = new ThrottleManager(); + private readonly Collection _failedSessions = new Collection(); #endregion } diff --git a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs index 3a7d1e5a9e4..b2e83053789 100644 --- a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs +++ b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs @@ -4210,7 +4210,7 @@ function Enable-PSSessionConfiguration $_ | Enable-PSSessionConfiguration -force $args[0] -sddl $args[1] -isSDDLSpecified $args[2] -queryForSet $args[3] -captionForSet $args[4] -queryForQC $args[5] -captionForQC $args[6] -whatif:$args[7] -confirm:$args[8] -shouldProcessDescForQC $args[9] -setEnabledTarget $args[10] -setEnabledAction $args[11] -skipNetworkProfileCheck $args[12] -noServiceRestart $args[13] "; - private static ScriptBlock s_enablePluginSb; + private static readonly ScriptBlock s_enablePluginSb; #endregion @@ -4238,7 +4238,7 @@ static EnablePSSessionConfigurationCommand() [ValidateNotNullOrEmpty] public string[] Name { get; set; } - private Collection _shellsToEnable = new Collection(); + private readonly Collection _shellsToEnable = new Collection(); /// /// Property that sets force parameter. This will allow @@ -4496,7 +4496,7 @@ function Disable-PSSessionConfiguration $_ | Disable-PSSessionConfiguration -force $args[0] -whatif:$args[1] -confirm:$args[2] -restartWinRMMessage $args[3] -setEnabledTarget $args[4] -setEnabledAction $args[5] -noServiceRestart $args[6] "; - private static ScriptBlock s_disablePluginSb; + private static readonly ScriptBlock s_disablePluginSb; #endregion @@ -4524,7 +4524,7 @@ static DisablePSSessionConfigurationCommand() [ValidateNotNullOrEmpty] public string[] Name { get; set; } - private Collection _shellsToDisable = new Collection(); + private readonly Collection _shellsToDisable = new Collection(); /// /// Property that sets force parameter. This will allow @@ -4901,7 +4901,7 @@ function Enable-PSRemoting Enable-PSRemoting -force $args[0] -queryForRegisterDefault $args[1] -captionForRegisterDefault $args[2] -queryForSet $args[3] -captionForSet $args[4] -whatif:$args[5] -confirm:$args[6] -skipNetworkProfileCheck $args[7] -errorMsgUnableToInstallPlugin $args[8] "; - private static ScriptBlock s_enableRemotingSb; + private static readonly ScriptBlock s_enableRemotingSb; #endregion @@ -5126,7 +5126,7 @@ function Disable-PSRemoting Disable-PSRemoting -force:$args[0] -queryForSet $args[1] -captionForSet $args[2] -restartWinRMMessage $args[3] -whatif:$args[4] -confirm:$args[5] "; - private static ScriptBlock s_disableRemotingSb; + private static readonly ScriptBlock s_disableRemotingSb; #endregion Private Data diff --git a/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs b/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs index dd4f153ca1d..e9f18ac4b7a 100644 --- a/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs +++ b/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs @@ -394,8 +394,8 @@ private string GetLocalhostWithNetworkAccessEnabled(Dictionary /// private class DisconnectRunspaceOperation : IThrottleOperation { - private PSSession _remoteSession; - private ObjectStream _writeStream; + private readonly PSSession _remoteSession; + private readonly ObjectStream _writeStream; internal DisconnectRunspaceOperation(PSSession session, ObjectStream stream) { @@ -556,14 +556,14 @@ private void Dispose(bool disposing) #region Private Members // Object used to perform network disconnect operations in a limited manner. - private ThrottleManager _throttleManager = new ThrottleManager(); + private readonly ThrottleManager _throttleManager = new ThrottleManager(); // Event indicating that all disconnect operations through the ThrottleManager // are complete. - private ManualResetEvent _operationsComplete = new ManualResetEvent(true); + private readonly ManualResetEvent _operationsComplete = new ManualResetEvent(true); // Output data stream. - private ObjectStream _stream = new ObjectStream(); + private readonly ObjectStream _stream = new ObjectStream(); #endregion } diff --git a/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs b/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs index 6b2fa8c804e..8b5ece9be4d 100644 --- a/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs @@ -1986,7 +1986,7 @@ private void PreProcessStreamObject(PSStreamObject streamObject) private ThrottleManager _throttleManager = new ThrottleManager(); // throttle manager for handling all throttling operations - private ManualResetEvent _operationsComplete = new ManualResetEvent(true); + private readonly ManualResetEvent _operationsComplete = new ManualResetEvent(true); private ManualResetEvent _disconnectComplete; // the initial state is true because when no // operations actually take place as in case of a @@ -2003,17 +2003,17 @@ private void PreProcessStreamObject(PSStreamObject streamObject) private bool _inputStreamClosed = false; private const string InProcParameterSet = "InProcess"; - private PSDataCollection _input = new PSDataCollection(); + private readonly PSDataCollection _input = new PSDataCollection(); private bool _needToCollect = false; private bool _needToStartSteppablePipelineOnServer = false; private bool _clearInvokeCommandOnRunspace = false; - private List _inputWriters = new List(); - private object _jobSyncObject = new object(); + private readonly List _inputWriters = new List(); + private readonly object _jobSyncObject = new object(); private bool _nojob = false; private Guid _instanceId = Guid.NewGuid(); private bool _propagateErrors = false; - private static RobustConnectionProgress s_RCProgress = new RobustConnectionProgress(); + private static readonly RobustConnectionProgress s_RCProgress = new RobustConnectionProgress(); internal static readonly string RemoteJobType = "RemoteJob"; @@ -2093,14 +2093,14 @@ namespace System.Management.Automation.Internal internal class RobustConnectionProgress { private System.Management.Automation.Host.PSHost _psHost; - private string _activity; + private readonly string _activity; private string _status; private int _secondsTotal; private int _secondsRemaining; private ProgressRecord _progressRecord; private long _sourceId; private bool _progressIsRunning; - private object _syncObject; + private readonly object _syncObject; private Timer _updateTimer; /// diff --git a/src/System.Management.Automation/engine/remoting/commands/JobRepository.cs b/src/System.Management.Automation/engine/remoting/commands/JobRepository.cs index d06eabf25a3..7bb52abcb1e 100644 --- a/src/System.Management.Automation/engine/remoting/commands/JobRepository.cs +++ b/src/System.Management.Automation/engine/remoting/commands/JobRepository.cs @@ -132,9 +132,9 @@ internal Dictionary Dictionary #region Private Members - private Dictionary _repository = new Dictionary(); - private object _syncObject = new object(); // object for synchronization - private string _identifier; + private readonly Dictionary _repository = new Dictionary(); + private readonly object _syncObject = new object(); // object for synchronization + private readonly string _identifier; #endregion Private Members } diff --git a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationOptionCommand.cs b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationOptionCommand.cs index 963259b91ff..8e5580c7190 100644 --- a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationOptionCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationOptionCommand.cs @@ -431,7 +431,7 @@ internal override Hashtable ConstructOptionsAsHashtable() [OutputType(typeof(WSManConfigurationOption))] public sealed class NewPSTransportOptionCommand : PSCmdlet { - private WSManConfigurationOption _option = new WSManConfigurationOption(); + private readonly WSManConfigurationOption _option = new WSManConfigurationOption(); /// /// MaxIdleTimeoutSec. diff --git a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs index a000e2d0bbe..4b46e14c46b 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs @@ -146,7 +146,7 @@ internal string GetMessage(string resourceString, params object[] args) #region Private Members - private static string s_LOCALHOST = "localhost"; + private static readonly string s_LOCALHOST = "localhost"; // private PSETWTracer tracer = PSETWTracer.GetETWTracer(PSKeyword.Cmdlets); @@ -3471,7 +3471,7 @@ internal class ExecutionCmdletHelperComputerName : ExecutionCmdletHelper /// Determines if the command should be invoked and then disconnect the /// remote runspace from the client. /// - private bool _invokeAndDisconnect; + private readonly bool _invokeAndDisconnect; /// /// The remote runspace created using the computer name diff --git a/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs b/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs index e36fb633783..7161bfd40b4 100644 --- a/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs +++ b/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs @@ -1303,7 +1303,7 @@ private void WriteInvalidArgumentError(PSRemotingErrorId errorId, string resourc private RemotePipeline _remotePipeline; private Job _job; private ManualResetEvent _stopPipelineReceive; - private object _syncObject = new object(); + private readonly object _syncObject = new object(); #endregion } diff --git a/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs b/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs index c63e4548e6a..aac403e8315 100644 --- a/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs @@ -1011,7 +1011,7 @@ private void HandleStopJobCompleted(object sender, AsyncCompletedEventArgs event #region Private Members - private HashSet _pendingJobs = new HashSet(); + private readonly HashSet _pendingJobs = new HashSet(); private readonly ManualResetEvent _waitForJobs = new ManualResetEvent(false); private readonly Dictionary> _cleanUpActions = new Dictionary>(); diff --git a/src/System.Management.Automation/engine/remoting/commands/getrunspacecommand.cs b/src/System.Management.Automation/engine/remoting/commands/getrunspacecommand.cs index 2a3c92dfcf3..0ad23712ee6 100644 --- a/src/System.Management.Automation/engine/remoting/commands/getrunspacecommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/getrunspacecommand.cs @@ -525,10 +525,10 @@ public void Dispose() #region Private Members // Object used for querying remote runspaces. - private QueryRunspaces _queryRunspaces = new QueryRunspaces(); + private readonly QueryRunspaces _queryRunspaces = new QueryRunspaces(); // Object to collect output data from multiple threads. - private ObjectStream _stream = new ObjectStream(); + private readonly ObjectStream _stream = new ObjectStream(); #endregion } diff --git a/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs b/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs index c9df93cd05b..bf1c6283f9f 100644 --- a/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs @@ -1276,10 +1276,10 @@ private void WriteErrorCreateRemoteRunspaceFailed(Exception e, Uri uri) #region Private Members private ThrottleManager _throttleManager = new ThrottleManager(); - private ObjectStream _stream = new ObjectStream(); + private readonly ObjectStream _stream = new ObjectStream(); // event that signals that all operations are // complete (including closing if any) - private ManualResetEvent _operationsComplete = new ManualResetEvent(true); + private readonly ManualResetEvent _operationsComplete = new ManualResetEvent(true); // the initial state is true because when no // operations actually take place as in case of a // parameter binding exception, then Dispose is @@ -1288,13 +1288,13 @@ private void WriteErrorCreateRemoteRunspaceFailed(Exception e, Uri uri) // BeginProcessing() // list of runspaces to dispose - private List _toDispose = new List(); + private readonly List _toDispose = new List(); // List of runspace connect operations. Need to keep for cleanup. - private Collection> _allOperations = new Collection>(); + private readonly Collection> _allOperations = new Collection>(); // Default FQEID. - private string _defaultFQEID = "PSSessionOpenFailed"; + private readonly string _defaultFQEID = "PSSessionOpenFailed"; #endregion Private Members } @@ -1312,7 +1312,7 @@ internal class OpenRunspaceOperation : IThrottleOperation, IDisposable private bool _startComplete; private bool _stopComplete; - private object _syncObject = new object(); + private readonly object _syncObject = new object(); internal RemoteRunspace OperatedRunspace { get; } @@ -1378,7 +1378,7 @@ internal override void StopOperation() // b) To ensure all callbacks are fired by manually invoking callbacks and handling // any exceptions thrown on this thread. (ThrottleManager will not respond if it doesn't // get a start/stop complete callback). - private List> _internalCallbacks = new List>(); + private readonly List> _internalCallbacks = new List>(); internal override event EventHandler OperationComplete { add diff --git a/src/System.Management.Automation/engine/remoting/common/AsyncObject.cs b/src/System.Management.Automation/engine/remoting/common/AsyncObject.cs index a68a6f78869..2c3ddbe9ce4 100644 --- a/src/System.Management.Automation/engine/remoting/common/AsyncObject.cs +++ b/src/System.Management.Automation/engine/remoting/common/AsyncObject.cs @@ -22,7 +22,7 @@ internal class AsyncObject where T : class /// /// Value was set. /// - private ManualResetEvent _valueWasSet; + private readonly ManualResetEvent _valueWasSet; /// /// Value. diff --git a/src/System.Management.Automation/engine/remoting/common/DispatchTable.cs b/src/System.Management.Automation/engine/remoting/common/DispatchTable.cs index 035d39ac84e..9dc073e6616 100644 --- a/src/System.Management.Automation/engine/remoting/common/DispatchTable.cs +++ b/src/System.Management.Automation/engine/remoting/common/DispatchTable.cs @@ -33,7 +33,7 @@ internal class DispatchTable where T : class /// /// Response async objects. /// - private Dictionary> _responseAsyncObjects = new Dictionary>(); + private readonly Dictionary> _responseAsyncObjects = new Dictionary>(); /// /// Next call id. diff --git a/src/System.Management.Automation/engine/remoting/common/Indexer.cs b/src/System.Management.Automation/engine/remoting/common/Indexer.cs index 0f6b70482c8..243a1580ea5 100644 --- a/src/System.Management.Automation/engine/remoting/common/Indexer.cs +++ b/src/System.Management.Automation/engine/remoting/common/Indexer.cs @@ -16,12 +16,12 @@ internal class Indexer : IEnumerable, IEnumerator /// /// Current. /// - private int[] _current; + private readonly int[] _current; /// /// Lengths. /// - private int[] _lengths; + private readonly int[] _lengths; /// /// Current. diff --git a/src/System.Management.Automation/engine/remoting/common/ObjectRef.cs b/src/System.Management.Automation/engine/remoting/common/ObjectRef.cs index 25534b59a30..a5ae0dab19c 100644 --- a/src/System.Management.Automation/engine/remoting/common/ObjectRef.cs +++ b/src/System.Management.Automation/engine/remoting/common/ObjectRef.cs @@ -20,7 +20,7 @@ internal class ObjectRef where T : class /// /// Old value. /// - private T _oldValue; + private readonly T _oldValue; /// /// Old value. diff --git a/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs b/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs index dff56e407f9..81e2ec9b136 100644 --- a/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs +++ b/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs @@ -17,7 +17,7 @@ internal class HyperVSocketEndPoint : EndPoint { #region Members - private System.Net.Sockets.AddressFamily _addressFamily; + private readonly System.Net.Sockets.AddressFamily _addressFamily; private Guid _vmId; private Guid _serviceId; @@ -138,7 +138,7 @@ internal sealed class RemoteSessionHyperVSocketServer : IDisposable #region Members private readonly object _syncObject; - private PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource(); + private readonly PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource(); #endregion @@ -337,9 +337,9 @@ internal sealed class RemoteSessionHyperVSocketClient : IDisposable #region Members private readonly object _syncObject; - private PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource(); + private readonly PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource(); - private static ManualResetEvent s_connectDone = + private static readonly ManualResetEvent s_connectDone = new ManualResetEvent(false); #endregion diff --git a/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs b/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs index 6c0e0625bdd..a5418197c52 100644 --- a/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs +++ b/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs @@ -350,7 +350,7 @@ public sealed class RemoteSessionNamedPipeServer : IDisposable #region Members private readonly object _syncObject; - private PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource(); + private readonly PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource(); private const string _threadName = "IPC Listener Thread"; private const int _namedPipeBufferSizeForRemoting = 32768; @@ -358,7 +358,7 @@ public sealed class RemoteSessionNamedPipeServer : IDisposable private const int _maxPipePathLengthMacOS = 104; // Singleton server. - private static object s_syncObject; + private static readonly object s_syncObject; internal static RemoteSessionNamedPipeServer IPCNamedPipeServer; internal static bool IPCNamedPipeServerEnabled; @@ -1019,7 +1019,7 @@ internal class NamedPipeClientBase : IDisposable #region Members private NamedPipeClientStream _clientPipeStream; - private PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource(); + private readonly PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource(); protected string _pipeName; diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHost.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHost.cs index 414676dffed..f0f37381e7c 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHost.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHost.cs @@ -42,12 +42,12 @@ internal string MethodName /// /// Method info. /// - private RemoteHostMethodInfo _methodInfo; + private readonly RemoteHostMethodInfo _methodInfo; /// /// Call id. /// - private long _callId; + private readonly long _callId; /// /// Call id. @@ -530,7 +530,7 @@ internal class RemoteHostResponse /// /// Call id. /// - private long _callId; + private readonly long _callId; /// /// Call id. @@ -546,17 +546,17 @@ internal long CallId /// /// Method id. /// - private RemoteHostMethodId _methodId; + private readonly RemoteHostMethodId _methodId; /// /// Return value. /// - private object _returnValue; + private readonly object _returnValue; /// /// Exception. /// - private Exception _exception; + private readonly Exception _exception; /// /// Constructor for RemoteHostResponse. diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs index bc5d47c8a83..57953b1fd8b 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs @@ -21,10 +21,10 @@ internal class RemoteSessionCapability { #region DO NOT REMOVE OR RENAME THESE FIELDS - it will break remoting compatibility with Windows PowerShell - private Version _psversion; - private Version _serversion; + private readonly Version _psversion; + private readonly Version _serversion; private Version _protocolVersion; - private RemotingDestination _remotingDestination; + private readonly RemotingDestination _remotingDestination; private static byte[] _timeZoneInByteFormat; private TimeZoneInfo _timeZone; @@ -177,7 +177,7 @@ internal class HostDefaultData #region DO NOT REMOVE OR RENAME THESE FIELDS - it will break remoting compatibility with Windows PowerShell - private Dictionary data; + private readonly Dictionary data; #endregion @@ -358,7 +358,7 @@ internal bool IsHostNull /// /// Is host ui null. /// - private bool _isHostUINull; + private readonly bool _isHostUINull; /// /// Is host ui null. @@ -374,7 +374,7 @@ internal bool IsHostUINull /// /// Is host raw ui null. /// - private bool _isHostRawUINull; + private readonly bool _isHostRawUINull; private readonly bool _isHostNull; diff --git a/src/System.Management.Automation/engine/remoting/common/fragmentor.cs b/src/System.Management.Automation/engine/remoting/common/fragmentor.cs index 72feecefdc9..c01f3fb5d23 100644 --- a/src/System.Management.Automation/engine/remoting/common/fragmentor.cs +++ b/src/System.Management.Automation/engine/remoting/common/fragmentor.cs @@ -427,7 +427,7 @@ internal static int GetBlobLength(byte[] fragmentBytes, int startIndex) internal class SerializedDataStream : Stream, IDisposable { [TraceSourceAttribute("SerializedDataStream", "SerializedDataStream")] - private static PSTraceSource s_trace = PSTraceSource.GetTracer("SerializedDataStream", "SerializedDataStream"); + private static readonly PSTraceSource s_trace = PSTraceSource.GetTracer("SerializedDataStream", "SerializedDataStream"); #region Global Constants private static long s_objectIdSequenceNumber = 0; @@ -437,20 +437,20 @@ internal class SerializedDataStream : Stream, IDisposable #region Private Data private bool _isEntered; - private FragmentedRemoteObject _currentFragment; + private readonly FragmentedRemoteObject _currentFragment; private long _fragmentId; - private int _fragmentSize; - private object _syncObject; + private readonly int _fragmentSize; + private readonly object _syncObject; private bool _isDisposed; - private bool _notifyOnWriteFragmentImmediately; + private readonly bool _notifyOnWriteFragmentImmediately; // MemoryStream does not dynamically resize as data is read. This will waste // lot of memory as data sent on the network will still be there in memory. // To avoid this a queue of memory streams (each stream is of fragmentsize) // is created..so after data is sent the MemoryStream is disposed there by // clearing resources. - private Queue _queuedStreams; + private readonly Queue _queuedStreams; private MemoryStream _writeStream; private MemoryStream _readStream; private int _writeOffset; @@ -956,13 +956,13 @@ public override void SetLength(long value) internal class Fragmentor { #region Global Constants - private static UTF8Encoding s_utf8Encoding = new UTF8Encoding(); + private static readonly UTF8Encoding s_utf8Encoding = new UTF8Encoding(); // This const defines the default depth to be used for serializing objects for remoting. private const int SerializationDepthForRemoting = 1; #endregion private int _fragmentSize; - private SerializationContext _serializationContext; + private readonly SerializationContext _serializationContext; #region Constructor diff --git a/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs b/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs index 571ec3225d5..97e7c038aec 100644 --- a/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs +++ b/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs @@ -600,34 +600,34 @@ private void RaiseThrottleManagerEvents() /// Default throttle limit - the maximum number of operations /// to be processed at a time. /// - private static int s_DEFAULT_THROTTLE_LIMIT = 32; + private static readonly int s_DEFAULT_THROTTLE_LIMIT = 32; /// /// Maximum value that the throttle limit can be set to. /// - private static int s_THROTTLE_LIMIT_MAX = int.MaxValue; + private static readonly int s_THROTTLE_LIMIT_MAX = int.MaxValue; /// /// All pending operations. /// - private List _operationsQueue; + private readonly List _operationsQueue; /// /// List of items on which a StartOperation has /// been called. /// - private List _startOperationQueue; + private readonly List _startOperationQueue; /// /// List of items on which a StopOperation has /// been called. /// - private List _stopOperationQueue; + private readonly List _stopOperationQueue; /// /// Object used to synchronize access to the queues. /// - private object _syncObject; + private readonly object _syncObject; private bool _submitComplete = false; // to check if operations have been submitComplete private bool _stopping = false; // if stop is in process diff --git a/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs index e8a780543bc..b90693c6a59 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs @@ -141,7 +141,7 @@ internal abstract class BaseTransportManager : IDisposable #region tracer [TraceSourceAttribute("Transport", "Traces BaseWSManTransportManager")] - private static PSTraceSource s_baseTracer = PSTraceSource.GetTracer("Transport", "Traces BaseWSManTransportManager"); + private static readonly PSTraceSource s_baseTracer = PSTraceSource.GetTracer("Transport", "Traces BaseWSManTransportManager"); #endregion @@ -178,7 +178,7 @@ internal abstract class BaseTransportManager : IDisposable #region Private Data // fragmentor used to fragment & defragment objects added to this collection. - private ReceiveDataCollection.OnDataAvailableCallback _onDataAvailableCallback; + private readonly ReceiveDataCollection.OnDataAvailableCallback _onDataAvailableCallback; // crypto helper used for encrypting/decrypting // secure string @@ -420,8 +420,8 @@ internal abstract class BaseClientTransportManager : BaseTransportManager, IDisp protected object syncObject = new object(); protected PrioritySendDataCollection dataToBeSent; // used to handle callbacks from the server..these are used to synchronize received callbacks - private Queue _callbackNotificationQueue; - private ReceiveDataCollection.OnDataAvailableCallback _onDataAvailableCallback; + private readonly Queue _callbackNotificationQueue; + private readonly ReceiveDataCollection.OnDataAvailableCallback _onDataAvailableCallback; private bool _isServicingCallbacks; private bool _suspendQueueServicing; private bool _isDebuggerSuspend; @@ -1217,9 +1217,9 @@ internal abstract class AbstractServerTransportManager : BaseTransportManager { #region Private Data - private object _syncObject = new object(); + private readonly object _syncObject = new object(); // used to listen to data available events from serialized datastream. - private SerializedDataStream.OnDataAvailableCallback _onDataAvailable; + private readonly SerializedDataStream.OnDataAvailableCallback _onDataAvailable; // the following variable are used by onDataAvailableCallback. private bool _shouldFlushData; private bool _reportAsPending; diff --git a/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs b/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs index 6ed7eb06245..2a951ad355c 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs @@ -784,9 +784,9 @@ private static string private const string configProvidersKeyName = "PSConfigurationProviders"; private const string configProviderApplicationBaseKeyName = "ApplicationBase"; private const string configProviderAssemblyNameKeyName = "AssemblyName"; - private static Dictionary s_ssnStateProviders = + private static readonly Dictionary s_ssnStateProviders = new Dictionary(StringComparer.OrdinalIgnoreCase); - private static object s_syncObject = new object(); + private static readonly object s_syncObject = new object(); #endregion } @@ -1684,8 +1684,8 @@ internal static void ValidateRoleDefinitions(IDictionary roleDefinitions) /// internal sealed class DISCPowerShellConfiguration : PSSessionConfiguration { - private string _configFile; - private Hashtable _configHash; + private readonly string _configFile; + private readonly Hashtable _configHash; /// /// Gets the configuration hashtable that results from parsing the specified configuration file. diff --git a/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs index fd55cd51bd3..6db0eb3f5f0 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs @@ -402,9 +402,9 @@ internal class OutOfProcessTextWriter { #region Private Data - private TextWriter _writer; + private readonly TextWriter _writer; private bool _isStopped; - private object _syncObject = new object(); + private readonly object _syncObject = new object(); #endregion @@ -466,10 +466,10 @@ internal abstract class OutOfProcessClientSessionTransportManagerBase : BaseClie private readonly BlockingCollection _sessionMessageQueue; private readonly BlockingCollection _commandMessageQueue; - private PrioritySendDataCollection.OnDataAvailableCallback _onDataAvailableToSendCallback; + private readonly PrioritySendDataCollection.OnDataAvailableCallback _onDataAvailableToSendCallback; private OutOfProcessUtils.DataProcessingDelegates _dataProcessingCallbacks; - private Dictionary _cmdTransportManagers; - private Timer _closeTimeOutTimer; + private readonly Dictionary _cmdTransportManagers; + private readonly Timer _closeTimeOutTimer; protected OutOfProcessTextWriter stdInWriter; protected PowerShellTraceSource _tracer; @@ -1055,7 +1055,7 @@ internal class OutOfProcessClientSessionTransportManager : OutOfProcessClientSes #region Private Data private Process _serverProcess; - private NewProcessConnectionInfo _connectionInfo; + private readonly NewProcessConnectionInfo _connectionInfo; private bool _processCreated = true; private PowerShellProcessInstance _processInstance; @@ -1426,9 +1426,9 @@ internal sealed class VMHyperVSocketClientSessionTransportManager : HyperVSocket #region Private Data private Guid _vmGuid; - private string _configurationName; - private VMConnectionInfo _connectionInfo; - private NetworkCredential _networkCredential; + private readonly string _configurationName; + private readonly VMConnectionInfo _connectionInfo; + private readonly NetworkCredential _networkCredential; #endregion @@ -1512,7 +1512,7 @@ internal sealed class ContainerHyperVSocketClientSessionTransportManager : Hyper #region Private Data private Guid _targetGuid; // currently this is the utility vm guid in HyperV container scenario - private ContainerConnectionInfo _connectionInfo; + private readonly ContainerConnectionInfo _connectionInfo; #endregion @@ -1570,7 +1570,7 @@ internal sealed class SSHClientSessionTransportManager : OutOfProcessClientSessi { #region Data - private SSHConnectionInfo _connectionInfo; + private readonly SSHConnectionInfo _connectionInfo; private int _sshProcessId; private StreamWriter _stdInWriter; private StreamReader _stdOutReader; @@ -1858,9 +1858,9 @@ internal abstract class NamedPipeClientSessionTransportManagerBase : OutOfProces { #region Data - private RunspaceConnectionInfo _connectionInfo; + private readonly RunspaceConnectionInfo _connectionInfo; protected NamedPipeClientBase _clientPipe = new NamedPipeClientBase(); - private string _threadName; + private readonly string _threadName; #endregion @@ -1985,7 +1985,7 @@ internal sealed class NamedPipeClientSessionTransportManager : NamedPipeClientSe { #region Private Data - private NamedPipeConnectionInfo _connectionInfo; + private readonly NamedPipeConnectionInfo _connectionInfo; private const string _threadName = "NamedPipeTransport Reader Thread"; #endregion @@ -2052,7 +2052,7 @@ internal sealed class ContainerNamedPipeClientSessionTransportManager : NamedPip { #region Private Data - private ContainerConnectionInfo _connectionInfo; + private readonly ContainerConnectionInfo _connectionInfo; private const string _threadName = "ContainerNamedPipeTransport Reader Thread"; #endregion @@ -2120,9 +2120,9 @@ internal class OutOfProcessClientCommandTransportManager : BaseClientCommandTran { #region Private Data - private OutOfProcessTextWriter _stdInWriter; - private PrioritySendDataCollection.OnDataAvailableCallback _onDataAvailableToSendCallback; - private Timer _signalTimeOutTimer; + private readonly OutOfProcessTextWriter _stdInWriter; + private readonly PrioritySendDataCollection.OnDataAvailableCallback _onDataAvailableToSendCallback; + private readonly Timer _signalTimeOutTimer; #endregion @@ -2421,10 +2421,10 @@ internal class OutOfProcessServerSessionTransportManager : AbstractServerSession { #region Private Data - private OutOfProcessTextWriter _stdOutWriter; - private OutOfProcessTextWriter _stdErrWriter; - private Dictionary _cmdTransportManagers; - private object _syncObject = new object(); + private readonly OutOfProcessTextWriter _stdOutWriter; + private readonly OutOfProcessTextWriter _stdErrWriter; + private readonly Dictionary _cmdTransportManagers; + private readonly object _syncObject = new object(); #endregion @@ -2519,8 +2519,8 @@ internal class OutOfProcessServerTransportManager : AbstractServerTransportManag { #region Private Data - private OutOfProcessTextWriter _stdOutWriter; - private OutOfProcessTextWriter _stdErrWriter; + private readonly OutOfProcessTextWriter _stdOutWriter; + private readonly OutOfProcessTextWriter _stdErrWriter; private Guid _powershellInstanceId; private bool _isDataAckSendPending; diff --git a/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs b/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs index 6c2b64479f4..6ec4f8cd908 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs @@ -55,9 +55,9 @@ internal class PrioritySendDataCollection // these callbacks are used to notify when data becomes available under // suc circumstances. private OnDataAvailableCallback _onDataAvailableCallback; - private SerializedDataStream.OnDataAvailableCallback _onSendCollectionDataAvailable; + private readonly SerializedDataStream.OnDataAvailableCallback _onSendCollectionDataAvailable; private bool _isHandlingCallback; - private object _readSyncObject = new object(); + private readonly object _readSyncObject = new object(); /// /// Callback that is called once a fragmented data is available to send. @@ -291,13 +291,13 @@ internal class ReceiveDataCollection : IDisposable #region tracer [TraceSourceAttribute("Transport", "Traces BaseWSManTransportManager")] - private static PSTraceSource s_baseTracer = PSTraceSource.GetTracer("Transport", "Traces BaseWSManTransportManager"); + private static readonly PSTraceSource s_baseTracer = PSTraceSource.GetTracer("Transport", "Traces BaseWSManTransportManager"); #endregion #region Private Data // fragmentor used to defragment objects added to this collection. - private Fragmentor _defragmentor; + private readonly Fragmentor _defragmentor; // this stream holds incoming data..this stream doesn't know anything // about fragment boundaries. @@ -311,7 +311,7 @@ internal class ReceiveDataCollection : IDisposable // max deserialized object size in bytes private int? _maxReceivedObjectSize; private int _totalReceivedObjectSizeSoFar; - private bool _isCreateByClientTM; + private readonly bool _isCreateByClientTM; // this indicates if any off sync fragments can be ignored // this gets reset (to false) upon receiving the next "start" fragment along the stream @@ -319,7 +319,7 @@ internal class ReceiveDataCollection : IDisposable // objects need to cleanly release resources without // locking entire processing logic. - private object _syncObject; + private readonly object _syncObject; private bool _isDisposed; // holds the number of threads that are currently in // ProcessRawData method. This might happen only for @@ -738,9 +738,9 @@ internal class PriorityReceiveDataCollection : IDisposable { #region Private Data - private Fragmentor _defragmentor; - private ReceiveDataCollection[] _recvdData; - private bool _isCreateByClientTM; + private readonly Fragmentor _defragmentor; + private readonly ReceiveDataCollection[] _recvdData; + private readonly bool _isCreateByClientTM; #endregion diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs index fca6eb12a51..dcea29cbfcf 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs @@ -632,7 +632,7 @@ internal class WSManBinaryOrTextDataStruct /// internal class WSManData_ManToUn : IDisposable { - private WSManDataStruct _internalData; + private readonly WSManDataStruct _internalData; [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private IntPtr _marshalledObject = IntPtr.Zero; [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] @@ -876,7 +876,7 @@ internal static WSManData_UnToMan UnMarshal(IntPtr unmanagedData) [StructLayout(LayoutKind.Sequential)] internal struct WSManDataDWord { - private WSManDataType _type; + private readonly WSManDataType _type; private WSManDWordDataInternal _dwordData; /// @@ -1723,7 +1723,7 @@ internal struct WSManShellAsyncCallback // GC handle which prevents garbage collector from collecting this delegate. private GCHandle _gcHandle; [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] - private IntPtr _asyncCallback; + private readonly IntPtr _asyncCallback; internal WSManShellAsyncCallback(WSManShellCompletionFunction callback) { diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs index 860dcb3ae32..d7b3224179c 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs @@ -127,9 +127,9 @@ internal class WSManPluginInstance { #region Private Members - private Dictionary _activeShellSessions; - private object _syncObject; - private static Dictionary s_activePlugins = new Dictionary(); + private readonly Dictionary _activeShellSessions; + private readonly object _syncObject; + private static readonly Dictionary s_activePlugins = new Dictionary(); /// /// Enables dependency injection after the static constructor is called. diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs index cd77ccedb82..57b84dbb470 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs @@ -169,7 +169,7 @@ internal sealed class WSManPluginEntryDelegates : IDisposable #region Private Members // Holds the delegate pointers in a structure that has identical layout to the native structure. - private WSManPluginEntryDelegatesInternal _unmanagedStruct = new WSManPluginEntryDelegatesInternal(); + private readonly WSManPluginEntryDelegatesInternal _unmanagedStruct = new WSManPluginEntryDelegatesInternal(); internal WSManPluginEntryDelegatesInternal UnmanagedStruct { get { return _unmanagedStruct; } diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs index 9574301f415..8993c0c2419 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs @@ -24,7 +24,7 @@ namespace System.Management.Automation.Remoting /// internal abstract class WSManPluginServerSession : IDisposable { - private object _syncObject; + private readonly object _syncObject; protected bool isClosed; protected bool isContextReported; @@ -400,8 +400,8 @@ internal class WSManPluginShellSession : WSManPluginServerSession { #region Private Members - private Dictionary _activeCommandSessions; - private ServerRemoteSession _remoteSession; + private readonly Dictionary _activeCommandSessions; + private readonly ServerRemoteSession _remoteSession; #endregion @@ -730,7 +730,7 @@ internal class WSManPluginCommandSession : WSManPluginServerSession { #region Private Members - private ServerRemoteSession _remoteSession; + private readonly ServerRemoteSession _remoteSession; #endregion diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginTransportManager.cs index 2c963a69d16..9b195ee6033 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginTransportManager.cs @@ -22,9 +22,9 @@ internal class WSManPluginServerTransportManager : AbstractServerSessionTranspor // the following variables are used to block thread from sending // data to the client until the client sends a receive request. private bool _isRequestPending; - private object _syncObject; - private ManualResetEvent _waitHandle; - private Dictionary _activeCmdTransportManagers; + private readonly object _syncObject; + private readonly ManualResetEvent _waitHandle; + private readonly Dictionary _activeCmdTransportManagers; private bool _isClosed; // used to keep track of last error..this will be used // for reporting operation complete to WSMan. @@ -386,7 +386,7 @@ internal void PerformStop() internal class WSManPluginCommandTransportManager : WSManPluginServerTransportManager { - private WSManPluginServerTransportManager _serverTransportMgr; + private readonly WSManPluginServerTransportManager _serverTransportMgr; private System.Guid _cmdId; // Create Cmd Transport Manager for this sessn transport manager diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs index 76319a5bc5a..71dd3823514 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs @@ -38,7 +38,7 @@ internal static class WSManTransportManagerUtils #region Static Data // Fully qualified error Id modifiers based on transport (WinRM) error codes. - private static Dictionary s_transportErrorCodeToFQEID = new Dictionary() + private static readonly Dictionary s_transportErrorCodeToFQEID = new Dictionary() { {WSManNativeApi.ERROR_WSMAN_ACCESS_DENIED, "AccessDenied"}, {WSManNativeApi.ERROR_WSMAN_OUTOF_MEMORY, "ServerOutOfMemory"}, @@ -332,10 +332,10 @@ internal CompletionEventArgs(CompletionNotification notification) private WSManTransportManagerUtils.tmStartModes _startMode = WSManTransportManagerUtils.tmStartModes.None; - private string _sessionName; + private readonly string _sessionName; // callbacks - private PrioritySendDataCollection.OnDataAvailableCallback _onDataAvailableToSendCallback; + private readonly PrioritySendDataCollection.OnDataAvailableCallback _onDataAvailableToSendCallback; // instance callback handlers private WSManNativeApi.WSManShellAsync _createSessionCallback; @@ -449,7 +449,7 @@ private void ProcessShellData(string data) // This dictionary maintains active session transport managers to be used from various // callbacks. - private static Dictionary s_sessionTMHandles = + private static readonly Dictionary s_sessionTMHandles = new Dictionary(); private static long s_sessionTMSeed; // generate unique session id @@ -495,8 +495,8 @@ private static bool TryGetSessionTransportManager(IntPtr operationContext, #region SHIM: Redirection delegates for test purposes - private static Delegate s_sessionSendRedirect = null; - private static Delegate s_protocolVersionRedirect = null; + private static readonly Delegate s_sessionSendRedirect = null; + private static readonly Delegate s_protocolVersionRedirect = null; #endregion @@ -2592,9 +2592,9 @@ internal class WSManAPIDataCommon : IDisposable private WSManNativeApi.WSManStreamIDSet_ManToUn _outputStreamSet; // Dispose private bool _isDisposed; - private object _syncObject = new object(); + private readonly object _syncObject = new object(); #if !UNIX - private WindowsIdentity _identityToImpersonate; + private readonly WindowsIdentity _identityToImpersonate; #endif /// @@ -2729,7 +2729,7 @@ internal sealed class WSManClientCommandTransportManager : BaseClientCommandTran #region Private Data // operation handles - private IntPtr _wsManShellOperationHandle; + private readonly IntPtr _wsManShellOperationHandle; [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private IntPtr _wsManCmdOperationHandle; [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] @@ -2741,7 +2741,7 @@ internal sealed class WSManClientCommandTransportManager : BaseClientCommandTran // this is used with WSMan callbacks to represent a command transport manager. private long _cmdContextId; - private PrioritySendDataCollection.OnDataAvailableCallback _onDataAvailableToSendCallback; + private readonly PrioritySendDataCollection.OnDataAvailableCallback _onDataAvailableToSendCallback; // should be integrated with receiveDataInitiated private bool _shouldStartReceivingData; @@ -2768,7 +2768,7 @@ internal sealed class WSManClientCommandTransportManager : BaseClientCommandTran // will be sent during subsequent SendOneItem() private SendDataChunk _chunkToSend; - private string _cmdLine; + private readonly string _cmdLine; private readonly WSManClientSessionTransportManager _sessnTm; private class SendDataChunk @@ -2883,7 +2883,7 @@ internal WSManClientCommandTransportManager(WSManConnectionInfo connectionInfo, #region SHIM: Redirection delegate for command code send. - private static Delegate s_commandCodeSendRedirect = null; + private static readonly Delegate s_commandCodeSendRedirect = null; #endregion @@ -3862,7 +3862,7 @@ private void OnDataAvailableCallback(byte[] data, DataPriorityType priorityType) #region SHIM: Redirection delegate for command data send. - private static Delegate s_commandSendRedirect = null; + private static readonly Delegate s_commandSendRedirect = null; #endregion @@ -3990,7 +3990,7 @@ internal override void Dispose(bool isDisposing) // This dictionary maintains active command transport managers to be used from various // callbacks. - private static Dictionary s_cmdTMHandles = + private static readonly Dictionary s_cmdTMHandles = new Dictionary(); private static long s_cmdTMSeed; diff --git a/src/System.Management.Automation/engine/remoting/server/ServerMethodExecutor.cs b/src/System.Management.Automation/engine/remoting/server/ServerMethodExecutor.cs index 0c0fb0a0c42..258ddc8a8e4 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerMethodExecutor.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerMethodExecutor.cs @@ -31,17 +31,17 @@ internal class ServerMethodExecutor /// /// Server dispatch table. /// - private ServerDispatchTable _serverDispatchTable; + private readonly ServerDispatchTable _serverDispatchTable; /// /// Remote host call data type. /// - private RemotingDataType _remoteHostCallDataType; + private readonly RemotingDataType _remoteHostCallDataType; /// /// Transport manager. /// - private AbstractServerTransportManager _transportManager; + private readonly AbstractServerTransportManager _transportManager; /// /// Constructor for ServerMethodExecutor. diff --git a/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs b/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs index b71da3cb5e7..ed66a04a264 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs @@ -23,31 +23,31 @@ internal class ServerPowerShellDriver private bool _extraPowerShellAlreadyScheduled; // extra PowerShell at the server to be run after localPowerShell - private PowerShell _extraPowerShell; + private readonly PowerShell _extraPowerShell; // output buffer for the local PowerShell that is associated with this powershell driver // associated with this powershell data structure handler object to handle all communications with the client - private PSDataCollection _localPowerShellOutput; + private readonly PSDataCollection _localPowerShellOutput; // if the remaining data has been sent to the client before sending state information - private bool[] _datasent = new bool[2]; + private readonly bool[] _datasent = new bool[2]; // sync object for synchronizing sending data to client - private object _syncObject = new object(); + private readonly object _syncObject = new object(); // there is no input when this driver was created - private bool _noInput; - private bool _addToHistory; + private readonly bool _noInput; + private readonly bool _addToHistory; // the server remote host instance // associated with this powershell - private ServerRemoteHost _remoteHost; + private readonly ServerRemoteHost _remoteHost; // apartment state for this powershell - private ApartmentState apartmentState; + private readonly ApartmentState apartmentState; // Handles nested invocation of PS drivers. - private IRSPDriverInvoke _psDriverInvoker; + private readonly IRSPDriverInvoke _psDriverInvoker; #endregion Private Members diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs index 921f9f456f1..737cd512296 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs @@ -20,12 +20,12 @@ internal class ServerRemoteHost : PSHost, IHostSupportsInteractiveSession /// /// Remote host user interface. /// - private ServerRemoteHostUserInterface _remoteHostUserInterface; + private readonly ServerRemoteHostUserInterface _remoteHostUserInterface; /// /// Server method executor. /// - private ServerMethodExecutor _serverMethodExecutor; + private readonly ServerMethodExecutor _serverMethodExecutor; /// /// Client runspace pool id. @@ -45,7 +45,7 @@ internal class ServerRemoteHost : PSHost, IHostSupportsInteractiveSession /// /// ServerDriverRemoteHost. /// - private ServerDriverRemoteHost _serverDriverRemoteHost; + private readonly ServerDriverRemoteHost _serverDriverRemoteHost; #endregion diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs index 5fe393171d3..911f2495805 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs @@ -17,12 +17,12 @@ internal class ServerRemoteHostRawUserInterface : PSHostRawUserInterface /// /// Remote host user interface. /// - private ServerRemoteHostUserInterface _remoteHostUserInterface; + private readonly ServerRemoteHostUserInterface _remoteHostUserInterface; /// /// Server method executor. /// - private ServerMethodExecutor _serverMethodExecutor; + private readonly ServerMethodExecutor _serverMethodExecutor; /// /// Host default data. diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostUserInterface.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostUserInterface.cs index 89a5ef97569..314fc25587f 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostUserInterface.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostUserInterface.cs @@ -20,7 +20,7 @@ internal class ServerRemoteHostUserInterface : PSHostUserInterface, IHostUISuppo /// /// Server method executor. /// - private ServerMethodExecutor _serverMethodExecutor; + private readonly ServerMethodExecutor _serverMethodExecutor; /// /// Constructor for ServerRemoteHostUserInterface. diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs index 15dc8654f88..bd1f48d7571 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs @@ -413,12 +413,12 @@ private void HandleRemoveAssociation(object sender, EventArgs e) // transport manager using which this // runspace pool driver handles all client // communication - private AbstractServerSessionTransportManager _transportManager; - private Dictionary _associatedShells + private readonly AbstractServerSessionTransportManager _transportManager; + private readonly Dictionary _associatedShells = new Dictionary(); // powershell data structure handlers associated with this // runspace pool data structure handler - private object _associationSyncObject = new object(); + private readonly object _associationSyncObject = new object(); // object to synchronize operations to above #endregion Private Members @@ -434,10 +434,10 @@ internal class ServerPowerShellDataStructureHandler // transport manager using which this // powershell driver handles all client // communication - private AbstractServerTransportManager _transportManager; + private readonly AbstractServerTransportManager _transportManager; private Guid _clientRunspacePoolId; private Guid _clientPowerShellId; - private RemoteStreamOptions _streamSerializationOptions; + private readonly RemoteStreamOptions _streamSerializationOptions; private Runspace _rsUsedToInvokePowerShell; #endregion Private Members diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs index 8aff9264d0b..fbd1fe548b4 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs @@ -49,7 +49,7 @@ internal class ServerRunspacePoolDriver : IRSPDriverInvoke private readonly string _initialLocation; // Script to run after a RunspacePool/Runspace is created in this session. - private ConfigurationDataFromXML _configData; + private readonly ConfigurationDataFromXML _configData; // application private data to send back to the client in when we get into "opened" state private PSPrimitiveDictionary _applicationPrivateData; @@ -61,35 +61,35 @@ internal class ServerRunspacePoolDriver : IRSPDriverInvoke // with the client // powershell's associated with this runspace pool - private Dictionary _associatedShells + private readonly Dictionary _associatedShells = new Dictionary(); // remote host associated with this runspacepool - private ServerDriverRemoteHost _remoteHost; + private readonly ServerDriverRemoteHost _remoteHost; private bool _isClosed; // server capability reported to the client during negotiation (not the actual capability) - private RemoteSessionCapability _serverCapability; + private readonly RemoteSessionCapability _serverCapability; private Runspace _rsToUseForSteppablePipeline; // steppable pipeline event subscribers exist per-session - private ServerSteppablePipelineSubscriber _eventSubscriber = new ServerSteppablePipelineSubscriber(); + private readonly ServerSteppablePipelineSubscriber _eventSubscriber = new ServerSteppablePipelineSubscriber(); private PSDataCollection _inputCollection; // PowerShell driver input collection // Object to invoke nested PowerShell drivers on single pipeline worker thread. - private PowerShellDriverInvoker _driverNestedInvoker; + private readonly PowerShellDriverInvoker _driverNestedInvoker; // Remote wrapper for script debugger. private ServerRemoteDebugger _serverRemoteDebugger; // Version of PowerShell client. - private Version _clientPSVersion; + private readonly Version _clientPSVersion; // Optional endpoint configuration name. // Used in OutOfProc scenarios that do not support PSSession endpoint configuration. // Results in a configured remote runspace pushed onto driver host. - private string _configurationName; + private readonly string _configurationName; /// /// Event that get raised when the RunspacePool is closed. @@ -954,7 +954,7 @@ private void HandleCreateAndInvokePowerShell(object _, RemoteDataEventArgs _invokePumpStack; + private readonly ConcurrentStack _invokePumpStack; #endregion @@ -1700,9 +1700,9 @@ public void PopInvoker() /// private sealed class InvokePump { - private Queue _driverInvokeQueue; - private ManualResetEvent _processDrivers; - private object _syncObject; + private readonly Queue _driverInvokeQueue; + private readonly ManualResetEvent _processDrivers; + private readonly object _syncObject; private bool _stopPump; private bool _isDisposed; @@ -1812,9 +1812,9 @@ internal sealed class ServerRemoteDebugger : Debugger, IDisposable { #region Private Members - private IRSPDriverInvoke _driverInvoker; - private Runspace _runspace; - private ObjectRef _wrappedDebugger; + private readonly IRSPDriverInvoke _driverInvoker; + private readonly Runspace _runspace; + private readonly ObjectRef _wrappedDebugger; private bool _inDebugMode; private DebuggerStopEventArgs _debuggerStopEventArgs; @@ -2258,10 +2258,10 @@ public void Dispose() private sealed class ThreadCommandProcessing { // Members - private ManualResetEventSlim _commandCompleteEvent; - private Debugger _wrappedDebugger; - private PSCommand _command; - private PSDataCollection _output; + private readonly ManualResetEventSlim _commandCompleteEvent; + private readonly Debugger _wrappedDebugger; + private readonly PSCommand _command; + private readonly PSDataCollection _output; private DebuggerCommandResults _results; private Exception _exception; #if !UNIX diff --git a/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineDriver.cs b/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineDriver.cs index 9b86ac8c5ca..01745457c46 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineDriver.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineDriver.cs @@ -16,7 +16,7 @@ namespace System.Management.Automation /// internal class ExecutionContextForStepping : IDisposable { - private ExecutionContext _executionContext; + private readonly ExecutionContext _executionContext; private PSInformationalBuffers _originalInformationalBuffers; private PSHost _originalHost; @@ -72,13 +72,13 @@ internal class ServerSteppablePipelineDriver // information // data to client // was created - private bool _addToHistory; + private readonly bool _addToHistory; // associated with this powershell - private ApartmentState apartmentState; // apartment state for this powershell + private readonly ApartmentState apartmentState; // apartment state for this powershell // pipeline that runs the actual command. - private ServerSteppablePipelineSubscriber _eventSubscriber; - private PSDataCollection _powershellInput; // input collection of the PowerShell pipeline + private readonly ServerSteppablePipelineSubscriber _eventSubscriber; + private readonly PSDataCollection _powershellInput; // input collection of the PowerShell pipeline #endregion diff --git a/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineSubscriber.cs b/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineSubscriber.cs index 850993cf162..556d71e2a9b 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineSubscriber.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineSubscriber.cs @@ -29,7 +29,7 @@ internal class ServerSteppablePipelineSubscriber { #region Private data - private object _syncObject = new object(); + private readonly object _syncObject = new object(); private bool _initialized = false; private PSLocalEventManager _eventManager; private PSEventSubscriber _startSubscriber; diff --git a/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs b/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs index e6520a9d389..49827b91c05 100644 --- a/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs +++ b/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs @@ -70,11 +70,11 @@ internal ServerRemoteSessionContext() internal class ServerRemoteSession : RemoteSession { [TraceSourceAttribute("ServerRemoteSession", "ServerRemoteSession")] - private static PSTraceSource s_trace = PSTraceSource.GetTracer("ServerRemoteSession", "ServerRemoteSession"); + private static readonly PSTraceSource s_trace = PSTraceSource.GetTracer("ServerRemoteSession", "ServerRemoteSession"); - private PSSenderInfo _senderInfo; - private string _configProviderId; - private string _initParameters; + private readonly PSSenderInfo _senderInfo; + private readonly string _configProviderId; + private readonly string _initParameters; private string _initScriptForOutOfProcRS; private PSSessionConfiguration _sessionConfigProvider; @@ -83,7 +83,7 @@ internal class ServerRemoteSession : RemoteSession private int? _maxRecvdDataSizeCommand; private ServerRunspacePoolDriver _runspacePoolDriver; - private PSRemotingCryptoHelperServer _cryptoHelper; + private readonly PSRemotingCryptoHelperServer _cryptoHelper; // Specifies an optional endpoint configuration for out-of-proc session use. // Creates a pushed remote runspace session created with this configuration name. diff --git a/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs b/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs index 27bd41330f1..98fd8884503 100644 --- a/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs +++ b/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs @@ -32,11 +32,11 @@ namespace System.Management.Automation.Remoting internal class ServerRemoteSessionDSHandlerStateMachine { [TraceSourceAttribute("ServerRemoteSessionDSHandlerStateMachine", "ServerRemoteSessionDSHandlerStateMachine")] - private static PSTraceSource s_trace = PSTraceSource.GetTracer("ServerRemoteSessionDSHandlerStateMachine", "ServerRemoteSessionDSHandlerStateMachine"); + private static readonly PSTraceSource s_trace = PSTraceSource.GetTracer("ServerRemoteSessionDSHandlerStateMachine", "ServerRemoteSessionDSHandlerStateMachine"); - private ServerRemoteSession _session; - private object _syncObject; - private Queue _processPendingEventsQueue + private readonly ServerRemoteSession _session; + private readonly object _syncObject; + private readonly Queue _processPendingEventsQueue = new Queue(); // whether some thread is actively processing events // in a loop. If this is set then other threads @@ -46,7 +46,7 @@ private Queue _processPendingEventsQueue // and processed private bool _eventsInProcess = false; - private EventHandler[,] _stateMachineHandle; + private readonly EventHandler[,] _stateMachineHandle; private RemoteSessionState _state; /// diff --git a/src/System.Management.Automation/engine/remoting/server/serverremotingprotocolimplementation.cs b/src/System.Management.Automation/engine/remoting/server/serverremotingprotocolimplementation.cs index 653299e2cbb..1679831a477 100644 --- a/src/System.Management.Automation/engine/remoting/server/serverremotingprotocolimplementation.cs +++ b/src/System.Management.Automation/engine/remoting/server/serverremotingprotocolimplementation.cs @@ -12,9 +12,9 @@ namespace System.Management.Automation.Remoting /// internal class ServerRemoteSessionDSHandlerImpl : ServerRemoteSessionDataStructureHandler { - private AbstractServerSessionTransportManager _transportManager; - private ServerRemoteSessionDSHandlerStateMachine _stateMachine; - private ServerRemoteSession _session; + private readonly AbstractServerSessionTransportManager _transportManager; + private readonly ServerRemoteSessionDSHandlerStateMachine _stateMachine; + private readonly ServerRemoteSession _session; internal override AbstractServerSessionTransportManager TransportManager { diff --git a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs index 2341dca4042..4457b2dcd38 100644 --- a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs +++ b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs @@ -1713,11 +1713,11 @@ private static bool GetAndValidateEncryptionRecipients( return true; } - private static object s_syncObject = new object(); + private static readonly object s_syncObject = new object(); private static string s_lastSeenCertificate = string.Empty; private static bool s_hasProcessedCertificate = false; private static CmsMessageRecipient[] s_encryptionRecipients = null; - private static Lazy s_sbLoggingSettingCache = new Lazy( + private static readonly Lazy s_sbLoggingSettingCache = new Lazy( () => Utils.GetPolicySetting(Utils.SystemWideThenCurrentUserConfig), isThreadSafe: true); @@ -2181,7 +2181,7 @@ internal sealed class PSScriptCmdlet : PSCmdlet, IDynamicParameters, IDisposable private readonly bool _fromScriptFile; private readonly bool _useLocalScope; private readonly bool _runOptimized; - private bool _rethrowExitException; + private readonly bool _rethrowExitException; private MshCommandRuntime _commandRuntime; private readonly MutableTuple _localsTuple; private bool _exitWasCalled; diff --git a/src/System.Management.Automation/engine/serialization.cs b/src/System.Management.Automation/engine/serialization.cs index ddc44bd8970..a26d0e66b42 100644 --- a/src/System.Management.Automation/engine/serialization.cs +++ b/src/System.Management.Automation/engine/serialization.cs @@ -174,7 +174,7 @@ public static object[] DeserializeAsList(string source) /// /// Default depth of serialization. /// - private static int s_mshDefaultSerializationDepth = 1; + private static readonly int s_mshDefaultSerializationDepth = 1; } /// @@ -1543,7 +1543,7 @@ int depth _writer.WriteEndElement(); } - private static Lazy s_cimSerializer = new Lazy(CimSerializer.Create); + private static readonly Lazy s_cimSerializer = new Lazy(CimSerializer.Create); private void PrepareCimInstanceForSerialization(PSObject psObject, CimInstance cimInstance) { @@ -3004,7 +3004,7 @@ internal InternalDeserializer(XmlReader reader, DeserializationContext context) #region Known CIMTypes - private static Lazy> s_knownCimArrayTypes = new Lazy>( + private static readonly Lazy> s_knownCimArrayTypes = new Lazy>( () => new HashSet { @@ -3296,7 +3296,7 @@ private bool RehydrateCimInstanceProperty( return true; } - private static Lazy s_cimDeserializer = new Lazy(CimDeserializer.Create); + private static readonly Lazy s_cimDeserializer = new Lazy(CimDeserializer.Create); private CimClass RehydrateCimClass(PSPropertyInfo classMetadataProperty) { diff --git a/src/System.Management.Automation/help/AliasHelpInfo.cs b/src/System.Management.Automation/help/AliasHelpInfo.cs index b51d1b192dc..57cb7fdd184 100644 --- a/src/System.Management.Automation/help/AliasHelpInfo.cs +++ b/src/System.Management.Automation/help/AliasHelpInfo.cs @@ -70,7 +70,7 @@ internal override HelpCategory HelpCategory } } - private PSObject _fullHelpObject; + private readonly PSObject _fullHelpObject; /// /// Returns full help object for alias help. diff --git a/src/System.Management.Automation/help/AliasHelpProvider.cs b/src/System.Management.Automation/help/AliasHelpProvider.cs index db7e4056d1e..1705b9bafa5 100644 --- a/src/System.Management.Automation/help/AliasHelpProvider.cs +++ b/src/System.Management.Automation/help/AliasHelpProvider.cs @@ -40,7 +40,7 @@ internal AliasHelpProvider(HelpSystem helpSystem) : base(helpSystem) /// of wildcard search patterns. This is currently not achievable /// through _commandDiscovery. /// - private SessionState _sessionState; + private readonly SessionState _sessionState; /// /// Command Discovery object for current session. @@ -50,7 +50,7 @@ internal AliasHelpProvider(HelpSystem helpSystem) : base(helpSystem) /// The AliasInfo object returned from _commandDiscovery is essential /// in creating AliasHelpInfo. /// - private CommandDiscovery _commandDiscovery; + private readonly CommandDiscovery _commandDiscovery; #region Common Properties diff --git a/src/System.Management.Automation/help/CabinetAPI.cs b/src/System.Management.Automation/help/CabinetAPI.cs index 41a83010f58..0b90cd5c35b 100644 --- a/src/System.Management.Automation/help/CabinetAPI.cs +++ b/src/System.Management.Automation/help/CabinetAPI.cs @@ -80,7 +80,7 @@ internal abstract class ICabinetExtractorLoader /// internal class CabinetExtractorFactory { - private static ICabinetExtractorLoader s_cabinetLoader; + private static readonly ICabinetExtractorLoader s_cabinetLoader; internal static ICabinetExtractor EmptyExtractor = new EmptyCabinetExtractor(); /// diff --git a/src/System.Management.Automation/help/CommandHelpProvider.cs b/src/System.Management.Automation/help/CommandHelpProvider.cs index e89bbcc40c4..3844398b629 100644 --- a/src/System.Management.Automation/help/CommandHelpProvider.cs +++ b/src/System.Management.Automation/help/CommandHelpProvider.cs @@ -48,7 +48,7 @@ static CommandHelpProvider() s_engineModuleHelpFileCache.Add("Microsoft.WSMan.Management", "Microsoft.Wsman.Management.dll-Help.xml"); } - private static Dictionary s_engineModuleHelpFileCache = new Dictionary(); + private static readonly Dictionary s_engineModuleHelpFileCache = new Dictionary(); private readonly ExecutionContext _context; diff --git a/src/System.Management.Automation/help/HelpCategoryInvalidException.cs b/src/System.Management.Automation/help/HelpCategoryInvalidException.cs index 194160ad5e2..75cb2c41005 100644 --- a/src/System.Management.Automation/help/HelpCategoryInvalidException.cs +++ b/src/System.Management.Automation/help/HelpCategoryInvalidException.cs @@ -72,7 +72,7 @@ public ErrorRecord ErrorRecord } } - private string _helpCategory = System.Management.Automation.HelpCategory.None.ToString(); + private readonly string _helpCategory = System.Management.Automation.HelpCategory.None.ToString(); /// /// Gets name of the help category that is invalid. diff --git a/src/System.Management.Automation/help/HelpCommands.cs b/src/System.Management.Automation/help/HelpCommands.cs index 852db86c267..5f4f1a4234f 100644 --- a/src/System.Management.Automation/help/HelpCommands.cs +++ b/src/System.Management.Automation/help/HelpCommands.cs @@ -68,7 +68,7 @@ public GetHelpCommand() IgnoreCase = true)] public string[] Category { get; set; } - private string _provider = string.Empty; + private readonly string _provider = string.Empty; /// /// Changes the view of HelpObject returned. @@ -723,7 +723,7 @@ internal static void VerifyParameterForbiddenInRemoteRunspace(Cmdlet cmdlet, str #region trace [TraceSourceAttribute("GetHelpCommand ", "GetHelpCommand ")] - private static PSTraceSource s_tracer = PSTraceSource.GetTracer("GetHelpCommand ", "GetHelpCommand "); + private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("GetHelpCommand ", "GetHelpCommand "); #endregion } diff --git a/src/System.Management.Automation/help/HelpCommentsParser.cs b/src/System.Management.Automation/help/HelpCommentsParser.cs index 62cbfdd9557..f838b5d6f9a 100644 --- a/src/System.Management.Automation/help/HelpCommentsParser.cs +++ b/src/System.Management.Automation/help/HelpCommentsParser.cs @@ -61,10 +61,10 @@ private HelpCommentsParser(CommandInfo commandInfo, List parameterDescri private readonly List _links = new List(); internal bool isExternalHelpSet = false; - private ScriptBlock _scriptBlock; - private CommandMetadata _commandMetadata; - private string _commandName; - private List _parameterDescriptions; + private readonly ScriptBlock _scriptBlock; + private readonly CommandMetadata _commandMetadata; + private readonly string _commandName; + private readonly List _parameterDescriptions; private XmlDocument _doc; internal static readonly string mshURI = "http://msh"; internal static readonly string mamlURI = "http://schemas.microsoft.com/maml/2004/10"; diff --git a/src/System.Management.Automation/help/HelpErrorTracer.cs b/src/System.Management.Automation/help/HelpErrorTracer.cs index 7437e5cc7dd..e69b6791d0f 100644 --- a/src/System.Management.Automation/help/HelpErrorTracer.cs +++ b/src/System.Management.Automation/help/HelpErrorTracer.cs @@ -52,12 +52,12 @@ internal class HelpErrorTracer internal sealed class TraceFrame : IDisposable { // Following are help context information - private string _helpFile = string.Empty; + private readonly string _helpFile = string.Empty; // ErrorRecords accumulated during the help content loading. - private Collection _errors = new Collection(); + private readonly Collection _errors = new Collection(); - private HelpErrorTracer _helpTracer; + private readonly HelpErrorTracer _helpTracer; /// /// Constructor. Here help context information will be collected. /// diff --git a/src/System.Management.Automation/help/HelpFileHelpInfo.cs b/src/System.Management.Automation/help/HelpFileHelpInfo.cs index 1df1b70411b..adb2afac47f 100644 --- a/src/System.Management.Automation/help/HelpFileHelpInfo.cs +++ b/src/System.Management.Automation/help/HelpFileHelpInfo.cs @@ -50,8 +50,8 @@ private HelpFileHelpInfo(string name, string text, string filename) /// Name for the help info internal override string Name { get; } = string.Empty; - private string _filename = string.Empty; - private string _synopsis = string.Empty; + private readonly string _filename = string.Empty; + private readonly string _synopsis = string.Empty; /// /// Synopsis for the help info. /// diff --git a/src/System.Management.Automation/help/HelpFileHelpProvider.cs b/src/System.Management.Automation/help/HelpFileHelpProvider.cs index 2c527d2f95a..d00cd0cdfc0 100644 --- a/src/System.Management.Automation/help/HelpFileHelpProvider.cs +++ b/src/System.Management.Automation/help/HelpFileHelpProvider.cs @@ -415,7 +415,7 @@ internal override void Reset() /// /// This will avoid one help file getting loaded again and again. /// - private Hashtable _helpFiles = new Hashtable(); + private readonly Hashtable _helpFiles = new Hashtable(); #endregion } diff --git a/src/System.Management.Automation/help/HelpNotFoundException.cs b/src/System.Management.Automation/help/HelpNotFoundException.cs index e6dc7a21ee4..ecede69799a 100644 --- a/src/System.Management.Automation/help/HelpNotFoundException.cs +++ b/src/System.Management.Automation/help/HelpNotFoundException.cs @@ -77,7 +77,7 @@ public ErrorRecord ErrorRecord } } - private string _helpTopic = string.Empty; + private readonly string _helpTopic = string.Empty; /// /// Gets help topic for which help is not found. diff --git a/src/System.Management.Automation/help/HelpProvider.cs b/src/System.Management.Automation/help/HelpProvider.cs index 66a7ab1ab95..95119d88b90 100644 --- a/src/System.Management.Automation/help/HelpProvider.cs +++ b/src/System.Management.Automation/help/HelpProvider.cs @@ -50,7 +50,7 @@ internal HelpProvider(HelpSystem helpSystem) _helpSystem = helpSystem; } - private HelpSystem _helpSystem; + private readonly HelpSystem _helpSystem; internal HelpSystem HelpSystem { diff --git a/src/System.Management.Automation/help/HelpProviderWithCache.cs b/src/System.Management.Automation/help/HelpProviderWithCache.cs index 99dc3fa7a19..495ec6a0b5d 100644 --- a/src/System.Management.Automation/help/HelpProviderWithCache.cs +++ b/src/System.Management.Automation/help/HelpProviderWithCache.cs @@ -28,7 +28,7 @@ internal HelpProviderWithCache(HelpSystem helpSystem) : base(helpSystem) /// /// This hashtable is made case-insensitive so that helpInfo can be retrieved case insensitively. /// - private Hashtable _helpCache = new Hashtable(StringComparer.OrdinalIgnoreCase); + private readonly Hashtable _helpCache = new Hashtable(StringComparer.OrdinalIgnoreCase); /// /// Exact match help for a target. diff --git a/src/System.Management.Automation/help/HelpSystem.cs b/src/System.Management.Automation/help/HelpSystem.cs index fb92ed1c19c..7743f08609e 100644 --- a/src/System.Management.Automation/help/HelpSystem.cs +++ b/src/System.Management.Automation/help/HelpSystem.cs @@ -103,7 +103,7 @@ internal HelpSystem(ExecutionContext context) Initialize(); } - private ExecutionContext _executionContext; + private readonly ExecutionContext _executionContext; /// /// ExecutionContext for the help system. Different help providers @@ -173,7 +173,7 @@ internal IEnumerable GetHelp(HelpRequest helpRequest) #region Error Handling - private Collection _lastErrors = new Collection(); + private readonly Collection _lastErrors = new Collection(); /// /// This is for tracking the last set of errors happened during the help @@ -540,7 +540,7 @@ private IEnumerable SearchHelp(HelpRequest helpRequest) #region Help Provider Manager - private ArrayList _helpProviders = new ArrayList(); + private readonly ArrayList _helpProviders = new ArrayList(); /// /// Return the list of help providers initialized. diff --git a/src/System.Management.Automation/help/MUIFileSearcher.cs b/src/System.Management.Automation/help/MUIFileSearcher.cs index 2101e268dc1..bc506284c9b 100644 --- a/src/System.Management.Automation/help/MUIFileSearcher.cs +++ b/src/System.Management.Automation/help/MUIFileSearcher.cs @@ -86,7 +86,7 @@ internal Collection Result /// _uniqueMatches is used to track matches already found during the search process. /// This is useful for ignoring duplicates in the case of unique search. /// - private Hashtable _uniqueMatches = new Hashtable(StringComparer.OrdinalIgnoreCase); + private readonly Hashtable _uniqueMatches = new Hashtable(StringComparer.OrdinalIgnoreCase); /// /// Search for files using the target, searchPaths member of this class. diff --git a/src/System.Management.Automation/help/MamlClassHelpInfo.cs b/src/System.Management.Automation/help/MamlClassHelpInfo.cs index 002eecb3bfe..042ab21e703 100644 --- a/src/System.Management.Automation/help/MamlClassHelpInfo.cs +++ b/src/System.Management.Automation/help/MamlClassHelpInfo.cs @@ -42,7 +42,7 @@ private MamlClassHelpInfo(XmlNode xmlNode, HelpCategory helpCategory) /// /// PSObject representation on help. /// - private PSObject _fullHelpObject; + private readonly PSObject _fullHelpObject; #region Load diff --git a/src/System.Management.Automation/help/MamlCommandHelpInfo.cs b/src/System.Management.Automation/help/MamlCommandHelpInfo.cs index 998e647cd05..774ef1fc1c0 100644 --- a/src/System.Management.Automation/help/MamlCommandHelpInfo.cs +++ b/src/System.Management.Automation/help/MamlCommandHelpInfo.cs @@ -98,7 +98,7 @@ internal void OverrideProviderSpecificHelpWithGenericHelp(HelpInfo genericHelpIn #region Basic Help Properties - private PSObject _fullHelpObject; + private readonly PSObject _fullHelpObject; /// /// Full help object for this help item. diff --git a/src/System.Management.Automation/help/MamlNode.cs b/src/System.Management.Automation/help/MamlNode.cs index 712dc2325ea..3be86db5915 100644 --- a/src/System.Management.Automation/help/MamlNode.cs +++ b/src/System.Management.Automation/help/MamlNode.cs @@ -74,7 +74,7 @@ internal MamlNode(XmlNode xmlNode) _xmlNode = xmlNode; } - private XmlNode _xmlNode; + private readonly XmlNode _xmlNode; /// /// Underline xmlNode for this MamlNode object. diff --git a/src/System.Management.Automation/help/ProviderCommandHelpInfo.cs b/src/System.Management.Automation/help/ProviderCommandHelpInfo.cs index 6d9bedf4fac..d51fb716b82 100644 --- a/src/System.Management.Automation/help/ProviderCommandHelpInfo.cs +++ b/src/System.Management.Automation/help/ProviderCommandHelpInfo.cs @@ -13,7 +13,7 @@ internal class ProviderCommandHelpInfo : HelpInfo /// /// Help info. /// - private HelpInfo _helpInfo; + private readonly HelpInfo _helpInfo; /// /// Constructor for ProviderCommandHelpInfo. diff --git a/src/System.Management.Automation/help/ProviderHelpInfo.cs b/src/System.Management.Automation/help/ProviderHelpInfo.cs index 39eebe0c23a..e159892a73e 100644 --- a/src/System.Management.Automation/help/ProviderHelpInfo.cs +++ b/src/System.Management.Automation/help/ProviderHelpInfo.cs @@ -136,7 +136,7 @@ internal override HelpCategory HelpCategory } } - private PSObject _fullHelpObject; + private readonly PSObject _fullHelpObject; /// /// Full help object for this provider help info. diff --git a/src/System.Management.Automation/help/RemoteHelpInfo.cs b/src/System.Management.Automation/help/RemoteHelpInfo.cs index a80ba7a7736..1aa113dd86b 100644 --- a/src/System.Management.Automation/help/RemoteHelpInfo.cs +++ b/src/System.Management.Automation/help/RemoteHelpInfo.cs @@ -13,7 +13,7 @@ namespace System.Management.Automation /// internal class RemoteHelpInfo : BaseCommandHelpInfo { - private PSObject _deserializedRemoteHelp; + private readonly PSObject _deserializedRemoteHelp; internal RemoteHelpInfo( ExecutionContext context, diff --git a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs index 16ac4f2a58e..0251ed31d60 100644 --- a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs +++ b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs @@ -31,7 +31,7 @@ public class UpdatableHelpCommandBase : PSCmdlet internal bool _stopping; internal int activityId; - private Dictionary _exceptions; + private readonly Dictionary _exceptions; #region Parameters @@ -161,7 +161,7 @@ private void HandleProgressChanged(object sender, UpdatableHelpProgressEventArgs #region Constructor - private static Dictionary s_metadataCache; + private static readonly Dictionary s_metadataCache; /// /// Static constructor diff --git a/src/System.Management.Automation/help/UpdatableHelpSystem.cs b/src/System.Management.Automation/help/UpdatableHelpSystem.cs index 6bdac0afaf8..ce350e979ce 100644 --- a/src/System.Management.Automation/help/UpdatableHelpSystem.cs +++ b/src/System.Management.Automation/help/UpdatableHelpSystem.cs @@ -233,12 +233,12 @@ internal UpdatableHelpProgressEventArgs(string moduleName, UpdatableHelpCommandT /// internal class UpdatableHelpSystem : IDisposable { - private TimeSpan _defaultTimeout; - private Collection _progressEvents; + private readonly TimeSpan _defaultTimeout; + private readonly Collection _progressEvents; private bool _stopping; - private object _syncObject; - private UpdatableHelpCommandBase _cmdlet; - private CancellationTokenSource _cancelTokenSource; + private readonly object _syncObject; + private readonly UpdatableHelpCommandBase _cmdlet; + private readonly CancellationTokenSource _cancelTokenSource; internal WebClient WebClient { get; } @@ -1578,8 +1578,8 @@ private void HandleDownloadProgressChanged(object sender, DownloadProgressChange /// internal class UpdatableHelpSystemDrive : IDisposable { - private string _driveName; - private PSCmdlet _cmdlet; + private readonly string _driveName; + private readonly PSCmdlet _cmdlet; /// /// Gets the drive name. diff --git a/src/System.Management.Automation/logging/MshLog.cs b/src/System.Management.Automation/logging/MshLog.cs index 9ebdb699e40..5f4c2b3b885 100644 --- a/src/System.Management.Automation/logging/MshLog.cs +++ b/src/System.Management.Automation/logging/MshLog.cs @@ -60,13 +60,13 @@ internal static class MshLog /// The value of this dictionary is never empty. A value of type DummyProvider means /// no logging. /// - private static ConcurrentDictionary> s_logProviders = + private static readonly ConcurrentDictionary> s_logProviders = new ConcurrentDictionary>(); private const string _crimsonLogProviderAssemblyName = "MshCrimsonLog"; private const string _crimsonLogProviderTypeName = "System.Management.Automation.Logging.CrimsonLogProvider"; - private static Collection s_ignoredCommands = new Collection(); + private static readonly Collection s_ignoredCommands = new Collection(); /// /// Static constructor. diff --git a/src/System.Management.Automation/namespaces/CoreCommandContext.cs b/src/System.Management.Automation/namespaces/CoreCommandContext.cs index 4c571a6fb73..56d8688749d 100644 --- a/src/System.Management.Automation/namespaces/CoreCommandContext.cs +++ b/src/System.Management.Automation/namespaces/CoreCommandContext.cs @@ -32,7 +32,7 @@ internal sealed class CmdletProviderContext [Dbg.TraceSourceAttribute( "CmdletProviderContext", "The context under which a core command is being run.")] - private static Dbg.PSTraceSource s_tracer = + private static readonly Dbg.PSTraceSource s_tracer = Dbg.PSTraceSource.GetTracer("CmdletProviderContext", "The context under which a core command is being run."); @@ -295,12 +295,12 @@ internal CmdletProviderContext( /// If the constructor that takes a context to copy is /// called, this will be set to the context being copied. /// - private CmdletProviderContext _copiedContext; + private readonly CmdletProviderContext _copiedContext; /// /// The credentials under which the operation should run. /// - private PSCredential _credentials = PSCredential.Empty; + private readonly PSCredential _credentials = PSCredential.Empty; /// /// The force parameter gives guidance to providers on how vigorously they @@ -313,7 +313,7 @@ internal CmdletProviderContext( /// made visible to anyone and should only be set through the /// constructor. /// - private Cmdlet _command; + private readonly Cmdlet _command; /// /// This makes the origin of the provider request visible to the internals. @@ -328,7 +328,7 @@ internal CmdletProviderContext( /// If it is false, the objects will be accumulated until the /// GetErrorObjects method is called. /// - private bool _streamErrors; + private readonly bool _streamErrors; /// /// A collection in which objects that are written using the WriteObject(s) diff --git a/src/System.Management.Automation/namespaces/FileSystemContentStream.cs b/src/System.Management.Automation/namespaces/FileSystemContentStream.cs index da2d708aa99..9186e10f8ad 100644 --- a/src/System.Management.Automation/namespaces/FileSystemContentStream.cs +++ b/src/System.Management.Automation/namespaces/FileSystemContentStream.cs @@ -38,31 +38,31 @@ internal class FileSystemContentReaderWriter : IContentReader, IContentWriter [Dbg.TraceSourceAttribute( "FileSystemContentStream", "The provider content reader and writer for the file system")] - private static Dbg.PSTraceSource s_tracer = + private static readonly Dbg.PSTraceSource s_tracer = Dbg.PSTraceSource.GetTracer("FileSystemContentStream", "The provider content reader and writer for the file system"); #endregion tracer - private string _path; - private string _streamName; - private FileMode _mode; - private FileAccess _access; - private FileShare _share; - private Encoding _encoding; - private CmdletProvider _provider; + private readonly string _path; + private readonly string _streamName; + private readonly FileMode _mode; + private readonly FileAccess _access; + private readonly FileShare _share; + private readonly Encoding _encoding; + private readonly CmdletProvider _provider; private FileStream _stream; private StreamReader _reader; private StreamWriter _writer; - private bool _usingByteEncoding; + private readonly bool _usingByteEncoding; private const char DefaultDelimiter = '\n'; - private string _delimiter = $"{DefaultDelimiter}"; - private int[] _offsetDictionary; - private bool _usingDelimiter; - private StringBuilder _currentLineContent; + private readonly string _delimiter = $"{DefaultDelimiter}"; + private readonly int[] _offsetDictionary; + private readonly bool _usingDelimiter; + private readonly StringBuilder _currentLineContent; private bool _waitForChanges; - private bool _isRawStream; + private readonly bool _isRawStream; private long _fileOffset; private FileAttributes _oldAttributes; @@ -73,7 +73,7 @@ internal class FileSystemContentReaderWriter : IContentReader, IContentWriter private bool _alreadyDetectEncoding = false; // False to add a newline to the end of the output string, true if not. - private bool _suppressNewline = false; + private readonly bool _suppressNewline = false; /// /// Constructor for the content stream. diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 23706ab1e05..089b029fffa 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -66,7 +66,7 @@ public sealed partial class FileSystemProvider : NavigationCmdletProvider, /// using "FileSystemProvider" as the category. /// [Dbg.TraceSourceAttribute("FileSystemProvider", "The namespace navigation provider for the file system")] - private static Dbg.PSTraceSource s_tracer = + private static readonly Dbg.PSTraceSource s_tracer = Dbg.PSTraceSource.GetTracer("FileSystemProvider", "The namespace navigation provider for the file system"); /// @@ -83,7 +83,7 @@ public FileSystemProvider() } private Collection _excludeMatcher = null; - private static System.IO.EnumerationOptions _enumerationOptions = new System.IO.EnumerationOptions + private static readonly System.IO.EnumerationOptions _enumerationOptions = new System.IO.EnumerationOptions { MatchType = MatchType.Win32, MatchCasing = MatchCasing.CaseInsensitive, @@ -7323,7 +7323,7 @@ private struct NetResource /// private class InodeTracker { - private HashSet<(UInt64, UInt64)> _visitations; + private readonly HashSet<(UInt64, UInt64)> _visitations; /// /// Construct a new InodeTracker with an initial path. @@ -8750,9 +8750,9 @@ internal static class CopyFileRemoteUtils #region PSCopyToSessionHelper internal const string PSCopyToSessionHelperName = @"PSCopyToSessionHelper"; - private static string s_driveMaxSizeErrorFormatString = FileSystemProviderStrings.DriveMaxSizeError; - private static string s_PSCopyToSessionHelperDefinition = StringUtil.Format(PSCopyToSessionHelperDefinitionFormat, @"[ValidateNotNullOrEmpty()]", s_driveMaxSizeErrorFormatString); - private static string s_PSCopyToSessionHelperDefinitionRestricted = StringUtil.Format(PSCopyToSessionHelperDefinitionFormat, @"[ValidateUserDrive()]", s_driveMaxSizeErrorFormatString); + private static readonly string s_driveMaxSizeErrorFormatString = FileSystemProviderStrings.DriveMaxSizeError; + private static readonly string s_PSCopyToSessionHelperDefinition = StringUtil.Format(PSCopyToSessionHelperDefinitionFormat, @"[ValidateNotNullOrEmpty()]", s_driveMaxSizeErrorFormatString); + private static readonly string s_PSCopyToSessionHelperDefinitionRestricted = StringUtil.Format(PSCopyToSessionHelperDefinitionFormat, @"[ValidateUserDrive()]", s_driveMaxSizeErrorFormatString); private const string PSCopyToSessionHelperDefinitionFormat = @" param ( [Parameter(ParameterSetName=""PSCopyFileToRemoteSession"")] @@ -9200,13 +9200,13 @@ function PSCreateDirectoryOnRemoteSession }} "; - private static string s_PSCopyToSessionHelper = functionToken + PSCopyToSessionHelperName + @" + private static readonly string s_PSCopyToSessionHelper = functionToken + PSCopyToSessionHelperName + @" { " + s_PSCopyToSessionHelperDefinition + @" } "; - private static Hashtable s_PSCopyToSessionHelperFunction = new Hashtable() { + private static readonly Hashtable s_PSCopyToSessionHelperFunction = new Hashtable() { {nameToken, PSCopyToSessionHelperName}, {definitionToken, s_PSCopyToSessionHelperDefinitionRestricted} }; @@ -9216,8 +9216,8 @@ function PSCreateDirectoryOnRemoteSession #region PSCopyFromSessionHelper internal const string PSCopyFromSessionHelperName = @"PSCopyFromSessionHelper"; - private static string s_PSCopyFromSessionHelperDefinition = StringUtil.Format(PSCopyFromSessionHelperDefinitionFormat, @"[ValidateNotNullOrEmpty()]"); - private static string s_PSCopyFromSessionHelperDefinitionRestricted = StringUtil.Format(PSCopyFromSessionHelperDefinitionFormat, @"[ValidateUserDrive()]"); + private static readonly string s_PSCopyFromSessionHelperDefinition = StringUtil.Format(PSCopyFromSessionHelperDefinitionFormat, @"[ValidateNotNullOrEmpty()]"); + private static readonly string s_PSCopyFromSessionHelperDefinitionRestricted = StringUtil.Format(PSCopyFromSessionHelperDefinitionFormat, @"[ValidateUserDrive()]"); private const string PSCopyFromSessionHelperDefinitionFormat = @" param ( [Parameter(ParameterSetName=""PSCopyFileFromRemoteSession"", Mandatory=$true)] @@ -9695,7 +9695,7 @@ PSGetPathDirAndFiles @params } "; - private static Hashtable s_PSCopyFromSessionHelperFunction = new Hashtable() { + private static readonly Hashtable s_PSCopyFromSessionHelperFunction = new Hashtable() { {nameToken, PSCopyFromSessionHelperName}, {definitionToken, s_PSCopyFromSessionHelperDefinitionRestricted} }; @@ -9706,7 +9706,7 @@ PSGetPathDirAndFiles @params internal const string PSCopyRemoteUtilsName = @"PSCopyRemoteUtils"; internal static string PSCopyRemoteUtilsDefinition = StringUtil.Format(PSCopyRemoteUtilsDefinitionFormat, @"[ValidateNotNullOrEmpty()]", PSValidatePathFunction); - private static string s_PSCopyRemoteUtilsDefinitionRestricted = StringUtil.Format(PSCopyRemoteUtilsDefinitionFormat, @"[ValidateUserDrive()]", PSValidatePathFunction); + private static readonly string s_PSCopyRemoteUtilsDefinitionRestricted = StringUtil.Format(PSCopyRemoteUtilsDefinitionFormat, @"[ValidateUserDrive()]", PSValidatePathFunction); private const string PSCopyRemoteUtilsDefinitionFormat = @" param ( [Parameter(ParameterSetName=""PSRemoteDirectoryExist"", Mandatory=$true)] diff --git a/src/System.Management.Automation/namespaces/LocationGlobber.cs b/src/System.Management.Automation/namespaces/LocationGlobber.cs index 0a4e1785e4c..3cfe9af6bb6 100644 --- a/src/System.Management.Automation/namespaces/LocationGlobber.cs +++ b/src/System.Management.Automation/namespaces/LocationGlobber.cs @@ -25,7 +25,7 @@ internal sealed class LocationGlobber [Dbg.TraceSourceAttribute( "LocationGlobber", "The location globber converts PowerShell paths with glob characters to zero or more paths.")] - private static Dbg.PSTraceSource s_tracer = + private static readonly Dbg.PSTraceSource s_tracer = Dbg.PSTraceSource.GetTracer("LocationGlobber", "The location globber converts PowerShell paths with glob characters to zero or more paths."); @@ -35,7 +35,7 @@ internal sealed class LocationGlobber [Dbg.TraceSourceAttribute( "PathResolution", "Traces the path resolution algorithm.")] - private static Dbg.PSTraceSource s_pathResolutionTracer = + private static readonly Dbg.PSTraceSource s_pathResolutionTracer = Dbg.PSTraceSource.GetTracer( "PathResolution", "Traces the path resolution algorithm.", @@ -1654,7 +1654,7 @@ internal bool IsAbsolutePath(string path, out string driveName) /// /// The instance of session state on which this globber acts. /// - private SessionState _sessionState; + private readonly SessionState _sessionState; /// /// Removes the back tick "`" from any of the glob characters in the path. diff --git a/src/System.Management.Automation/namespaces/PathInfo.cs b/src/System.Management.Automation/namespaces/PathInfo.cs index cd91845f84c..d8a171341ea 100644 --- a/src/System.Management.Automation/namespaces/PathInfo.cs +++ b/src/System.Management.Automation/namespaces/PathInfo.cs @@ -78,7 +78,7 @@ public string ProviderPath } private string _providerPath; - private SessionState _sessionState; + private readonly SessionState _sessionState; /// /// Gets the MSH path that this object represents. @@ -91,9 +91,9 @@ public string Path } } - private PSDriveInfo _drive; - private ProviderInfo _provider; - private string _path = string.Empty; + private readonly PSDriveInfo _drive; + private readonly ProviderInfo _provider; + private readonly string _path = string.Empty; /// /// Gets a string representing the MSH path. diff --git a/src/System.Management.Automation/namespaces/ProviderDeclarationAttribute.cs b/src/System.Management.Automation/namespaces/ProviderDeclarationAttribute.cs index 4107dc662c6..7c007ca7c29 100644 --- a/src/System.Management.Automation/namespaces/ProviderDeclarationAttribute.cs +++ b/src/System.Management.Automation/namespaces/ProviderDeclarationAttribute.cs @@ -52,7 +52,7 @@ public CmdletProviderAttribute( ProviderCapabilities = providerCapabilities; } - private char[] _illegalCharacters = new char[] { ':', '\\', '[', ']', '?', '*' }; + private readonly char[] _illegalCharacters = new char[] { ':', '\\', '[', ']', '?', '*' }; /// /// Gets the name of the provider. diff --git a/src/System.Management.Automation/namespaces/RegistryProvider.cs b/src/System.Management.Automation/namespaces/RegistryProvider.cs index 5436dfb0bbb..3c170bca8ff 100644 --- a/src/System.Management.Automation/namespaces/RegistryProvider.cs +++ b/src/System.Management.Automation/namespaces/RegistryProvider.cs @@ -75,7 +75,7 @@ public sealed partial class RegistryProvider : [Dbg.TraceSourceAttribute( "RegistryProvider", "The namespace navigation provider for the Windows Registry")] - private static Dbg.PSTraceSource s_tracer = + private static readonly Dbg.PSTraceSource s_tracer = Dbg.PSTraceSource.GetTracer("RegistryProvider", "The namespace navigation provider for the Windows Registry"); diff --git a/src/System.Management.Automation/namespaces/RegistryWrapper.cs b/src/System.Management.Automation/namespaces/RegistryWrapper.cs index 13f451a539c..351d656de28 100644 --- a/src/System.Management.Automation/namespaces/RegistryWrapper.cs +++ b/src/System.Management.Automation/namespaces/RegistryWrapper.cs @@ -112,7 +112,7 @@ public static object ConvertUIntToValueForRegistryIfNeeded(object value, Registr internal class RegistryWrapper : IRegistryWrapper { - private RegistryKey _regKey; + private readonly RegistryKey _regKey; internal RegistryWrapper(RegistryKey regKey) { @@ -244,8 +244,8 @@ public ObjectSecurity GetAccessControl(AccessControlSections includeSections) internal class TransactedRegistryWrapper : IRegistryWrapper { - private TransactedRegistryKey _txRegKey; - private CmdletProvider _provider; + private readonly TransactedRegistryKey _txRegKey; + private readonly CmdletProvider _provider; internal TransactedRegistryWrapper(TransactedRegistryKey txRegKey, CmdletProvider provider) { diff --git a/src/System.Management.Automation/namespaces/SessionStateProviderBase.cs b/src/System.Management.Automation/namespaces/SessionStateProviderBase.cs index f3720bb130d..595cd623834 100644 --- a/src/System.Management.Automation/namespaces/SessionStateProviderBase.cs +++ b/src/System.Management.Automation/namespaces/SessionStateProviderBase.cs @@ -1116,8 +1116,8 @@ internal SessionStateProviderBaseContentReaderWriter(string path, SessionStatePr _provider = provider; } - private string _path; - private SessionStateProviderBase _provider; + private readonly string _path; + private readonly SessionStateProviderBase _provider; /// /// Reads the content from the item. diff --git a/src/System.Management.Automation/security/CatalogHelper.cs b/src/System.Management.Automation/security/CatalogHelper.cs index 74a239a2ccd..eaf79f0ad8a 100644 --- a/src/System.Management.Automation/security/CatalogHelper.cs +++ b/src/System.Management.Automation/security/CatalogHelper.cs @@ -73,14 +73,14 @@ public class CatalogInformation internal static class CatalogHelper { // Catalog Version is (0X100 = 256) for Catalog Version 1 - private static int catalogVersion1 = 256; + private static readonly int catalogVersion1 = 256; // Catalog Version is (0X200 = 512) for Catalog Version 2 - private static int catalogVersion2 = 512; + private static readonly int catalogVersion2 = 512; // Hash Algorithms supported by Windows Catalog - private static string HashAlgorithmSHA1 = "SHA1"; - private static string HashAlgorithmSHA256 = "SHA256"; + private static readonly string HashAlgorithmSHA1 = "SHA1"; + private static readonly string HashAlgorithmSHA256 = "SHA256"; private static PSCmdlet _cmdlet = null; /// diff --git a/src/System.Management.Automation/security/SecurityManager.cs b/src/System.Management.Automation/security/SecurityManager.cs index 7d6478601d7..9b4b47ffca8 100644 --- a/src/System.Management.Automation/security/SecurityManager.cs +++ b/src/System.Management.Automation/security/SecurityManager.cs @@ -68,7 +68,7 @@ internal enum RunPromptDecision private ExecutionPolicy _executionPolicy; // shellId supplied by runspace configuration - private string _shellId; + private readonly string _shellId; /// /// Initializes a new instance of the PSAuthorizationManager diff --git a/src/System.Management.Automation/security/SecuritySupport.cs b/src/System.Management.Automation/security/SecuritySupport.cs index d9c1f0d3994..6622c608aa2 100644 --- a/src/System.Management.Automation/security/SecuritySupport.cs +++ b/src/System.Management.Automation/security/SecuritySupport.cs @@ -1047,7 +1047,7 @@ public CmsMessageRecipient(string identifier) this.Certificates = new X509Certificate2Collection(); } - private string _identifier = null; + private readonly string _identifier = null; /// /// Creates an instance of the CmsMessageRecipient class. @@ -1059,7 +1059,7 @@ public CmsMessageRecipient(X509Certificate2 certificate) this.Certificates = new X509Certificate2Collection(); } - private X509Certificate2 _pendingCertificate = null; + private readonly X509Certificate2 _pendingCertificate = null; /// /// Gets the certificate associated with this recipient. @@ -1563,7 +1563,7 @@ internal static void CurrentDomain_ProcessExit(object sender, EventArgs e) private static IntPtr s_amsiSession = IntPtr.Zero; private static bool s_amsiInitFailed = false; - private static object s_amsiLockObject = new object(); + private static readonly object s_amsiLockObject = new object(); /// /// Reset the AMSI session (used to track related script invocations) diff --git a/src/System.Management.Automation/security/nativeMethods.cs b/src/System.Management.Automation/security/nativeMethods.cs index e109e000719..c9c0f208436 100644 --- a/src/System.Management.Automation/security/nativeMethods.cs +++ b/src/System.Management.Automation/security/nativeMethods.cs @@ -1081,36 +1081,36 @@ internal static DWORD DestroyWintrustDataStruct(WINTRUST_DATA wtd) [StructLayout(LayoutKind.Sequential)] internal struct CRYPT_PROVIDER_CERT { - private DWORD _cbStruct; + private readonly DWORD _cbStruct; internal IntPtr pCert; // PCCERT_CONTEXT - private BOOL _fCommercial; - private BOOL _fTrustedRoot; - private BOOL _fSelfSigned; - private BOOL _fTestCert; - private DWORD _dwRevokedReason; - private DWORD _dwConfidence; - private DWORD _dwError; - private IntPtr _pTrustListContext; // CTL_CONTEXT* - private BOOL _fTrustListSignerCert; - private IntPtr _pCtlContext; // PCCTL_CONTEXT - private DWORD _dwCtlError; - private BOOL _fIsCyclic; - private IntPtr _pChainElement; // PCERT_CHAIN_ELEMENT + private readonly BOOL _fCommercial; + private readonly BOOL _fTrustedRoot; + private readonly BOOL _fSelfSigned; + private readonly BOOL _fTestCert; + private readonly DWORD _dwRevokedReason; + private readonly DWORD _dwConfidence; + private readonly DWORD _dwError; + private readonly IntPtr _pTrustListContext; // CTL_CONTEXT* + private readonly BOOL _fTrustListSignerCert; + private readonly IntPtr _pCtlContext; // PCCTL_CONTEXT + private readonly DWORD _dwCtlError; + private readonly BOOL _fIsCyclic; + private readonly IntPtr _pChainElement; // PCERT_CHAIN_ELEMENT }; [StructLayout(LayoutKind.Sequential)] internal struct CRYPT_PROVIDER_SGNR { - private DWORD _cbStruct; + private readonly DWORD _cbStruct; private FILETIME _sftVerifyAsOf; - private DWORD _csCertChain; - private IntPtr _pasCertChain; // CRYPT_PROVIDER_CERT* - private DWORD _dwSignerType; - private IntPtr _psSigner; // CMSG_SIGNER_INFO* - private DWORD _dwError; + private readonly DWORD _csCertChain; + private readonly IntPtr _pasCertChain; // CRYPT_PROVIDER_CERT* + private readonly DWORD _dwSignerType; + private readonly IntPtr _psSigner; // CMSG_SIGNER_INFO* + private readonly DWORD _dwError; internal DWORD csCounterSigners; internal IntPtr pasCounterSigners; // CRYPT_PROVIDER_SGNR* - private IntPtr _pChainContext; // PCCERT_CHAIN_CONTEXT + private readonly IntPtr _pChainContext; // PCCERT_CHAIN_CONTEXT }; [DllImport("wintrust.dll", SetLastError = true, CharSet = CharSet.Unicode)] @@ -1949,14 +1949,14 @@ internal struct SIP_INDIRECT_DATA [StructLayout(LayoutKind.Sequential)] internal struct CRYPTCATCDF { - private DWORD _cbStruct; - private IntPtr _hFile; - private DWORD _dwCurFilePos; - private DWORD _dwLastMemberOffset; - private BOOL _fEOF; + private readonly DWORD _cbStruct; + private readonly IntPtr _hFile; + private readonly DWORD _dwCurFilePos; + private readonly DWORD _dwLastMemberOffset; + private readonly BOOL _fEOF; [MarshalAs(UnmanagedType.LPWStr)] - private string _pwszResultDir; - private IntPtr _hCATStore; + private readonly string _pwszResultDir; + private readonly IntPtr _hCATStore; }; [StructLayout(LayoutKind.Sequential)] @@ -1980,29 +1980,29 @@ internal struct CRYPTCATMEMBER [StructLayout(LayoutKind.Sequential)] internal struct CRYPTCATATTRIBUTE { - private DWORD _cbStruct; + private readonly DWORD _cbStruct; [MarshalAs(UnmanagedType.LPWStr)] internal string pwszReferenceTag; - private DWORD _dwAttrTypeAndAction; + private readonly DWORD _dwAttrTypeAndAction; internal DWORD cbValue; internal System.IntPtr pbValue; - private DWORD _dwReserved; + private readonly DWORD _dwReserved; }; [StructLayout(LayoutKind.Sequential)] internal struct CRYPTCATSTORE { - private DWORD _cbStruct; + private readonly DWORD _cbStruct; internal DWORD dwPublicVersion; [MarshalAs(UnmanagedType.LPWStr)] internal string pwszP7File; - private IntPtr _hProv; - private DWORD _dwEncodingType; - private DWORD _fdwStoreFlags; - private IntPtr _hReserved; - private IntPtr _hAttrs; - private IntPtr _hCryptMsg; - private IntPtr _hSorted; + private readonly IntPtr _hProv; + private readonly DWORD _dwEncodingType; + private readonly DWORD _fdwStoreFlags; + private readonly IntPtr _hReserved; + private readonly IntPtr _hAttrs; + private readonly IntPtr _hCryptMsg; + private readonly IntPtr _hSorted; }; [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] diff --git a/src/System.Management.Automation/security/wldpNativeMethods.cs b/src/System.Management.Automation/security/wldpNativeMethods.cs index 6f814ed8ca2..6bdf2a63a06 100644 --- a/src/System.Management.Automation/security/wldpNativeMethods.cs +++ b/src/System.Management.Automation/security/wldpNativeMethods.cs @@ -62,7 +62,7 @@ public static SystemEnforcementMode GetSystemLockdownPolicy() return s_systemLockdownPolicy.Value; } - private static object s_systemLockdownPolicyLock = new object(); + private static readonly object s_systemLockdownPolicyLock = new object(); private static SystemEnforcementMode? s_systemLockdownPolicy = null; private static bool s_allowDebugOverridePolicy = false; diff --git a/src/System.Management.Automation/singleshell/config/MshConsoleLoadException.cs b/src/System.Management.Automation/singleshell/config/MshConsoleLoadException.cs index cbd4d8836cf..b19501d15ef 100644 --- a/src/System.Management.Automation/singleshell/config/MshConsoleLoadException.cs +++ b/src/System.Management.Automation/singleshell/config/MshConsoleLoadException.cs @@ -86,7 +86,7 @@ private void CreateErrorRecord() _errorRecord = new ErrorRecord(new ParentContainsErrorRecordException(this), "ConsoleLoadFailure", ErrorCategory.ResourceUnavailable, null); } - private Collection _PSSnapInExceptions = new Collection(); + private readonly Collection _PSSnapInExceptions = new Collection(); internal Collection PSSnapInExceptions { get diff --git a/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs b/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs index b1f13ab0cf0..abd58feae67 100644 --- a/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs +++ b/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs @@ -262,8 +262,8 @@ internal string AbsoluteModulePath /// public Collection Formats { get; } - private string _descriptionIndirect; - private string _descriptionFallback = string.Empty; + private readonly string _descriptionIndirect; + private readonly string _descriptionFallback = string.Empty; private string _description; /// /// Description of mshsnapin. @@ -281,8 +281,8 @@ public string Description } } - private string _vendorIndirect; - private string _vendorFallback = string.Empty; + private readonly string _vendorIndirect; + private readonly string _vendorFallback = string.Empty; private string _vendor; /// /// Vendor of mshsnapin. @@ -1335,11 +1335,11 @@ private static IList DefaultMshSnapins } private static IList s_defaultMshSnapins = null; - private static object s_syncObject = new object(); + private static readonly object s_syncObject = new object(); #endregion - private static PSTraceSource s_mshsnapinTracer = PSTraceSource.GetTracer("MshSnapinLoadUnload", "Loading and unloading mshsnapins", false); + private static readonly PSTraceSource s_mshsnapinTracer = PSTraceSource.GetTracer("MshSnapinLoadUnload", "Loading and unloading mshsnapins", false); } } diff --git a/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs b/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs index 130ebbe8241..569c21c23e0 100644 --- a/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs +++ b/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs @@ -116,7 +116,7 @@ private void CreateErrorRecord() } } - private bool _warning = false; + private readonly bool _warning = false; private ErrorRecord _errorRecord; private bool _isErrorRecordOriginallyNull; @@ -146,8 +146,8 @@ public override ErrorRecord ErrorRecord } } - private string _PSSnapin = string.Empty; - private string _reason = string.Empty; + private readonly string _PSSnapin = string.Empty; + private readonly string _reason = string.Empty; /// /// Gets message for this exception. diff --git a/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs b/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs index ea6ecd3b0ba..fa48a5b7ee3 100644 --- a/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs +++ b/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs @@ -153,8 +153,8 @@ public string CommandName #endregion Properties #region Private - private string _errorId = "CommandNotFoundException"; - private ErrorCategory _errorCategory = ErrorCategory.ObjectNotFound; + private readonly string _errorId = "CommandNotFoundException"; + private readonly ErrorCategory _errorCategory = ErrorCategory.ObjectNotFound; private static string BuildMessage( string commandName, @@ -416,7 +416,7 @@ public string CommandName get { return _commandName; } } - private string _commandName = string.Empty; + private readonly string _commandName = string.Empty; /// /// Gets the PSVersion that the script requires. @@ -426,7 +426,7 @@ public Version RequiresPSVersion get { return _requiresPSVersion; } } - private Version _requiresPSVersion; + private readonly Version _requiresPSVersion; /// /// Gets the missing snap-ins that the script requires. @@ -436,7 +436,7 @@ public ReadOnlyCollection MissingPSSnapIns get { return _missingPSSnapIns; } } - private ReadOnlyCollection _missingPSSnapIns = new ReadOnlyCollection(Array.Empty()); + private readonly ReadOnlyCollection _missingPSSnapIns = new ReadOnlyCollection(Array.Empty()); /// /// Gets or sets the ID of the shell. @@ -446,7 +446,7 @@ public string RequiresShellId get { return _requiresShellId; } } - private string _requiresShellId; + private readonly string _requiresShellId; /// /// Gets or sets the path to the incompatible shell. @@ -456,7 +456,7 @@ public string RequiresShellPath get { return _requiresShellPath; } } - private string _requiresShellPath; + private readonly string _requiresShellPath; #endregion Properties diff --git a/src/System.Management.Automation/utils/CryptoUtils.cs b/src/System.Management.Automation/utils/CryptoUtils.cs index 2b644f8aebb..0c9824cf37e 100644 --- a/src/System.Management.Automation/utils/CryptoUtils.cs +++ b/src/System.Management.Automation/utils/CryptoUtils.cs @@ -278,7 +278,7 @@ internal class PSCryptoException : Exception { #region Private Members - private uint _errorCode; + private readonly uint _errorCode; #endregion Private Members @@ -386,7 +386,7 @@ internal class PSRSACryptoServiceProvider : IDisposable // bool indicating if session key was generated before private bool _sessionKeyGenerated = false; - private static object s_syncObject = new object(); + private static readonly object s_syncObject = new object(); #endregion Private Members diff --git a/src/System.Management.Automation/utils/ExecutionExceptions.cs b/src/System.Management.Automation/utils/ExecutionExceptions.cs index ab60cc636ba..47ae54d4a82 100644 --- a/src/System.Management.Automation/utils/ExecutionExceptions.cs +++ b/src/System.Management.Automation/utils/ExecutionExceptions.cs @@ -276,7 +276,7 @@ public ProviderInvocationException ProviderInvocationException } [NonSerialized] - private ProviderInvocationException _providerInvocationException; + private readonly ProviderInvocationException _providerInvocationException; /// /// This is the ProviderInfo associated with the provider which diff --git a/src/System.Management.Automation/utils/IObjectWriter.cs b/src/System.Management.Automation/utils/IObjectWriter.cs index eb011e4f3b8..b8f8b38192f 100644 --- a/src/System.Management.Automation/utils/IObjectWriter.cs +++ b/src/System.Management.Automation/utils/IObjectWriter.cs @@ -124,7 +124,7 @@ public abstract int MaxCapacity internal class DiscardingPipelineWriter : PipelineWriter { - private ManualResetEvent _waitHandle = new ManualResetEvent(true); + private readonly ManualResetEvent _waitHandle = new ManualResetEvent(true); public override WaitHandle WaitHandle { get { return _waitHandle; } diff --git a/src/System.Management.Automation/utils/MetadataExceptions.cs b/src/System.Management.Automation/utils/MetadataExceptions.cs index 21f9a9b842c..21038ac27eb 100644 --- a/src/System.Management.Automation/utils/MetadataExceptions.cs +++ b/src/System.Management.Automation/utils/MetadataExceptions.cs @@ -151,7 +151,7 @@ internal bool SwallowException get { return _swallowException; } } - private bool _swallowException = false; + private readonly bool _swallowException = false; } /// diff --git a/src/System.Management.Automation/utils/MshArgumentException.cs b/src/System.Management.Automation/utils/MshArgumentException.cs index e937a275b4d..63d9821a55b 100644 --- a/src/System.Management.Automation/utils/MshArgumentException.cs +++ b/src/System.Management.Automation/utils/MshArgumentException.cs @@ -137,7 +137,7 @@ public ErrorRecord ErrorRecord } private ErrorRecord _errorRecord; - private string _errorId = "Argument"; + private readonly string _errorId = "Argument"; /// /// See @@ -152,7 +152,7 @@ public override string Message get { return string.IsNullOrEmpty(_message) ? base.Message : _message; } } - private string _message; + private readonly string _message; } } diff --git a/src/System.Management.Automation/utils/MshArgumentNullException.cs b/src/System.Management.Automation/utils/MshArgumentNullException.cs index a7b870bcab0..cf356157bf4 100644 --- a/src/System.Management.Automation/utils/MshArgumentNullException.cs +++ b/src/System.Management.Automation/utils/MshArgumentNullException.cs @@ -135,7 +135,7 @@ public ErrorRecord ErrorRecord } private ErrorRecord _errorRecord; - private string _errorId = "ArgumentNull"; + private readonly string _errorId = "ArgumentNull"; /// /// See @@ -150,7 +150,7 @@ public override string Message get { return string.IsNullOrEmpty(_message) ? base.Message : _message; } } - private string _message; + private readonly string _message; } } diff --git a/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs b/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs index e54320235a2..9346e867ac1 100644 --- a/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs +++ b/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs @@ -133,7 +133,7 @@ public ErrorRecord ErrorRecord } private ErrorRecord _errorRecord; - private string _errorId = "ArgumentOutOfRange"; + private readonly string _errorId = "ArgumentOutOfRange"; } } diff --git a/src/System.Management.Automation/utils/MshInvalidOperationException.cs b/src/System.Management.Automation/utils/MshInvalidOperationException.cs index e4c0b7b111e..128b36cec9a 100644 --- a/src/System.Management.Automation/utils/MshInvalidOperationException.cs +++ b/src/System.Management.Automation/utils/MshInvalidOperationException.cs @@ -137,8 +137,8 @@ internal void SetErrorId(string errorId) _errorId = errorId; } - private ErrorCategory _errorCategory = ErrorCategory.InvalidOperation; - private object _target = null; + private readonly ErrorCategory _errorCategory = ErrorCategory.InvalidOperation; + private readonly object _target = null; } } diff --git a/src/System.Management.Automation/utils/MshNotImplementedException.cs b/src/System.Management.Automation/utils/MshNotImplementedException.cs index c84f66e1ac4..e264be4cd0d 100644 --- a/src/System.Management.Automation/utils/MshNotImplementedException.cs +++ b/src/System.Management.Automation/utils/MshNotImplementedException.cs @@ -114,7 +114,7 @@ public ErrorRecord ErrorRecord } private ErrorRecord _errorRecord; - private string _errorId = "NotImplemented"; + private readonly string _errorId = "NotImplemented"; } } diff --git a/src/System.Management.Automation/utils/MshNotSupportedException.cs b/src/System.Management.Automation/utils/MshNotSupportedException.cs index fc4ce6871f3..fd1de79e92e 100644 --- a/src/System.Management.Automation/utils/MshNotSupportedException.cs +++ b/src/System.Management.Automation/utils/MshNotSupportedException.cs @@ -114,7 +114,7 @@ public ErrorRecord ErrorRecord } private ErrorRecord _errorRecord; - private string _errorId = "NotSupported"; + private readonly string _errorId = "NotSupported"; } } diff --git a/src/System.Management.Automation/utils/MshObjectDisposedException.cs b/src/System.Management.Automation/utils/MshObjectDisposedException.cs index 0de12d3b0d3..e0fc1ae7ef5 100644 --- a/src/System.Management.Automation/utils/MshObjectDisposedException.cs +++ b/src/System.Management.Automation/utils/MshObjectDisposedException.cs @@ -120,7 +120,7 @@ public ErrorRecord ErrorRecord } private ErrorRecord _errorRecord; - private string _errorId = "ObjectDisposed"; + private readonly string _errorId = "ObjectDisposed"; } } diff --git a/src/System.Management.Automation/utils/MshTraceSource.cs b/src/System.Management.Automation/utils/MshTraceSource.cs index 9a4d28b8b5b..dda48ac85c2 100644 --- a/src/System.Management.Automation/utils/MshTraceSource.cs +++ b/src/System.Management.Automation/utils/MshTraceSource.cs @@ -49,7 +49,7 @@ public partial class PSTraceSource /// /// Lock object for the GetTracer method. /// - private static object s_getTracerLock = new object(); + private static readonly object s_getTracerLock = new object(); /// /// A helper to get an instance of the PSTraceSource class. diff --git a/src/System.Management.Automation/utils/ObjectReader.cs b/src/System.Management.Automation/utils/ObjectReader.cs index 99cf452fb38..2beced09114 100644 --- a/src/System.Management.Automation/utils/ObjectReader.cs +++ b/src/System.Management.Automation/utils/ObjectReader.cs @@ -203,7 +203,7 @@ private void OnDataReady(object sender, EventArgs args) /// we are protected from outside code interfering in our /// critical section. Thanks to Wintellect for the hint. /// - private object _monitorObject = new object(); + private readonly object _monitorObject = new object(); #endregion Private fields @@ -490,7 +490,7 @@ internal class PSDataCollectionReader { #region Private Data - private PSDataCollectionEnumerator _enumerator; + private readonly PSDataCollectionEnumerator _enumerator; #endregion @@ -649,7 +649,7 @@ internal class PSDataCollectionPipelineReader { #region Private Data - private PSDataCollection _datastore; + private readonly PSDataCollection _datastore; #endregion Private Data diff --git a/src/System.Management.Automation/utils/ObjectStream.cs b/src/System.Management.Automation/utils/ObjectStream.cs index 607d6acc94a..8653808f599 100644 --- a/src/System.Management.Automation/utils/ObjectStream.cs +++ b/src/System.Management.Automation/utils/ObjectStream.cs @@ -401,7 +401,7 @@ internal sealed class ObjectStream : ObjectStreamBase, IDisposable // PERF-2003/08/22-JonN We should probably use Queue instead // PERF-2004/06/30-JonN Probably more efficient to use type // Collection as the underlying store - private List _objects; + private readonly List _objects; /// /// Is the stream open or closed for writing? @@ -420,7 +420,7 @@ internal sealed class ObjectStream : ObjectStreamBase, IDisposable /// the stream is closed for reading. Instead, use WaitAny on /// this handle and also _readClosedHandle. /// - private AutoResetEvent _readHandle; + private readonly AutoResetEvent _readHandle; /// /// Handle returned to callers for blocking on data ready. @@ -431,7 +431,7 @@ internal sealed class ObjectStream : ObjectStreamBase, IDisposable /// When this handle is set, the stream is closed for reading, /// so all blocked readers should be released. /// - private ManualResetEvent _readClosedHandle; + private readonly ManualResetEvent _readClosedHandle; /// /// Write handle - signaled with the number of objects in the @@ -446,7 +446,7 @@ internal sealed class ObjectStream : ObjectStreamBase, IDisposable /// the stream is closed for writing. Instead, use WaitAny on /// this handle and also _writeClosedHandle. /// - private AutoResetEvent _writeHandle; + private readonly AutoResetEvent _writeHandle; /// /// Handle returned to callers for blocking until buffer space @@ -458,7 +458,7 @@ internal sealed class ObjectStream : ObjectStreamBase, IDisposable /// When this handle is set, the stream is closed for writing, /// so all blocked readers should be released. /// - private ManualResetEvent _writeClosedHandle; + private readonly ManualResetEvent _writeClosedHandle; #endregion Synchronization handles /// @@ -493,7 +493,7 @@ internal sealed class ObjectStream : ObjectStreamBase, IDisposable /// Note that this is not permitted to be more than Int32.MaxValue, /// since the underlying list has this limitation. /// - private int _capacity = Int32.MaxValue; + private readonly int _capacity = Int32.MaxValue; /// /// This object is used to acquire an exclusive lock on the stream. @@ -503,7 +503,7 @@ internal sealed class ObjectStream : ObjectStreamBase, IDisposable /// we are protected from outside code interfering in our /// critical section. Thanks to Wintellect for the hint. /// - private object _monitorObject = new object(); + private readonly object _monitorObject = new object(); /// /// Indicates if this stream has already been disposed. @@ -1551,7 +1551,7 @@ internal sealed class PSDataCollectionStream : ObjectStreamBase { #region Private Fields - private PSDataCollection _objects; + private readonly PSDataCollection _objects; private Guid _psInstanceId; private bool _isOpen; private PipelineWriter _writer; @@ -1559,7 +1559,7 @@ internal sealed class PSDataCollectionStream : ObjectStreamBase private PipelineReader _psobjectReader; private PipelineReader _objectReaderForPipeline; private PipelineReader _psobjectReaderForPipeline; - private object _syncObject = new object(); + private readonly object _syncObject = new object(); private bool _disposed = false; #endregion diff --git a/src/System.Management.Automation/utils/ObjectWriter.cs b/src/System.Management.Automation/utils/ObjectWriter.cs index 9da4a2307a3..b93bd25cd19 100644 --- a/src/System.Management.Automation/utils/ObjectWriter.cs +++ b/src/System.Management.Automation/utils/ObjectWriter.cs @@ -199,7 +199,7 @@ private void OnWriteReady (object sender, EventArgs args) /// The underlying stream. /// /// Can never be null - private ObjectStreamBase _stream; + private readonly ObjectStreamBase _stream; #endregion Private Fields } diff --git a/src/System.Management.Automation/utils/ParameterBinderExceptions.cs b/src/System.Management.Automation/utils/ParameterBinderExceptions.cs index 4daa7dc5962..66ab68042a6 100644 --- a/src/System.Management.Automation/utils/ParameterBinderExceptions.cs +++ b/src/System.Management.Automation/utils/ParameterBinderExceptions.cs @@ -403,7 +403,7 @@ public string ParameterName } } - private string _parameterName = string.Empty; + private readonly string _parameterName = string.Empty; /// /// Gets the type the parameter is expecting. @@ -416,7 +416,7 @@ public Type ParameterType } } - private Type _parameterType; + private readonly Type _parameterType; /// /// Gets the Type that was specified as the parameter value. @@ -429,7 +429,7 @@ public Type TypeSpecified } } - private Type _typeSpecified; + private readonly Type _typeSpecified; /// /// Gets the errorId of this ParameterBindingException. @@ -442,7 +442,7 @@ public string ErrorId } } - private string _errorId; + private readonly string _errorId; /// /// Gets the line in the script at which the error occurred. @@ -455,7 +455,7 @@ public Int64 Line } } - private Int64 _line = Int64.MinValue; + private readonly Int64 _line = Int64.MinValue; /// /// Gets the offset on the line in the script at which the error occurred. @@ -468,7 +468,7 @@ public Int64 Offset } } - private Int64 _offset = Int64.MinValue; + private readonly Int64 _offset = Int64.MinValue; /// /// Gets the invocation information about the command. @@ -481,14 +481,14 @@ public InvocationInfo CommandInvocation } } - private InvocationInfo _invocationInfo; + private readonly InvocationInfo _invocationInfo; #endregion Properties #region private - private string _resourceString; - private object[] _args = Array.Empty(); - private string _commandName; + private readonly string _resourceString; + private readonly object[] _args = Array.Empty(); + private readonly string _commandName; private string BuildMessage() { diff --git a/src/System.Management.Automation/utils/ParserException.cs b/src/System.Management.Automation/utils/ParserException.cs index ac10c577481..fe905446528 100644 --- a/src/System.Management.Automation/utils/ParserException.cs +++ b/src/System.Management.Automation/utils/ParserException.cs @@ -15,7 +15,7 @@ namespace System.Management.Automation public class ParseException : RuntimeException { private const string errorIdString = "Parse"; - private ParseError[] _errors; + private readonly ParseError[] _errors; /// /// The list of parser errors. diff --git a/src/System.Management.Automation/utils/PsUtils.cs b/src/System.Management.Automation/utils/PsUtils.cs index 0d8c3473ba0..fbb8aa177e2 100644 --- a/src/System.Management.Automation/utils/PsUtils.cs +++ b/src/System.Management.Automation/utils/PsUtils.cs @@ -566,7 +566,7 @@ internal class CRC32Hash { // CRC-32C polynomial representations private const uint polynomial = 0x1EDC6F41; - private static uint[] table; + private static readonly uint[] table; static CRC32Hash() { diff --git a/src/System.Management.Automation/utils/ResourceManagerCache.cs b/src/System.Management.Automation/utils/ResourceManagerCache.cs index 7c7036e5f09..57de0187a2f 100644 --- a/src/System.Management.Automation/utils/ResourceManagerCache.cs +++ b/src/System.Management.Automation/utils/ResourceManagerCache.cs @@ -16,13 +16,13 @@ internal static class ResourceManagerCache /// to the default resource assembly. The value is another dictionary that is keyed based on the base /// name for the resource that is being retrieved. The value for this dictionary is the ResourceManager. /// - private static Dictionary> s_resourceManagerCache = + private static readonly Dictionary> s_resourceManagerCache = new Dictionary>(StringComparer.OrdinalIgnoreCase); /// /// Used to synchronize access to the ResourceManagerCache. /// - private static object s_syncRoot = new object(); + private static readonly object s_syncRoot = new object(); /// /// Gets the ResourceManager from the cache or gets an instance of the ResourceManager diff --git a/src/System.Management.Automation/utils/SessionStateExceptions.cs b/src/System.Management.Automation/utils/SessionStateExceptions.cs index bb2532347f7..7fb7ae6ef3c 100644 --- a/src/System.Management.Automation/utils/SessionStateExceptions.cs +++ b/src/System.Management.Automation/utils/SessionStateExceptions.cs @@ -323,7 +323,7 @@ public override string Message } [NonSerialized] - private string _message /* = null */; + private readonly string _message /* = null */; #endregion Private/Internal } @@ -522,7 +522,7 @@ public string ItemName get { return _itemName; } } - private string _itemName = string.Empty; + private readonly string _itemName = string.Empty; /// /// Gets the category of session state object the error occurred on. @@ -532,12 +532,12 @@ public SessionStateCategory SessionStateCategory get { return _sessionStateCategory; } } - private SessionStateCategory _sessionStateCategory = SessionStateCategory.Variable; + private readonly SessionStateCategory _sessionStateCategory = SessionStateCategory.Variable; #endregion Properties #region Private - private string _errorId = "SessionStateException"; - private ErrorCategory _errorCategory = ErrorCategory.InvalidArgument; + private readonly string _errorId = "SessionStateException"; + private readonly ErrorCategory _errorCategory = ErrorCategory.InvalidArgument; private static string BuildMessage( string itemName, @@ -855,7 +855,7 @@ public ReadOnlyCollection PossibleMatches } } - private ReadOnlyCollection _possibleMatches; + private readonly ReadOnlyCollection _possibleMatches; #endregion public properties } diff --git a/src/System.Management.Automation/utils/StructuredTraceSource.cs b/src/System.Management.Automation/utils/StructuredTraceSource.cs index 1aebf9534e4..a407e69a479 100644 --- a/src/System.Management.Automation/utils/StructuredTraceSource.cs +++ b/src/System.Management.Automation/utils/StructuredTraceSource.cs @@ -1436,7 +1436,7 @@ internal static int ThreadIndentLevel /// internal string FullName { get; } = string.Empty; - private string _name; + private readonly string _name; /// /// Creates an instance of the TraceSource on demand. @@ -1765,7 +1765,7 @@ public void Dispose() /// /// The trace object that is used for any output. /// - private PSTraceSource _tracer; + private readonly PSTraceSource _tracer; /// /// The flag which caused this scope object to be created. diff --git a/src/System.Management.Automation/utils/Telemetry.cs b/src/System.Management.Automation/utils/Telemetry.cs index 6041c35ca06..7ea4abba555 100644 --- a/src/System.Management.Automation/utils/Telemetry.cs +++ b/src/System.Management.Automation/utils/Telemetry.cs @@ -93,7 +93,7 @@ public static class ApplicationInsightsTelemetry /// Use a hashset for quick lookups. /// We send telemetry only a known set of modules. /// If it's not in the list (initialized in the static constructor), then we report anonymous. - private static HashSet s_knownModules; + private static readonly HashSet s_knownModules; /// Gets a value indicating whether telemetry can be sent. public static bool CanSendTelemetry { get; private set; } diff --git a/src/System.Management.Automation/utils/Verbs.cs b/src/System.Management.Automation/utils/Verbs.cs index aeb6a3ee530..92fcde1b0fe 100644 --- a/src/System.Management.Automation/utils/Verbs.cs +++ b/src/System.Management.Automation/utils/Verbs.cs @@ -1311,8 +1311,8 @@ static Verbs() #endif } - private static Dictionary s_validVerbs = new Dictionary(StringComparer.OrdinalIgnoreCase); - private static Dictionary s_recommendedAlternateVerbs = new Dictionary(StringComparer.OrdinalIgnoreCase); + private static readonly Dictionary s_validVerbs = new Dictionary(StringComparer.OrdinalIgnoreCase); + private static readonly Dictionary s_recommendedAlternateVerbs = new Dictionary(StringComparer.OrdinalIgnoreCase); internal static bool IsStandard(string verb) { diff --git a/src/System.Management.Automation/utils/assert.cs b/src/System.Management.Automation/utils/assert.cs index 921ed42c0f3..3e7d6bd1912 100644 --- a/src/System.Management.Automation/utils/assert.cs +++ b/src/System.Management.Automation/utils/assert.cs @@ -72,7 +72,7 @@ internal static string StackTrace(int framesToSkip) return frameString.ToString(); } - private static object s_throwInsteadOfAssertLock = 1; + private static readonly object s_throwInsteadOfAssertLock = 1; private static bool s_throwInsteadOfAssert = false; /// diff --git a/src/System.Management.Automation/utils/tracing/EtwActivity.cs b/src/System.Management.Automation/utils/tracing/EtwActivity.cs index 7dfac67ddb2..f3a91390eec 100644 --- a/src/System.Management.Automation/utils/tracing/EtwActivity.cs +++ b/src/System.Management.Automation/utils/tracing/EtwActivity.cs @@ -103,9 +103,9 @@ public abstract class EtwActivity /// private class CorrelatedCallback { - private CallbackNoParameter callbackNoParam; - private CallbackWithState callbackWithState; - private AsyncCallback asyncCallback; + private readonly CallbackNoParameter callbackNoParam; + private readonly CallbackWithState callbackWithState; + private readonly AsyncCallback asyncCallback; /// /// ParentActivityId. @@ -182,7 +182,7 @@ public CorrelatedCallback(EtwActivity tracer, AsyncCallback callback) /// /// It is to be used in System.Timers.Timer scenarios. /// - private CallbackWithStateAndArgs callbackWithStateAndArgs; + private readonly CallbackWithStateAndArgs callbackWithStateAndArgs; /// /// EtwCorrelator Constructor. @@ -259,10 +259,10 @@ public void Callback(IAsyncResult asyncResult) } } - private static Dictionary providers = new Dictionary(); - private static object syncLock = new object(); + private static readonly Dictionary providers = new Dictionary(); + private static readonly object syncLock = new object(); - private static EventDescriptor _WriteTransferEvent = new EventDescriptor(0x1f05, 0x1, 0x11, 0x5, 0x14, 0x0, (long)0x4000000000000000); + private static readonly EventDescriptor _WriteTransferEvent = new EventDescriptor(0x1f05, 0x1, 0x11, 0x5, 0x14, 0x0, (long)0x4000000000000000); private EventProvider currentProvider; diff --git a/src/System.Management.Automation/utils/tracing/PSEtwLog.cs b/src/System.Management.Automation/utils/tracing/PSEtwLog.cs index ec772fe549c..8b758a5e560 100644 --- a/src/System.Management.Automation/utils/tracing/PSEtwLog.cs +++ b/src/System.Management.Automation/utils/tracing/PSEtwLog.cs @@ -15,7 +15,7 @@ internal static class PSEtwLog #if UNIX private static PSSysLogProvider provider; #else - private static PSEtwLogProvider provider; + private static readonly PSEtwLogProvider provider; #endif /// diff --git a/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs b/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs index 173c5b8379a..0b4043f2441 100755 --- a/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs +++ b/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs @@ -14,7 +14,7 @@ namespace System.Management.Automation.Tracing /// internal class PSEtwLogProvider : LogProvider { - private static EventProvider etwProvider; + private static readonly EventProvider etwProvider; internal static readonly Guid ProviderGuid = new Guid("F90714A8-5509-434A-BF6D-B1624C8A19A2"); private static EventDescriptor _xferEventDescriptor = new EventDescriptor(0x1f05, 0x1, 0x11, 0x5, 0x14, 0x0, (long)0x4000000000000000); diff --git a/src/System.Management.Automation/utils/tracing/TracingGen.cs b/src/System.Management.Automation/utils/tracing/TracingGen.cs index 09b712714ae..f3912c1b6dd 100644 --- a/src/System.Management.Automation/utils/tracing/TracingGen.cs +++ b/src/System.Management.Automation/utils/tracing/TracingGen.cs @@ -37,88 +37,88 @@ public sealed partial class Tracer : System.Management.Automation.Tracing.EtwAct /// public const long KeywordAll = 0xFFFFFFFF; private static Guid providerId = Guid.Parse("a0c1853b-5c40-4b15-8766-3cf1c58f985a"); - private static EventDescriptor WriteTransferEventEvent; - private static EventDescriptor DebugMessageEvent; - private static EventDescriptor M3PAbortingWorkflowExecutionEvent; - private static EventDescriptor M3PActivityExecutionFinishedEvent; - private static EventDescriptor M3PActivityExecutionQueuedEvent; - private static EventDescriptor M3PActivityExecutionStartedEvent; - private static EventDescriptor M3PBeginContainerParentJobExecutionEvent; - private static EventDescriptor M3PBeginCreateNewJobEvent; - private static EventDescriptor M3PBeginJobLogicEvent; - private static EventDescriptor M3PBeginProxyChildJobEventHandlerEvent; - private static EventDescriptor M3PBeginProxyJobEventHandlerEvent; - private static EventDescriptor M3PBeginProxyJobExecutionEvent; - private static EventDescriptor M3PBeginRunGarbageCollectionEvent; - private static EventDescriptor M3PBeginStartWorkflowApplicationEvent; - private static EventDescriptor M3PBeginWorkflowExecutionEvent; - private static EventDescriptor M3PCancellingWorkflowExecutionEvent; - private static EventDescriptor M3PChildWorkflowJobAdditionEvent; - private static EventDescriptor M3PEndContainerParentJobExecutionEvent; - private static EventDescriptor M3PEndCreateNewJobEvent; - private static EventDescriptor M3PEndJobLogicEvent; - private static EventDescriptor M3PEndpointDisabledEvent; - private static EventDescriptor M3PEndpointEnabledEvent; - private static EventDescriptor M3PEndpointModifiedEvent; - private static EventDescriptor M3PEndpointRegisteredEvent; - private static EventDescriptor M3PEndpointUnregisteredEvent; - private static EventDescriptor M3PEndProxyChildJobEventHandlerEvent; - private static EventDescriptor M3PEndProxyJobEventHandlerEvent; - private static EventDescriptor M3PEndProxyJobExecutionEvent; - private static EventDescriptor M3PEndRunGarbageCollectionEvent; - private static EventDescriptor M3PEndStartWorkflowApplicationEvent; - private static EventDescriptor M3PEndWorkflowExecutionEvent; - private static EventDescriptor M3PErrorImportingWorkflowFromXamlEvent; - private static EventDescriptor M3PForcedWorkflowShutdownErrorEvent; - private static EventDescriptor M3PForcedWorkflowShutdownFinishedEvent; - private static EventDescriptor M3PForcedWorkflowShutdownStartedEvent; - private static EventDescriptor M3PImportedWorkflowFromXamlEvent; - private static EventDescriptor M3PImportingWorkflowFromXamlEvent; - private static EventDescriptor M3PJobCreationCompleteEvent; - private static EventDescriptor M3PJobErrorEvent; - private static EventDescriptor M3PJobRemovedEvent; - private static EventDescriptor M3PJobRemoveErrorEvent; - private static EventDescriptor M3PJobStateChangedEvent; - private static EventDescriptor M3PLoadingWorkflowForExecutionEvent; - private static EventDescriptor M3POutOfProcessRunspaceStartedEvent; - private static EventDescriptor M3PParameterSplattingWasPerformedEvent; - private static EventDescriptor M3PParentJobCreatedEvent; - private static EventDescriptor M3PPersistenceStoreMaxSizeReachedEvent; - private static EventDescriptor M3PPersistingWorkflowEvent; - private static EventDescriptor M3PProxyJobRemoteJobAssociationEvent; - private static EventDescriptor M3PRemoveJobStartedEvent; - private static EventDescriptor M3PRunspaceAvailabilityChangedEvent; - private static EventDescriptor M3PRunspaceStateChangedEvent; - private static EventDescriptor M3PTrackingGuidContainerParentJobCorrelationEvent; - private static EventDescriptor M3PUnloadingWorkflowEvent; - private static EventDescriptor M3PWorkflowActivityExecutionFailedEvent; - private static EventDescriptor M3PWorkflowActivityValidatedEvent; - private static EventDescriptor M3PWorkflowActivityValidationFailedEvent; - private static EventDescriptor M3PWorkflowCleanupPerformedEvent; - private static EventDescriptor M3PWorkflowDeletedFromDiskEvent; - private static EventDescriptor M3PWorkflowEngineStartedEvent; - private static EventDescriptor M3PWorkflowExecutionAbortedEvent; - private static EventDescriptor M3PWorkflowExecutionCancelledEvent; - private static EventDescriptor M3PWorkflowExecutionErrorEvent; - private static EventDescriptor M3PWorkflowExecutionFinishedEvent; - private static EventDescriptor M3PWorkflowExecutionStartedEvent; - private static EventDescriptor M3PWorkflowJobCreatedEvent; - private static EventDescriptor M3PWorkflowLoadedForExecutionEvent; - private static EventDescriptor M3PWorkflowLoadedFromDiskEvent; - private static EventDescriptor M3PWorkflowManagerCheckpointEvent; - private static EventDescriptor M3PWorkflowPersistedEvent; - private static EventDescriptor M3PWorkflowPluginRequestedToShutdownEvent; - private static EventDescriptor M3PWorkflowPluginRestartedEvent; - private static EventDescriptor M3PWorkflowPluginStartedEvent; - private static EventDescriptor M3PWorkflowQuotaViolatedEvent; - private static EventDescriptor M3PWorkflowResumedEvent; - private static EventDescriptor M3PWorkflowResumingEvent; - private static EventDescriptor M3PWorkflowRunspacePoolCreatedEvent; - private static EventDescriptor M3PWorkflowStateChangedEvent; - private static EventDescriptor M3PWorkflowUnloadedEvent; - private static EventDescriptor M3PWorkflowValidationErrorEvent; - private static EventDescriptor M3PWorkflowValidationFinishedEvent; - private static EventDescriptor M3PWorkflowValidationStartedEvent; + private static readonly EventDescriptor WriteTransferEventEvent; + private static readonly EventDescriptor DebugMessageEvent; + private static readonly EventDescriptor M3PAbortingWorkflowExecutionEvent; + private static readonly EventDescriptor M3PActivityExecutionFinishedEvent; + private static readonly EventDescriptor M3PActivityExecutionQueuedEvent; + private static readonly EventDescriptor M3PActivityExecutionStartedEvent; + private static readonly EventDescriptor M3PBeginContainerParentJobExecutionEvent; + private static readonly EventDescriptor M3PBeginCreateNewJobEvent; + private static readonly EventDescriptor M3PBeginJobLogicEvent; + private static readonly EventDescriptor M3PBeginProxyChildJobEventHandlerEvent; + private static readonly EventDescriptor M3PBeginProxyJobEventHandlerEvent; + private static readonly EventDescriptor M3PBeginProxyJobExecutionEvent; + private static readonly EventDescriptor M3PBeginRunGarbageCollectionEvent; + private static readonly EventDescriptor M3PBeginStartWorkflowApplicationEvent; + private static readonly EventDescriptor M3PBeginWorkflowExecutionEvent; + private static readonly EventDescriptor M3PCancellingWorkflowExecutionEvent; + private static readonly EventDescriptor M3PChildWorkflowJobAdditionEvent; + private static readonly EventDescriptor M3PEndContainerParentJobExecutionEvent; + private static readonly EventDescriptor M3PEndCreateNewJobEvent; + private static readonly EventDescriptor M3PEndJobLogicEvent; + private static readonly EventDescriptor M3PEndpointDisabledEvent; + private static readonly EventDescriptor M3PEndpointEnabledEvent; + private static readonly EventDescriptor M3PEndpointModifiedEvent; + private static readonly EventDescriptor M3PEndpointRegisteredEvent; + private static readonly EventDescriptor M3PEndpointUnregisteredEvent; + private static readonly EventDescriptor M3PEndProxyChildJobEventHandlerEvent; + private static readonly EventDescriptor M3PEndProxyJobEventHandlerEvent; + private static readonly EventDescriptor M3PEndProxyJobExecutionEvent; + private static readonly EventDescriptor M3PEndRunGarbageCollectionEvent; + private static readonly EventDescriptor M3PEndStartWorkflowApplicationEvent; + private static readonly EventDescriptor M3PEndWorkflowExecutionEvent; + private static readonly EventDescriptor M3PErrorImportingWorkflowFromXamlEvent; + private static readonly EventDescriptor M3PForcedWorkflowShutdownErrorEvent; + private static readonly EventDescriptor M3PForcedWorkflowShutdownFinishedEvent; + private static readonly EventDescriptor M3PForcedWorkflowShutdownStartedEvent; + private static readonly EventDescriptor M3PImportedWorkflowFromXamlEvent; + private static readonly EventDescriptor M3PImportingWorkflowFromXamlEvent; + private static readonly EventDescriptor M3PJobCreationCompleteEvent; + private static readonly EventDescriptor M3PJobErrorEvent; + private static readonly EventDescriptor M3PJobRemovedEvent; + private static readonly EventDescriptor M3PJobRemoveErrorEvent; + private static readonly EventDescriptor M3PJobStateChangedEvent; + private static readonly EventDescriptor M3PLoadingWorkflowForExecutionEvent; + private static readonly EventDescriptor M3POutOfProcessRunspaceStartedEvent; + private static readonly EventDescriptor M3PParameterSplattingWasPerformedEvent; + private static readonly EventDescriptor M3PParentJobCreatedEvent; + private static readonly EventDescriptor M3PPersistenceStoreMaxSizeReachedEvent; + private static readonly EventDescriptor M3PPersistingWorkflowEvent; + private static readonly EventDescriptor M3PProxyJobRemoteJobAssociationEvent; + private static readonly EventDescriptor M3PRemoveJobStartedEvent; + private static readonly EventDescriptor M3PRunspaceAvailabilityChangedEvent; + private static readonly EventDescriptor M3PRunspaceStateChangedEvent; + private static readonly EventDescriptor M3PTrackingGuidContainerParentJobCorrelationEvent; + private static readonly EventDescriptor M3PUnloadingWorkflowEvent; + private static readonly EventDescriptor M3PWorkflowActivityExecutionFailedEvent; + private static readonly EventDescriptor M3PWorkflowActivityValidatedEvent; + private static readonly EventDescriptor M3PWorkflowActivityValidationFailedEvent; + private static readonly EventDescriptor M3PWorkflowCleanupPerformedEvent; + private static readonly EventDescriptor M3PWorkflowDeletedFromDiskEvent; + private static readonly EventDescriptor M3PWorkflowEngineStartedEvent; + private static readonly EventDescriptor M3PWorkflowExecutionAbortedEvent; + private static readonly EventDescriptor M3PWorkflowExecutionCancelledEvent; + private static readonly EventDescriptor M3PWorkflowExecutionErrorEvent; + private static readonly EventDescriptor M3PWorkflowExecutionFinishedEvent; + private static readonly EventDescriptor M3PWorkflowExecutionStartedEvent; + private static readonly EventDescriptor M3PWorkflowJobCreatedEvent; + private static readonly EventDescriptor M3PWorkflowLoadedForExecutionEvent; + private static readonly EventDescriptor M3PWorkflowLoadedFromDiskEvent; + private static readonly EventDescriptor M3PWorkflowManagerCheckpointEvent; + private static readonly EventDescriptor M3PWorkflowPersistedEvent; + private static readonly EventDescriptor M3PWorkflowPluginRequestedToShutdownEvent; + private static readonly EventDescriptor M3PWorkflowPluginRestartedEvent; + private static readonly EventDescriptor M3PWorkflowPluginStartedEvent; + private static readonly EventDescriptor M3PWorkflowQuotaViolatedEvent; + private static readonly EventDescriptor M3PWorkflowResumedEvent; + private static readonly EventDescriptor M3PWorkflowResumingEvent; + private static readonly EventDescriptor M3PWorkflowRunspacePoolCreatedEvent; + private static readonly EventDescriptor M3PWorkflowStateChangedEvent; + private static readonly EventDescriptor M3PWorkflowUnloadedEvent; + private static readonly EventDescriptor M3PWorkflowValidationErrorEvent; + private static readonly EventDescriptor M3PWorkflowValidationFinishedEvent; + private static readonly EventDescriptor M3PWorkflowValidationStartedEvent; /// /// Static constructor. diff --git a/src/powershell-unix/powershell-unix.csproj b/src/powershell-unix/powershell-unix.csproj index c113ceb8b30..d8a3f05812e 100644 --- a/src/powershell-unix/powershell-unix.csproj +++ b/src/powershell-unix/powershell-unix.csproj @@ -10,6 +10,8 @@ true true linux-x64;osx-x64; + true + true @@ -34,6 +36,10 @@ + + + + diff --git a/src/powershell-win-core/powershell-win-core.csproj b/src/powershell-win-core/powershell-win-core.csproj index 88e8b38d97a..6d4dd0db8c7 100644 --- a/src/powershell-win-core/powershell-win-core.csproj +++ b/src/powershell-win-core/powershell-win-core.csproj @@ -11,6 +11,8 @@ win7-x86;win7-x64 Microsoft.PowerShell ..\..\assets\pwsh.manifest + true + true @@ -51,6 +53,10 @@ + + + + diff --git a/src/powershell/Program.cs b/src/powershell/Program.cs index e4d3b51c5d6..01d5a4598a0 100644 --- a/src/powershell/Program.cs +++ b/src/powershell/Program.cs @@ -66,7 +66,9 @@ public static int Main(string[] args) #if UNIX AttemptExecPwshLogin(args); #endif +#pragma warning disable CA1062 // Validate arguments of public methods return UnmanagedPSEntry.Start(string.Empty, args, args.Length); +#pragma warning restore CA1062 // Validate arguments of public methods } #if UNIX diff --git a/test/xUnit/csharp/test_FileSystemProvider.cs b/test/xUnit/csharp/test_FileSystemProvider.cs index 268dbddef42..ef702d47bd6 100644 --- a/test/xUnit/csharp/test_FileSystemProvider.cs +++ b/test/xUnit/csharp/test_FileSystemProvider.cs @@ -24,8 +24,8 @@ namespace PSTests.Parallel { public class FileSystemProviderTests : IDisposable { - private string testPath; - private string testContent; + private readonly string testPath; + private readonly string testContent; public FileSystemProviderTests() { diff --git a/test/xUnit/csharp/test_PSConfiguration.cs b/test/xUnit/csharp/test_PSConfiguration.cs index 4bc38bdcfb4..6256db9b12b 100644 --- a/test/xUnit/csharp/test_PSConfiguration.cs +++ b/test/xUnit/csharp/test_PSConfiguration.cs @@ -374,7 +374,7 @@ internal void ForceReadingFromFile() public class PowerShellPolicyTests : IClassFixture { - private PowerShellPolicyFixture fixture; + private readonly PowerShellPolicyFixture fixture; public PowerShellPolicyTests(PowerShellPolicyFixture fixture) { diff --git a/test/xUnit/csharp/test_Runspace.cs b/test/xUnit/csharp/test_Runspace.cs index 3a7a6278bf6..bd8afb5746f 100644 --- a/test/xUnit/csharp/test_Runspace.cs +++ b/test/xUnit/csharp/test_Runspace.cs @@ -13,8 +13,8 @@ namespace PSTests.Sequential // otherwise Invoke will not return any objects public class RunspaceTests { - private static int count = 1; - private static string script = string.Format($"get-command get-command"); + private static readonly int count = 1; + private static readonly string script = string.Format($"get-command get-command"); [Fact] public void TestRunspaceWithPipeline()