From 3179552668bd54a3c39ad0b9a44d2a27742afa46 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Wed, 5 Feb 2020 11:39:35 +0000 Subject: [PATCH] Add readonly modifier to internal static members --- .../CimSessionOperations.cs | 22 ++++---- .../Utils.cs | 52 +++++++++---------- .../commands/management/Navigation.cs | 2 +- .../commands/management/Process.cs | 16 +++--- .../host/msh/CommandLineParameterParser.cs | 2 +- .../host/msh/ConsoleHostUserInterface.cs | 2 +- .../security/CertificateProvider.cs | 2 +- src/Microsoft.WSMan.Management/WsManHelper.cs | 4 +- .../CoreCLR/CorePsPlatform.cs | 2 +- .../common/BaseOutputtingCommand.cs | 2 +- .../FormatAndOutput/common/OutputManager.cs | 2 +- .../common/Utilities/MshParameter.cs | 2 +- .../Utilities/MshParameterAssociation.cs | 2 +- .../out-console/ConsoleLineOutput.cs | 2 +- .../engine/CommandDiscovery.cs | 4 +- .../engine/ExecutionContext.cs | 2 +- .../engine/InitialSessionState.cs | 24 ++++----- .../engine/LanguagePrimitives.cs | 6 +-- .../engine/Modules/AnalysisCache.cs | 2 +- .../engine/Modules/ModuleCmdletBase.cs | 6 +-- .../engine/Modules/ModuleIntrinsics.cs | 6 +-- .../engine/Modules/PSModuleInfo.cs | 2 +- .../engine/MshCommandRuntime.cs | 2 +- .../engine/MshObject.cs | 3 +- .../engine/MshObjectTypeDescriptor.cs | 2 +- .../engine/ParameterBinderBase.cs | 2 +- .../engine/PseudoParameters.cs | 2 +- .../engine/SpecialVariables.cs | 18 +++---- .../engine/TypeTable.cs | 2 +- .../engine/Utils.cs | 10 ++-- .../engine/interpreter/Utilities.cs | 4 +- .../engine/parser/Compiler.cs | 2 +- .../engine/parser/Parser.cs | 2 +- .../engine/parser/TypeResolver.cs | 6 +-- .../engine/parser/ast.cs | 2 +- .../NewPSSessionConfigurationOptionCommand.cs | 2 +- .../remoting/common/RunspaceConnectionInfo.cs | 2 +- .../fanin/InitialSessionStateProvider.cs | 2 +- .../engine/remoting/fanin/WSManPlugin.cs | 2 +- .../remoting/fanin/WSManPluginFacade.cs | 2 +- .../engine/runtime/CompiledScriptBlock.cs | 2 +- .../engine/runtime/Operations/NumericOps.cs | 4 +- .../engine/serialization.cs | 2 +- .../help/CabinetAPI.cs | 2 +- .../help/DefaultCommandHelpObjectBuilder.cs | 2 +- .../namespaces/FileSystemProvider.cs | 12 ++--- .../namespaces/ProviderBase.cs | 2 +- .../security/SecureStringHelper.cs | 2 +- .../security/SecuritySupport.cs | 8 +-- .../utils/EncodingUtils.cs | 2 +- .../utils/PlatformInvokes.cs | 18 +++---- 51 files changed, 145 insertions(+), 144 deletions(-) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs index 28d93fc668a..fb6a5f5972e 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs @@ -180,44 +180,44 @@ internal class CimSessionState : IDisposable /// where is the next available session number. /// For example, CimSession1, CimSession2, etc... /// - internal static string CimSessionClassName = "CimSession"; + internal static readonly string CimSessionClassName = "CimSession"; /// /// CimSession object name. /// - internal static string CimSessionObject = "{CimSession Object}"; + internal static readonly string CimSessionObject = "{CimSession Object}"; /// /// /// CimSession object path, which is identifying a cimsession object /// /// - internal static string SessionObjectPath = @"CimSession id = {0}, name = {2}, ComputerName = {3}, instance id = {1}"; + internal static readonly string SessionObjectPath = @"CimSession id = {0}, name = {2}, ComputerName = {3}, instance id = {1}"; /// /// Id property name of cimsession wrapper object. /// - internal static string idPropName = "Id"; + internal static readonly string idPropName = "Id"; /// /// Instanceid property name of cimsession wrapper object. /// - internal static string instanceidPropName = "InstanceId"; + internal static readonly string instanceidPropName = "InstanceId"; /// /// Name property name of cimsession wrapper object. /// - internal static string namePropName = "Name"; + internal static readonly string namePropName = "Name"; /// /// Computer name property name of cimsession object. /// - internal static string computernamePropName = "ComputerName"; + internal static readonly string computernamePropName = "ComputerName"; /// /// Protocol name property name of cimsession object. /// - internal static string protocolPropName = "Protocol"; + internal static readonly string protocolPropName = "Protocol"; /// /// @@ -813,7 +813,7 @@ public CimSessionBase() /// can running parallelly under more than one runspace(s). /// /// - internal static ConcurrentDictionary cimSessions + internal static readonly ConcurrentDictionary cimSessions = new ConcurrentDictionary(); /// @@ -821,7 +821,7 @@ internal static ConcurrentDictionary cimSessions /// Default runspace Id. /// /// - internal static Guid defaultRunspaceId = Guid.Empty; + internal static readonly Guid defaultRunspaceId = Guid.Empty; /// /// @@ -1209,7 +1209,7 @@ internal class CimRemoveSession : CimSessionBase /// /// Remove session action string. /// - internal static string RemoveCimSessionActionName = "Remove CimSession"; + internal static readonly string RemoveCimSessionActionName = "Remove CimSession"; /// /// Constructor. diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs index 76ba5c12a49..f46793eb50b 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs @@ -27,47 +27,47 @@ internal static class ConstValue /// Default computername /// /// - internal static string[] DefaultSessionName = { @"*" }; + internal static readonly string[] DefaultSessionName = { @"*" }; /// /// /// Empty computername, which will create DCOM session /// /// - internal static string NullComputerName = null; + internal static readonly string NullComputerName = null; /// /// /// Empty computername array, which will create DCOM session /// /// - internal static string[] NullComputerNames = { NullComputerName }; + internal static readonly string[] NullComputerNames = { NullComputerName }; /// /// /// localhost computername, which will create WSMAN session /// /// - internal static string LocalhostComputerName = @"localhost"; + internal static readonly string LocalhostComputerName = @"localhost"; /// /// /// Default namespace /// /// - internal static string DefaultNameSpace = @"root\cimv2"; + internal static readonly string DefaultNameSpace = @"root\cimv2"; /// /// /// Default namespace /// /// - internal static string DefaultQueryDialect = @"WQL"; + internal static readonly string DefaultQueryDialect = @"WQL"; /// /// Name of the note property that controls if "PSComputerName" column is shown. /// - internal static string ShowComputerNameNoteProperty = "PSShowComputerName"; + internal static readonly string ShowComputerNameNoteProperty = "PSShowComputerName"; /// /// @@ -169,17 +169,17 @@ internal static bool GenerateVerboseMessage /// /// Flag used to control generating message into powershell. /// - internal static string logFile = @"c:\temp\Cim.log"; + internal static readonly string logFile = @"c:\temp\Cim.log"; /// /// Indent space string. /// - internal static string space = @" "; + internal static readonly string space = @" "; /// /// Indent space strings array. /// - internal static string[] spaces = { + internal static readonly string[] spaces = { string.Empty, space, space + space, @@ -191,26 +191,26 @@ internal static bool GenerateVerboseMessage /// /// Lock the log file. /// - internal static object logLock = new object(); + internal static readonly object logLock = new object(); #endregion #region internal strings - internal static string runspaceStateChanged = "Runspace {0} state changed to {1}"; - internal static string classDumpInfo = @"Class type is {0}"; - internal static string propertyDumpInfo = @"Property name {0} of type {1}, its value is {2}"; - internal static string defaultPropertyType = @"It is a default property, default value is {0}"; - internal static string propertyValueSet = @"This property value is set by user {0}"; - internal static string addParameterSetName = @"Add parameter set {0} name to cache"; - internal static string removeParameterSetName = @"Remove parameter set {0} name from cache"; - internal static string currentParameterSetNameCount = @"Cache have {0} parameter set names"; - internal static string currentParameterSetNameInCache = @"Cache have parameter set {0} valid {1}"; - internal static string currentnonMandatoryParameterSetInCache = @"Cache have optional parameter set {0} valid {1}"; - internal static string optionalParameterSetNameCount = @"Cache have {0} optional parameter set names"; - internal static string finalParameterSetName = @"------Final parameter set name of the cmdlet is {0}"; - internal static string addToOptionalParameterSet = @"Add to optional ParameterSetNames {0}"; - internal static string startToResolveParameterSet = @"------Resolve ParameterSet Name"; - internal static string reservedString = @"------"; + internal static readonly string runspaceStateChanged = "Runspace {0} state changed to {1}"; + internal static readonly string classDumpInfo = @"Class type is {0}"; + internal static readonly string propertyDumpInfo = @"Property name {0} of type {1}, its value is {2}"; + internal static readonly string defaultPropertyType = @"It is a default property, default value is {0}"; + internal static readonly string propertyValueSet = @"This property value is set by user {0}"; + internal static readonly string addParameterSetName = @"Add parameter set {0} name to cache"; + internal static readonly string removeParameterSetName = @"Remove parameter set {0} name from cache"; + internal static readonly string currentParameterSetNameCount = @"Cache have {0} parameter set names"; + internal static readonly string currentParameterSetNameInCache = @"Cache have parameter set {0} valid {1}"; + internal static readonly string currentnonMandatoryParameterSetInCache = @"Cache have optional parameter set {0} valid {1}"; + internal static readonly string optionalParameterSetNameCount = @"Cache have {0} optional parameter set names"; + internal static readonly string finalParameterSetName = @"------Final parameter set name of the cmdlet is {0}"; + internal static readonly string addToOptionalParameterSet = @"Add to optional ParameterSetNames {0}"; + internal static readonly string startToResolveParameterSet = @"------Resolve ParameterSet Name"; + internal static readonly string reservedString = @"------"; #endregion #region runtime methods diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs index 564a8daf3ec..4389f657f69 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs @@ -26,7 +26,7 @@ public abstract class CoreCommandBase : PSCmdlet, IDynamicParameters /// using "NavigationCommands" as the category. /// [Dbg.TraceSourceAttribute("NavigationCommands", "The namespace navigation tracer")] - internal static Dbg.PSTraceSource tracer = Dbg.PSTraceSource.GetTracer("NavigationCommands", "The namespace navigation tracer"); + internal static readonly Dbg.PSTraceSource tracer = Dbg.PSTraceSource.GetTracer("NavigationCommands", "The namespace navigation tracer"); #endregion Tracer diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs index 3a23322fff2..91665575118 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs @@ -2700,14 +2700,14 @@ internal struct JOBOBJECT_BASIC_PROCESS_ID_LIST internal static class ProcessNativeMethods { // Fields - internal static UInt32 GENERIC_READ = 0x80000000; - internal static UInt32 GENERIC_WRITE = 0x40000000; - internal static UInt32 FILE_ATTRIBUTE_NORMAL = 0x80000000; - internal static UInt32 CREATE_ALWAYS = 2; - internal static UInt32 FILE_SHARE_WRITE = 0x00000002; - internal static UInt32 FILE_SHARE_READ = 0x00000001; - internal static UInt32 OF_READWRITE = 0x00000002; - internal static UInt32 OPEN_EXISTING = 3; + internal static readonly UInt32 GENERIC_READ = 0x80000000; + internal static readonly UInt32 GENERIC_WRITE = 0x40000000; + internal static readonly UInt32 FILE_ATTRIBUTE_NORMAL = 0x80000000; + internal static readonly UInt32 CREATE_ALWAYS = 2; + internal static readonly UInt32 FILE_SHARE_WRITE = 0x00000002; + internal static readonly UInt32 FILE_SHARE_READ = 0x00000001; + internal static readonly UInt32 OF_READWRITE = 0x00000002; + internal static readonly UInt32 OPEN_EXISTING = 3; // Methods diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs index 5e020c9ac65..ba90c7dd04e 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs @@ -183,7 +183,7 @@ internal class CommandLineParameterParser private const int MaxPipePathLengthLinux = 108; private const int MaxPipePathLengthMacOS = 104; - internal static string[] validParameters = { + internal static readonly string[] validParameters = { "sta", "mta", "command", diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs index cec08818f50..a4d0e91f540 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs @@ -1422,7 +1422,7 @@ public override void WriteErrorLine(string value) // We use System.Environment.NewLine because we are platform-agnostic - internal static string Crlf = System.Environment.NewLine; + internal static readonly string Crlf = System.Environment.NewLine; private const string Tab = "\x0009"; diff --git a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs index 6e524eff3de..3579ce7b46f 100644 --- a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs +++ b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs @@ -3386,7 +3386,7 @@ internal static class Crypt32Helpers /// private static object s_staticLock = new object(); - internal static List storeNames = new List(); + internal static readonly List storeNames = new List(); /// /// Get a list of store names at the specified location. diff --git a/src/Microsoft.WSMan.Management/WsManHelper.cs b/src/Microsoft.WSMan.Management/WsManHelper.cs index a1ce8af4214..db6d33b0649 100644 --- a/src/Microsoft.WSMan.Management/WsManHelper.cs +++ b/src/Microsoft.WSMan.Management/WsManHelper.cs @@ -94,7 +94,7 @@ internal class Sessions /// /// Dictionary object to store the connection. /// - internal static Dictionary SessionObjCache = new Dictionary(); + internal static readonly Dictionary SessionObjCache = new Dictionary(); ~Sessions() { @@ -102,7 +102,7 @@ internal class Sessions } } - internal static Sessions AutoSession = new Sessions(); + internal static readonly Sessions AutoSession = new Sessions(); // // // diff --git a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs index 96ba4cd28fb..c6ac57070cb 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs @@ -155,7 +155,7 @@ public static bool IsWindowsDesktop #endif // format files - internal static List FormatFileNames = new List + internal static readonly List FormatFileNames = new List { "Certificate.format.ps1xml", "Diagnostics.format.ps1xml", diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs index 2eea9f50c46..bb8305b2fdc 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs @@ -18,7 +18,7 @@ internal class OutCommandInner : ImplementationCommandBase { #region tracer [TraceSource("format_out_OutCommandInner", "OutCommandInner")] - internal static PSTraceSource tracer = PSTraceSource.GetTracer("format_out_OutCommandInner", "OutCommandInner"); + internal static readonly PSTraceSource tracer = PSTraceSource.GetTracer("format_out_OutCommandInner", "OutCommandInner"); #endregion tracer internal override void BeginProcessing() diff --git a/src/System.Management.Automation/FormatAndOutput/common/OutputManager.cs b/src/System.Management.Automation/FormatAndOutput/common/OutputManager.cs index 861a3ab6405..b07731c3e04 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/OutputManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/OutputManager.cs @@ -20,7 +20,7 @@ internal sealed class OutputManagerInner : ImplementationCommandBase { #region tracer [TraceSource("format_out_OutputManagerInner", "OutputManagerInner")] - internal static PSTraceSource tracer = PSTraceSource.GetTracer("format_out_OutputManagerInner", "OutputManagerInner"); + internal static readonly PSTraceSource tracer = PSTraceSource.GetTracer("format_out_OutputManagerInner", "OutputManagerInner"); #endregion tracer #region LineOutput diff --git a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameter.cs b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameter.cs index c9d509abeef..d04008a1f9a 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameter.cs @@ -228,7 +228,7 @@ internal sealed class ParameterProcessor { #region tracer [TraceSource("ParameterProcessor", "ParameterProcessor")] - internal static PSTraceSource tracer = PSTraceSource.GetTracer("ParameterProcessor", "ParameterProcessor"); + internal static readonly PSTraceSource tracer = PSTraceSource.GetTracer("ParameterProcessor", "ParameterProcessor"); #endregion tracer internal static void ThrowParameterBindingException(TerminatingErrorContext invocationContext, diff --git a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameterAssociation.cs b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameterAssociation.cs index 7042bf85dd1..22b4c47ee40 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameterAssociation.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameterAssociation.cs @@ -16,7 +16,7 @@ internal sealed class MshResolvedExpressionParameterAssociation { #region tracer [TraceSource("MshResolvedExpressionParameterAssociation", "MshResolvedExpressionParameterAssociation")] - internal static PSTraceSource tracer = PSTraceSource.GetTracer("MshResolvedExpressionParameterAssociation", + internal static readonly PSTraceSource tracer = PSTraceSource.GetTracer("MshResolvedExpressionParameterAssociation", "MshResolvedExpressionParameterAssociation"); #endregion tracer diff --git a/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs b/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs index b0fe26cfd49..b6cde18fb65 100644 --- a/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs +++ b/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs @@ -153,7 +153,7 @@ internal sealed class ConsoleLineOutput : LineOutput { #region tracer [TraceSource("ConsoleLineOutput", "ConsoleLineOutput")] - internal static PSTraceSource tracer = PSTraceSource.GetTracer("ConsoleLineOutput", "ConsoleLineOutput"); + internal static readonly PSTraceSource tracer = PSTraceSource.GetTracer("ConsoleLineOutput", "ConsoleLineOutput"); #endregion tracer #region LineOutput implementation diff --git a/src/System.Management.Automation/engine/CommandDiscovery.cs b/src/System.Management.Automation/engine/CommandDiscovery.cs index 4b58da58cb6..4737fe18d78 100644 --- a/src/System.Management.Automation/engine/CommandDiscovery.cs +++ b/src/System.Management.Automation/engine/CommandDiscovery.cs @@ -115,7 +115,7 @@ public enum PSModuleAutoLoadingPreference internal class CommandDiscovery { [TraceSource("CommandDiscovery", "Traces the discovery of cmdlets, scripts, functions, applications, etc.")] - internal static PSTraceSource discoveryTracer = + internal static readonly PSTraceSource discoveryTracer = PSTraceSource.GetTracer( "CommandDiscovery", "Traces the discovery of cmdlets, scripts, functions, applications, etc.", @@ -1710,7 +1710,7 @@ internal Collection IndexOfRelativePath() [EventSource(Name = "Microsoft-PowerShell-CommandDiscovery")] internal class CommandDiscoveryEventSource : EventSource { - internal static CommandDiscoveryEventSource Log = new CommandDiscoveryEventSource(); + internal static readonly CommandDiscoveryEventSource Log = new CommandDiscoveryEventSource(); public void CommandLookupStart(string CommandName) { WriteEvent(1, CommandName); } diff --git a/src/System.Management.Automation/engine/ExecutionContext.cs b/src/System.Management.Automation/engine/ExecutionContext.cs index 592b4554811..98f0b3deb5a 100644 --- a/src/System.Management.Automation/engine/ExecutionContext.cs +++ b/src/System.Management.Automation/engine/ExecutionContext.cs @@ -492,7 +492,7 @@ internal bool UseFullLanguageModeInDebugger } } - internal static List ModulesWithJobSourceAdapters = new List + internal static readonly List ModulesWithJobSourceAdapters = new List { Utils.ScheduledJobModuleName, }; diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index 6032259bea6..0d2e1274aa6 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -4435,7 +4435,7 @@ .ForwardHelpCategory Cmdlet internal const bool DefaultWhatIfPreference = false; internal const ConfirmImpact DefaultConfirmPreference = ConfirmImpact.High; - internal static SessionStateVariableEntry[] BuiltInVariables = new SessionStateVariableEntry[] + internal static readonly SessionStateVariableEntry[] BuiltInVariables = new SessionStateVariableEntry[] { // Engine variables that should be precreated before running profile // Bug fix for Win7:2202228 Engine halts if initial command fulls up variable table @@ -4772,11 +4772,11 @@ internal static SessionStateAliasEntry[] BuiltInAliases internal const string DefaultSetDriveFunctionText = "Set-Location $MyInvocation.MyCommand.Name"; - internal static ScriptBlock SetDriveScriptBlock = ScriptBlock.CreateDelayParsedScriptBlock(DefaultSetDriveFunctionText, isProductCode: true); + internal static readonly ScriptBlock SetDriveScriptBlock = ScriptBlock.CreateDelayParsedScriptBlock(DefaultSetDriveFunctionText, isProductCode: true); private static PSLanguageMode systemLanguageMode = (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) ? PSLanguageMode.ConstrainedLanguage : PSLanguageMode.FullLanguage; - internal static SessionStateFunctionEntry[] BuiltInFunctions = new SessionStateFunctionEntry[] + internal static readonly SessionStateFunctionEntry[] BuiltInFunctions = new SessionStateFunctionEntry[] { // Functions that don't require full language mode SessionStateFunctionEntry.GetDelayParsedFunctionEntry("cd..", "Set-Location ..", isProductCode: true, languageMode: systemLanguageMode), @@ -4843,12 +4843,12 @@ internal static void RemoveAllDrivesForProvider(ProviderInfo pi, SessionStateInt private static 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"; + internal static readonly string CoreSnapin = "Microsoft.PowerShell.Core"; + internal static readonly string CoreModule = "Microsoft.PowerShell.Core"; internal Collection defaultSnapins = new Collection(); // The list of engine modules to create warnings when you try to remove them - internal static HashSet EngineModules = new HashSet(StringComparer.OrdinalIgnoreCase) + internal static readonly HashSet EngineModules = new HashSet(StringComparer.OrdinalIgnoreCase) { "Microsoft.PowerShell.Utility", "Microsoft.PowerShell.Management", @@ -4858,7 +4858,7 @@ internal static void RemoveAllDrivesForProvider(ProviderInfo pi, SessionStateInt "Microsoft.WSMan.Management" }; - internal static HashSet NestedEngineModules = new HashSet(StringComparer.OrdinalIgnoreCase) + internal static readonly HashSet NestedEngineModules = new HashSet(StringComparer.OrdinalIgnoreCase) { "Microsoft.PowerShell.Commands.Utility", "Microsoft.PowerShell.Commands.Management", @@ -4866,7 +4866,7 @@ internal static void RemoveAllDrivesForProvider(ProviderInfo pi, SessionStateInt "Microsoft.PowerShell.ConsoleHost" }; - internal static Dictionary EngineModuleNestedModuleMapping = new Dictionary(StringComparer.OrdinalIgnoreCase) + internal static readonly Dictionary EngineModuleNestedModuleMapping = new Dictionary(StringComparer.OrdinalIgnoreCase) { { "Microsoft.PowerShell.Utility", "Microsoft.PowerShell.Commands.Utility"}, { "Microsoft.PowerShell.Management", "Microsoft.PowerShell.Commands.Management"}, @@ -4874,7 +4874,7 @@ internal static void RemoveAllDrivesForProvider(ProviderInfo pi, SessionStateInt { "Microsoft.PowerShell.Host", "Microsoft.PowerShell.ConsoleHost"}, }; - internal static Dictionary NestedModuleEngineModuleMapping = new Dictionary(StringComparer.OrdinalIgnoreCase) + internal static readonly Dictionary NestedModuleEngineModuleMapping = new Dictionary(StringComparer.OrdinalIgnoreCase) { { "Microsoft.PowerShell.Commands.Utility", "Microsoft.PowerShell.Utility"}, { "Microsoft.PowerShell.Commands.Management", "Microsoft.PowerShell.Management"}, @@ -4885,13 +4885,13 @@ internal static void RemoveAllDrivesForProvider(ProviderInfo pi, SessionStateInt }; // The list of engine modules that we will not allow users to remove - internal static HashSet ConstantEngineModules = new HashSet(StringComparer.OrdinalIgnoreCase) + internal static readonly HashSet ConstantEngineModules = new HashSet(StringComparer.OrdinalIgnoreCase) { CoreModule, }; // The list of nested engine modules that we will not allow users to remove - internal static HashSet ConstantEngineNestedModules = new HashSet(StringComparer.OrdinalIgnoreCase) + internal static readonly HashSet ConstantEngineNestedModules = new HashSet(StringComparer.OrdinalIgnoreCase) { "System.Management.Automation", }; @@ -5493,7 +5493,7 @@ private static string GetHelpFile(string assemblyPath) [EventSource(Name = "Microsoft-PowerShell-Runspaces")] internal class RunspaceEventSource : EventSource { - internal static RunspaceEventSource Log = new RunspaceEventSource(); + internal static readonly RunspaceEventSource Log = new RunspaceEventSource(); public void OpenRunspaceStart() { WriteEvent(1); } diff --git a/src/System.Management.Automation/engine/LanguagePrimitives.cs b/src/System.Management.Automation/engine/LanguagePrimitives.cs index 83690003bf7..16ffc89b809 100644 --- a/src/System.Management.Automation/engine/LanguagePrimitives.cs +++ b/src/System.Management.Automation/engine/LanguagePrimitives.cs @@ -1112,7 +1112,7 @@ internal static int TypeTableIndex(Type type) /// an exception when converted to decimal. /// The order of lines and columns cannot be changed since NumericCompare depends on it. /// - internal static Type[][] LargestTypeTable = new Type[][] + internal static readonly Type[][] LargestTypeTable = new Type[][] { // System.Int16 System.Int32 System.Int64 System.UInt16 System.UInt32 System.UInt64 System.SByte System.Byte System.Single System.Double System.Decimal /* System.Int16 */new Type[] { typeof(System.Int16), typeof(System.Int32), typeof(System.Int64), typeof(System.Int32), typeof(System.Int64), typeof(System.Double), typeof(System.Int16), typeof(System.Int16), typeof(System.Single), typeof(System.Double), typeof(System.Decimal) }, @@ -1423,8 +1423,8 @@ internal static void DoConversionsForSetInGenericDictionary(IDictionary dictiona #region type converter - internal static PSTraceSource typeConversion = PSTraceSource.GetTracer("TypeConversion", "Traces the type conversion algorithm", false); - internal static ConversionData NoConversion = new ConversionData(ConvertNoConversion, ConversionRank.None); + internal static readonly PSTraceSource typeConversion = PSTraceSource.GetTracer("TypeConversion", "Traces the type conversion algorithm", false); + internal static readonly ConversionData NoConversion = new ConversionData(ConvertNoConversion, ConversionRank.None); private static TypeConverter GetIntegerSystemConverter(Type type) { diff --git a/src/System.Management.Automation/engine/Modules/AnalysisCache.cs b/src/System.Management.Automation/engine/Modules/AnalysisCache.cs index 324922e9daa..4baa7cc6bfa 100644 --- a/src/System.Management.Automation/engine/Modules/AnalysisCache.cs +++ b/src/System.Management.Automation/engine/Modules/AnalysisCache.cs @@ -35,7 +35,7 @@ internal class AnalysisCache private static ConcurrentDictionary s_modulesBeingAnalyzed = new ConcurrentDictionary( /*concurrency*/1, /*capacity*/2, StringComparer.OrdinalIgnoreCase); - internal static char[] InvalidCommandNameCharacters = new[] + internal static readonly char[] InvalidCommandNameCharacters = new[] { '#', ',', '(', ')', '{', '}', '[', ']', '&', '/', '\\', '$', '^', ';', ':', '"', '\'', '<', '>', '|', '?', '@', '`', '*', '%', '+', '=', '~' diff --git a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs index ebf89ed90cc..8e2e9c519ef 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs @@ -237,10 +237,10 @@ internal List MatchAll private List _matchAll; // The list of commands permitted in a module manifest - internal static string[] PermittedCmdlets = new string[] { + internal static readonly string[] PermittedCmdlets = new string[] { "Import-LocalizedData", "ConvertFrom-StringData", "Write-Host", "Out-Host", "Join-Path" }; - internal static string[] ModuleManifestMembers = new string[] { + internal static readonly string[] ModuleManifestMembers = new string[] { "ModuleToProcess", "NestedModules", "GUID", @@ -303,7 +303,7 @@ internal List MatchAll /// /// Synchronization object for creation/cleanup of WindowsPS compat remoting session. /// - internal static object s_WindowsPowerShellCompatSyncObject = new object(); + internal static readonly object s_WindowsPowerShellCompatSyncObject = new object(); private Dictionary _currentlyProcessingModules = new Dictionary(); diff --git a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs index a4d343131f3..11af91cd4e8 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs @@ -32,7 +32,7 @@ public class ModuleIntrinsics /// Tracer for module analysis. /// [TraceSource("Modules", "Module loading and analysis")] - internal static PSTraceSource Tracer = PSTraceSource.GetTracer("Modules", "Module loading and analysis"); + internal static readonly PSTraceSource Tracer = PSTraceSource.GetTracer("Modules", "Module loading and analysis"); // The %WINDIR%\System32\WindowsPowerShell\v1.0\Modules module path, // to load forward compatible Windows PowerShell modules from @@ -895,7 +895,7 @@ internal static ExperimentalFeature[] GetExperimentalFeature(string manifestPath } // The extensions of all of the files that can be processed with Import-Module, put the ni.dll in front of .dll to have higher priority to be loaded. - internal static string[] PSModuleProcessableExtensions = new string[] { + internal static readonly string[] PSModuleProcessableExtensions = new string[] { StringLiterals.PowerShellDataFileExtension, StringLiterals.PowerShellScriptFileExtension, StringLiterals.PowerShellModuleFileExtension, @@ -906,7 +906,7 @@ internal static ExperimentalFeature[] GetExperimentalFeature(string manifestPath }; // A list of the extensions to check for implicit module loading and discovery, put the ni.dll in front of .dll to have higher priority to be loaded. - internal static string[] PSModuleExtensions = new string[] { + internal static readonly string[] PSModuleExtensions = new string[] { StringLiterals.PowerShellDataFileExtension, StringLiterals.PowerShellModuleFileExtension, StringLiterals.PowerShellCmdletizationFileExtension, diff --git a/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs b/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs index af0b93567b6..15e2495e4fd 100644 --- a/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs +++ b/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs @@ -1093,7 +1093,7 @@ private static void AddModuleToList(PSModuleInfo module, List modu moduleList.Add(module); } - internal static string[] _builtinVariables = new string[] { "_", "this", "input", "args", "true", "false", "null", + internal static readonly string[] _builtinVariables = new string[] { "_", "this", "input", "args", "true", "false", "null", "PSDefaultParameterValues", "Error", "PSScriptRoot", "PSCommandPath", "MyInvocation", "ExecutionContext", "StackTrace" }; /// diff --git a/src/System.Management.Automation/engine/MshCommandRuntime.cs b/src/System.Management.Automation/engine/MshCommandRuntime.cs index 2c4396de1c4..4d07cd3d3a8 100644 --- a/src/System.Management.Automation/engine/MshCommandRuntime.cs +++ b/src/System.Management.Automation/engine/MshCommandRuntime.cs @@ -2231,7 +2231,7 @@ internal object[] GetResultsAsArray() /// An empty array that is declared statically so we don't keep /// allocating them over and over... /// - internal static object[] StaticEmptyArray = Array.Empty(); + internal static readonly object[] StaticEmptyArray = Array.Empty(); /// /// Gets or sets the error pipe. diff --git a/src/System.Management.Automation/engine/MshObject.cs b/src/System.Management.Automation/engine/MshObject.cs index 12a677bdd72..e7bfeec31d2 100644 --- a/src/System.Management.Automation/engine/MshObject.cs +++ b/src/System.Management.Automation/engine/MshObject.cs @@ -2466,7 +2466,8 @@ public class PSCustomObject /// private PSCustomObject() { } - internal static PSCustomObject SelfInstance = new PSCustomObject(); + internal static readonly PSCustomObject SelfInstance = new PSCustomObject(); + /// /// Returns an empty string. /// diff --git a/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs b/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs index 3beae965b55..ee54859a1ea 100644 --- a/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs +++ b/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs @@ -330,7 +330,7 @@ private void DealWithSetValueException(ExtendedTypeSystemException e, out bool s /// public class PSObjectTypeDescriptor : CustomTypeDescriptor { - internal static PSTraceSource typeDescriptor = PSTraceSource.GetTracer("TypeDescriptor", "Traces the behavior of PSObjectTypeDescriptor, PSObjectTypeDescriptionProvider and PSObjectPropertyDescriptor.", false); + internal static readonly PSTraceSource typeDescriptor = PSTraceSource.GetTracer("TypeDescriptor", "Traces the behavior of PSObjectTypeDescriptor, PSObjectTypeDescriptionProvider and PSObjectPropertyDescriptor.", false); /// /// Occurs when there was an exception setting the value of a property. diff --git a/src/System.Management.Automation/engine/ParameterBinderBase.cs b/src/System.Management.Automation/engine/ParameterBinderBase.cs index 9823c090c48..4dcb5488041 100644 --- a/src/System.Management.Automation/engine/ParameterBinderBase.cs +++ b/src/System.Management.Automation/engine/ParameterBinderBase.cs @@ -61,7 +61,7 @@ internal abstract class ParameterBinderBase private static 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 = + internal static readonly PSTraceSource bindingTracer = PSTraceSource.GetTracer( "ParameterBinding", "Traces the process of binding the arguments to the parameters of cmdlets, scripts, and applications.", diff --git a/src/System.Management.Automation/engine/PseudoParameters.cs b/src/System.Management.Automation/engine/PseudoParameters.cs index bccb2fb3f37..78ef034cf5b 100644 --- a/src/System.Management.Automation/engine/PseudoParameters.cs +++ b/src/System.Management.Automation/engine/PseudoParameters.cs @@ -236,6 +236,6 @@ public string HelpFile /// public object Data { get; set; } - internal static RuntimeDefinedParameter[] EmptyParameterArray = new RuntimeDefinedParameter[0]; + internal static readonly RuntimeDefinedParameter[] EmptyParameterArray = new RuntimeDefinedParameter[0]; } } diff --git a/src/System.Management.Automation/engine/SpecialVariables.cs b/src/System.Management.Automation/engine/SpecialVariables.cs index 5c4c4ba2f49..aa241b6c942 100644 --- a/src/System.Management.Automation/engine/SpecialVariables.cs +++ b/src/System.Management.Automation/engine/SpecialVariables.cs @@ -181,40 +181,40 @@ internal static class SpecialVariables internal const string pwd = "PWD"; - internal static VariablePath PWDVarPath = new VariablePath("global:" + pwd); + internal static readonly VariablePath PWDVarPath = new VariablePath("global:" + pwd); internal const string Null = "null"; - internal static VariablePath NullVarPath = new VariablePath("null"); + internal static readonly VariablePath NullVarPath = new VariablePath("null"); internal const string True = "true"; - internal static VariablePath TrueVarPath = new VariablePath("true"); + internal static readonly VariablePath TrueVarPath = new VariablePath("true"); internal const string False = "false"; - internal static VariablePath FalseVarPath = new VariablePath("false"); + internal static readonly VariablePath FalseVarPath = new VariablePath("false"); internal const string PSModuleAutoLoading = "PSModuleAutoLoadingPreference"; - internal static VariablePath PSModuleAutoLoadingPreferenceVarPath = new VariablePath("global:" + PSModuleAutoLoading); + internal static readonly VariablePath PSModuleAutoLoadingPreferenceVarPath = new VariablePath("global:" + PSModuleAutoLoading); #region Platform Variables internal const string IsLinux = "IsLinux"; - internal static VariablePath IsLinuxPath = new VariablePath("IsLinux"); + internal static readonly VariablePath IsLinuxPath = new VariablePath("IsLinux"); internal const string IsMacOS = "IsMacOS"; - internal static VariablePath IsMacOSPath = new VariablePath("IsMacOS"); + internal static readonly VariablePath IsMacOSPath = new VariablePath("IsMacOS"); internal const string IsWindows = "IsWindows"; - internal static VariablePath IsWindowsPath = new VariablePath("IsWindows"); + internal static readonly VariablePath IsWindowsPath = new VariablePath("IsWindows"); internal const string IsCoreCLR = "IsCoreCLR"; - internal static VariablePath IsCoreCLRPath = new VariablePath("IsCoreCLR"); + internal static readonly VariablePath IsCoreCLRPath = new VariablePath("IsCoreCLR"); #endregion #region Preference Variables diff --git a/src/System.Management.Automation/engine/TypeTable.cs b/src/System.Management.Automation/engine/TypeTable.cs index 0f2fab28cc0..2b0c0eb2ed0 100644 --- a/src/System.Management.Automation/engine/TypeTable.cs +++ b/src/System.Management.Automation/engine/TypeTable.cs @@ -1681,7 +1681,7 @@ public ConsolidatedString(IEnumerable strings) internal static readonly ConsolidatedString Empty = new ConsolidatedString(Array.Empty()); - internal static IEqualityComparer EqualityComparer = new ConsolidatedStringEqualityComparer(); + internal static readonly IEqualityComparer EqualityComparer = new ConsolidatedStringEqualityComparer(); private class ConsolidatedStringEqualityComparer : IEqualityComparer { diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index 14b7f9d55bf..12374148fa7 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -302,7 +302,7 @@ internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int /// /// Allowed PowerShell Editions. /// - internal static string[] AllowedEditionValues = { "Desktop", "Core" }; + internal static readonly string[] AllowedEditionValues = { "Desktop", "Core" }; /// /// Helper fn to check byte[] arg for null. @@ -736,7 +736,7 @@ internal static bool IsValidPSEditionValue(string editionValue) /// The subdirectory of module paths /// e.g. ~\Documents\WindowsPowerShell\Modules and %ProgramFiles%\WindowsPowerShell\Modules. /// - internal static string ModuleDirectory = Path.Combine(ProductNameForDirectory, "Modules"); + internal static readonly string ModuleDirectory = Path.Combine(ProductNameForDirectory, "Modules"); internal static readonly ConfigScope[] SystemWideOnlyConfig = new[] { ConfigScope.AllUsers }; internal static readonly ConfigScope[] CurrentUserOnlyConfig = new[] { ConfigScope.CurrentUser }; @@ -1457,11 +1457,11 @@ internal static Encoding GetEncoding(string path) } // BigEndianUTF32 encoding is possible, but requires creation - internal static Encoding BigEndianUTF32Encoding = new UTF32Encoding(bigEndian: true, byteOrderMark: true); + internal static readonly Encoding BigEndianUTF32Encoding = new UTF32Encoding(bigEndian: true, byteOrderMark: true); // [System.Text.Encoding]::GetEncodings() | Where-Object { $_.GetEncoding().GetPreamble() } | // Add-Member ScriptProperty Preamble { $this.GetEncoding().GetPreamble() -join "-" } -PassThru | // Format-Table -Auto - internal static Dictionary encodingMap = + internal static readonly Dictionary encodingMap = new Dictionary() { { "255-254", Encoding.Unicode }, @@ -1471,7 +1471,7 @@ internal static Encoding GetEncoding(string path) { "239-187-191", Encoding.UTF8 }, }; - internal static char[] nonPrintableCharacters = { + internal static readonly char[] nonPrintableCharacters = { (char) 0, (char) 1, (char) 2, (char) 3, (char) 4, (char) 5, (char) 6, (char) 7, (char) 8, (char) 11, (char) 12, (char) 14, (char) 15, (char) 16, (char) 17, (char) 18, (char) 19, (char) 20, (char) 21, (char) 22, (char) 23, (char) 24, (char) 25, (char) 26, (char) 28, (char) 29, (char) 30, diff --git a/src/System.Management.Automation/engine/interpreter/Utilities.cs b/src/System.Management.Automation/engine/interpreter/Utilities.cs index baba0a41fa4..2ff8dbf9790 100644 --- a/src/System.Management.Automation/engine/interpreter/Utilities.cs +++ b/src/System.Management.Automation/engine/interpreter/Utilities.cs @@ -239,8 +239,8 @@ internal static object BooleanToObject(bool b) internal static readonly MethodInfo BooleanToObjectMethod = typeof(ScriptingRuntimeHelpers).GetMethod("BooleanToObject"); internal static readonly MethodInfo Int32ToObjectMethod = typeof(ScriptingRuntimeHelpers).GetMethod("Int32ToObject"); - internal static object True = true; - internal static object False = false; + internal static readonly object True = true; + internal static readonly object False = false; internal static object GetPrimitiveDefaultValue(Type type) { diff --git a/src/System.Management.Automation/engine/parser/Compiler.cs b/src/System.Management.Automation/engine/parser/Compiler.cs index 07e36bcdf75..25cee9e73e8 100644 --- a/src/System.Management.Automation/engine/parser/Compiler.cs +++ b/src/System.Management.Automation/engine/parser/Compiler.cs @@ -669,7 +669,7 @@ internal static class ExpressionCache // Empty expression is used at the end of blocks to give them the void expression result internal static readonly Expression Empty = Expression.Empty(); - internal static Expression GetExecutionContextFromTLS = + internal static readonly Expression GetExecutionContextFromTLS = Expression.Call(CachedReflectionInfo.LocalPipeline_GetExecutionContextFromTLS); internal static readonly Expression BoxedTrue = Expression.Field(null, typeof(Boxed).GetField("True", BindingFlags.Static | BindingFlags.NonPublic)); diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index df95f478075..6f13b768509 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -8083,7 +8083,7 @@ public override string ToString() [EventSource(Name = "Microsoft-PowerShell-Parser")] internal class ParserEventSource : EventSource { - internal static ParserEventSource Log = new ParserEventSource(); + internal static readonly ParserEventSource Log = new ParserEventSource(); internal const int MaxScriptLengthToLog = 50; diff --git a/src/System.Management.Automation/engine/parser/TypeResolver.cs b/src/System.Management.Automation/engine/parser/TypeResolver.cs index a0ae173907c..24c949960d1 100644 --- a/src/System.Management.Automation/engine/parser/TypeResolver.cs +++ b/src/System.Management.Automation/engine/parser/TypeResolver.cs @@ -723,7 +723,7 @@ internal static class CoreTypes // expose the ability to corrupt or escape PowerShell's environment. The following operations must // be safe: type conversion, all constructors, all methods (instance and static), and // and properties (instance and static). - internal static Lazy> Items = new Lazy>( + internal static readonly Lazy> Items = new Lazy>( () => new Dictionary { @@ -845,11 +845,11 @@ internal static bool Contains(Type inputType) internal static class TypeAccelerators { // builtins are not exposed publicly in a direct manner so they can't be changed at all - internal static Dictionary builtinTypeAccelerators = new Dictionary(64, StringComparer.OrdinalIgnoreCase); + internal static readonly Dictionary builtinTypeAccelerators = new Dictionary(64, StringComparer.OrdinalIgnoreCase); // users can add to user added accelerators (but not currently remove any.) Keeping a separate // list allows us to add removing in the future w/o worrying about breaking the builtins. - internal static Dictionary userTypeAccelerators = new Dictionary(64, StringComparer.OrdinalIgnoreCase); + internal static readonly Dictionary userTypeAccelerators = new Dictionary(64, StringComparer.OrdinalIgnoreCase); // We expose this one publicly for programmatic access to our type accelerator table, but it is // otherwise unused (so changes to this dictionary don't affect internals.) diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index be4bfc6b1bc..79d74b9edef 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -288,7 +288,7 @@ internal void ClearParent() internal abstract object Accept(ICustomAstVisitor visitor); internal abstract AstVisitAction InternalVisit(AstVisitor visitor); - internal static PSTypeName[] EmptyPSTypeNameArray = Array.Empty(); + internal static readonly PSTypeName[] EmptyPSTypeNameArray = Array.Empty(); internal bool IsInWorkflow() { diff --git a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationOptionCommand.cs b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationOptionCommand.cs index c96f974763d..c1b3b3b7326 100644 --- a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationOptionCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationOptionCommand.cs @@ -19,7 +19,7 @@ public class WSManConfigurationOption : PSTransportOption internal const string AttribOutputBufferingMode = "OutputBufferingMode"; - internal static System.Management.Automation.Runspaces.OutputBufferingMode? DefaultOutputBufferingMode = System.Management.Automation.Runspaces.OutputBufferingMode.Block; + internal static readonly System.Management.Automation.Runspaces.OutputBufferingMode? DefaultOutputBufferingMode = System.Management.Automation.Runspaces.OutputBufferingMode.Block; private System.Management.Automation.Runspaces.OutputBufferingMode? _outputBufferingMode = null; private const string AttribProcessIdleTimeout = "ProcessIdleTimeoutSec"; diff --git a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs index 2485b857752..b3159a0e557 100644 --- a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs +++ b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs @@ -1349,7 +1349,7 @@ private void UpdateUri(Uri uri) #if NOT_APPLY_PORT_DCR private static string DEFAULT_SCHEME = HTTP_SCHEME; - internal static string DEFAULT_SSL_SCHEME = HTTPS_SCHEME; + internal static readonly string DEFAULT_SSL_SCHEME = HTTPS_SCHEME; private static string DEFAULT_APP_NAME = "wsman"; /// /// See below for explanation. diff --git a/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs b/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs index 9f938ac3d4a..174cad6743b 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs @@ -948,7 +948,7 @@ internal static class ConfigFileConstants internal static readonly string VisibleProviders = "VisibleProviders"; internal static readonly string VisibleExternalCommands = "VisibleExternalCommands"; - internal static ConfigTypeEntry[] ConfigFileKeys = new ConfigTypeEntry[] { + internal static readonly ConfigTypeEntry[] ConfigFileKeys = new ConfigTypeEntry[] { new ConfigTypeEntry(AliasDefinitions, new ConfigTypeEntry.TypeValidationCallback(AliasDefinitionsTypeValidationCallback)), new ConfigTypeEntry(AssembliesToLoad, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), new ConfigTypeEntry(Author, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)), diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs index c6dde82a90b..77c30d4d43e 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs @@ -137,7 +137,7 @@ internal class WSManPluginInstance /// It is static because static instances of this class use the facade. Otherwise, /// it would be passed in via a parameterized constructor. /// - internal static IWSManNativeApiFacade wsmanPinvokeStatic = new WSManNativeApiFacade(); + internal static readonly IWSManNativeApiFacade wsmanPinvokeStatic = new WSManNativeApiFacade(); #endregion diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs index 727c8e231ff..ed5bf0a4a3e 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs @@ -419,7 +419,7 @@ private WSManPluginManagedEntryWrapper() { } /// /// Immutable container that holds the delegates and their unmanaged pointers. /// - internal static WSManPluginEntryDelegates workerPtrs = new WSManPluginEntryDelegates(); + internal static readonly WSManPluginEntryDelegates workerPtrs = new WSManPluginEntryDelegates(); #region Managed Entry Points diff --git a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs index 6f69be4eb49..ddb8bc5faeb 100644 --- a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs +++ b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs @@ -623,7 +623,7 @@ internal static void ClearScriptBlockCache() s_cachedScripts.Clear(); } - internal static ScriptBlock EmptyScriptBlock = + internal static readonly ScriptBlock EmptyScriptBlock = ScriptBlock.CreateDelayParsedScriptBlock(string.Empty, isProductCode: true); internal static ScriptBlock Create(Parser parser, string fileName, string fileContents) diff --git a/src/System.Management.Automation/engine/runtime/Operations/NumericOps.cs b/src/System.Management.Automation/engine/runtime/Operations/NumericOps.cs index 9fa515a9b81..f5670899c23 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/NumericOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/NumericOps.cs @@ -8,8 +8,8 @@ namespace System.Management.Automation { internal static class Boxed { - internal static object True = (object)true; - internal static object False = (object)false; + internal static readonly object True = (object)true; + internal static readonly object False = (object)false; } internal static class IntOps diff --git a/src/System.Management.Automation/engine/serialization.cs b/src/System.Management.Automation/engine/serialization.cs index 95af575cc5f..31ec2e348d2 100644 --- a/src/System.Management.Automation/engine/serialization.cs +++ b/src/System.Management.Automation/engine/serialization.cs @@ -355,7 +355,7 @@ internal void LogExtraMemoryUsage(int amountOfExtraMemory) internal readonly DeserializationOptions options; internal readonly PSRemotingCryptoHelper cryptoHelper; - internal static int MaxItemsInCimClassCache = 100; + internal static readonly int MaxItemsInCimClassCache = 100; internal readonly CimClassDeserializationCache cimClassSerializationIdCache = new CimClassDeserializationCache(); } diff --git a/src/System.Management.Automation/help/CabinetAPI.cs b/src/System.Management.Automation/help/CabinetAPI.cs index 41a83010f58..eb407f2ec62 100644 --- a/src/System.Management.Automation/help/CabinetAPI.cs +++ b/src/System.Management.Automation/help/CabinetAPI.cs @@ -81,7 +81,7 @@ internal abstract class ICabinetExtractorLoader internal class CabinetExtractorFactory { private static ICabinetExtractorLoader s_cabinetLoader; - internal static ICabinetExtractor EmptyExtractor = new EmptyCabinetExtractor(); + internal static readonly ICabinetExtractor EmptyExtractor = new EmptyCabinetExtractor(); /// /// Static constructor. diff --git a/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs b/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs index 76ac1e7d1b6..b8be27e99a0 100644 --- a/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs +++ b/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs @@ -42,7 +42,7 @@ public int Compare(object x, object y) /// internal class DefaultCommandHelpObjectBuilder { - internal static string TypeNameForDefaultHelp = "ExtendedCmdletHelpInfo"; + internal static readonly string TypeNameForDefaultHelp = "ExtendedCmdletHelpInfo"; /// /// Generates a HelpInfo PSObject from a CmdletInfo object. /// diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 67cd105fc40..cbe492db2cf 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -9704,7 +9704,7 @@ PSGetPathDirAndFiles @params }} "; - internal static string PSCopyFromSessionHelper = functionToken + PSCopyFromSessionHelperName + @" + internal static readonly string PSCopyFromSessionHelper = functionToken + PSCopyFromSessionHelperName + @" { " + s_PSCopyFromSessionHelperDefinition + @" } @@ -9721,7 +9721,7 @@ PSGetPathDirAndFiles @params internal const string PSCopyRemoteUtilsName = @"PSCopyRemoteUtils"; - internal static string PSCopyRemoteUtilsDefinition = StringUtil.Format(PSCopyRemoteUtilsDefinitionFormat, @"[ValidateNotNullOrEmpty()]", PSValidatePathFunction); + internal static readonly string PSCopyRemoteUtilsDefinition = StringUtil.Format(PSCopyRemoteUtilsDefinitionFormat, @"[ValidateNotNullOrEmpty()]", PSValidatePathFunction); private static string s_PSCopyRemoteUtilsDefinitionRestricted = StringUtil.Format(PSCopyRemoteUtilsDefinitionFormat, @"[ValidateUserDrive()]", PSValidatePathFunction); private const string PSCopyRemoteUtilsDefinitionFormat = @" @@ -9878,20 +9878,20 @@ function SafeGetDriveRoot return $result "; - internal static string PSCopyRemoteUtils = functionToken + PSCopyRemoteUtilsName + @" + internal static readonly string PSCopyRemoteUtils = functionToken + PSCopyRemoteUtilsName + @" { " + PSCopyRemoteUtilsDefinition + @" } "; - internal static Hashtable PSCopyRemoteUtilsFunction = new Hashtable() { + internal static readonly Hashtable PSCopyRemoteUtilsFunction = new Hashtable() { {nameToken, PSCopyRemoteUtilsName}, {definitionToken, s_PSCopyRemoteUtilsDefinitionRestricted} }; #endregion - internal static string AllCopyToRemoteScripts = s_PSCopyToSessionHelper + PSCopyRemoteUtils; + internal static readonly string AllCopyToRemoteScripts = s_PSCopyToSessionHelper + PSCopyRemoteUtils; internal static IEnumerable GetAllCopyToRemoteScriptFunctions() { @@ -9899,7 +9899,7 @@ internal static IEnumerable GetAllCopyToRemoteScriptFunctions() yield return PSCopyRemoteUtilsFunction; } - internal static string AllCopyFromRemoteScripts = PSCopyFromSessionHelper + PSCopyRemoteUtils; + internal static readonly string AllCopyFromRemoteScripts = PSCopyFromSessionHelper + PSCopyRemoteUtils; internal static IEnumerable GetAllCopyFromRemoteScriptFunctions() { diff --git a/src/System.Management.Automation/namespaces/ProviderBase.cs b/src/System.Management.Automation/namespaces/ProviderBase.cs index 22bd599f637..326d4d51b04 100644 --- a/src/System.Management.Automation/namespaces/ProviderBase.cs +++ b/src/System.Management.Automation/namespaces/ProviderBase.cs @@ -78,7 +78,7 @@ public abstract partial class CmdletProvider : IResourceSupplier [TraceSourceAttribute( "CmdletProviderClasses", "The namespace provider base classes tracer")] - internal static PSTraceSource providerBaseTracer = PSTraceSource.GetTracer( + internal static readonly PSTraceSource providerBaseTracer = PSTraceSource.GetTracer( "CmdletProviderClasses", "The namespace provider base classes tracer"); diff --git a/src/System.Management.Automation/security/SecureStringHelper.cs b/src/System.Management.Automation/security/SecureStringHelper.cs index 63066cbd291..e6180dc39b7 100644 --- a/src/System.Management.Automation/security/SecureStringHelper.cs +++ b/src/System.Management.Automation/security/SecureStringHelper.cs @@ -20,7 +20,7 @@ internal static class SecureStringHelper { // Some random hex characters to identify the beginning of a // V2-exported SecureString. - internal static string SecureStringExportHeader = "76492d1116743f0423413b16050a5345"; + internal static readonly string SecureStringExportHeader = "76492d1116743f0423413b16050a5345"; /// /// Create a new SecureString based on the specified binary data. diff --git a/src/System.Management.Automation/security/SecuritySupport.cs b/src/System.Management.Automation/security/SecuritySupport.cs index 22e553d3002..64ed73a99d9 100644 --- a/src/System.Management.Automation/security/SecuritySupport.cs +++ b/src/System.Management.Automation/security/SecuritySupport.cs @@ -961,11 +961,11 @@ internal static string Encrypt(byte[] contentBytes, CmsMessageRecipient[] recipi return encodedContent; } - internal static string BEGIN_CMS_SIGIL = "-----BEGIN CMS-----"; - internal static string END_CMS_SIGIL = "-----END CMS-----"; + internal static readonly string BEGIN_CMS_SIGIL = "-----BEGIN CMS-----"; + internal static readonly string END_CMS_SIGIL = "-----END CMS-----"; - internal static string BEGIN_CERTIFICATE_SIGIL = "-----BEGIN CERTIFICATE-----"; - internal static string END_CERTIFICATE_SIGIL = "-----END CERTIFICATE-----"; + internal static readonly string BEGIN_CERTIFICATE_SIGIL = "-----BEGIN CERTIFICATE-----"; + internal static readonly string END_CERTIFICATE_SIGIL = "-----END CERTIFICATE-----"; /// /// Adds Ascii armour to a byte stream in Base64 format. diff --git a/src/System.Management.Automation/utils/EncodingUtils.cs b/src/System.Management.Automation/utils/EncodingUtils.cs index af3c1c04a86..8206b5cf8a3 100644 --- a/src/System.Management.Automation/utils/EncodingUtils.cs +++ b/src/System.Management.Automation/utils/EncodingUtils.cs @@ -30,7 +30,7 @@ internal static class EncodingConversion Ascii, BigEndianUnicode, BigEndianUtf32, OEM, Unicode, Utf7, Utf8, Utf8Bom, Utf8NoBom, Utf32 }; - internal static Dictionary encodingMap = new Dictionary(StringComparer.OrdinalIgnoreCase) + internal static readonly Dictionary encodingMap = new Dictionary(StringComparer.OrdinalIgnoreCase) { { Ascii, System.Text.Encoding.ASCII }, { BigEndianUnicode, System.Text.Encoding.BigEndianUnicode }, diff --git a/src/System.Management.Automation/utils/PlatformInvokes.cs b/src/System.Management.Automation/utils/PlatformInvokes.cs index 4ffdeb41415..8e99cdff4b0 100644 --- a/src/System.Management.Automation/utils/PlatformInvokes.cs +++ b/src/System.Management.Automation/utils/PlatformInvokes.cs @@ -529,14 +529,14 @@ internal struct PRIVILEGE_SET // Fields internal static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); - internal static UInt32 GENERIC_READ = 0x80000000; - internal static UInt32 GENERIC_WRITE = 0x40000000; - internal static UInt32 FILE_ATTRIBUTE_NORMAL = 0x80000000; - internal static UInt32 CREATE_ALWAYS = 2; - internal static UInt32 FILE_SHARE_WRITE = 0x00000002; - internal static UInt32 FILE_SHARE_READ = 0x00000001; - internal static UInt32 OF_READWRITE = 0x00000002; - internal static UInt32 OPEN_EXISTING = 3; + internal static readonly UInt32 GENERIC_READ = 0x80000000; + internal static readonly UInt32 GENERIC_WRITE = 0x40000000; + internal static readonly UInt32 FILE_ATTRIBUTE_NORMAL = 0x80000000; + internal static readonly UInt32 CREATE_ALWAYS = 2; + internal static readonly UInt32 FILE_SHARE_WRITE = 0x00000002; + internal static readonly UInt32 FILE_SHARE_READ = 0x00000001; + internal static readonly UInt32 OF_READWRITE = 0x00000002; + internal static readonly UInt32 OPEN_EXISTING = 3; [StructLayout(LayoutKind.Sequential)] internal class PROCESS_INFORMATION @@ -679,7 +679,7 @@ internal static extern bool CreateProcess( [DllImport(PinvokeDllNames.ResumeThreadDllName, CharSet = CharSet.Unicode, SetLastError = true)] public static extern uint ResumeThread(IntPtr threadHandle); - internal static uint RESUME_THREAD_FAILED = System.UInt32.MaxValue; // (DWORD)-1 + internal static readonly uint RESUME_THREAD_FAILED = System.UInt32.MaxValue; // (DWORD)-1 [DllImport(PinvokeDllNames.CreateFileDllName, CharSet = CharSet.Unicode, SetLastError = true)] public static extern System.IntPtr CreateFileW(