From dafcf2423dad6582340ab9f08fb2d89b4504eb4c Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Thu, 30 Jul 2020 15:16:08 -0700 Subject: [PATCH] Revert "Use `is null` syntax (#13277)" This reverts commit 6c03776d743edfdffc3e347a7d7249864b5e2447. --- .../CimAsyncOperation.cs | 14 +- .../CimCommandBase.cs | 12 +- .../CimGetAssociatedInstance.cs | 2 +- .../CimGetCimClass.cs | 2 +- .../CimGetInstance.cs | 4 +- .../CimIndicationWatcher.cs | 8 +- .../CimInvokeCimMethod.cs | 8 +- .../CimNewCimInstance.cs | 10 +- .../CimRegisterCimIndication.cs | 2 +- .../CimResultObserver.cs | 2 +- .../CimSessionOperations.cs | 6 +- .../CimSessionProxy.cs | 14 +- .../CimSetCimInstance.cs | 2 +- .../CimWriteError.cs | 8 +- .../NewCimSessionCommand.cs | 4 +- .../RegisterCimIndicationCommand.cs | 2 +- .../Utils.cs | 8 +- .../CounterSet.cs | 2 +- .../GetEventCommand.cs | 10 +- .../NewWinEventCommand.cs | 8 +- .../cmdletization/SessionBasedWrapper.cs | 16 +- .../cmdletization/cim/CimJobException.cs | 12 +- .../cmdletization/cim/CreateInstanceJob.cs | 10 +- .../cim/ExtrinsicMethodInvocationJob.cs | 6 +- .../cim/MethodInvocationJobBase.cs | 2 +- .../cmdletization/cim/QueryJobBase.cs | 2 +- .../cim/TerminatingErrorTracker.cs | 2 +- .../cmdletization/cim/cimChildJobBase.cs | 16 +- .../cmdletization/cim/cimConverter.cs | 14 +- .../cmdletization/cim/cimJobContext.cs | 2 +- .../cim/cimOperationOptionsHelper.cs | 4 +- .../cimSupport/cmdletization/cim/cimQuery.cs | 4 +- .../cmdletization/cim/cimWrapper.cs | 8 +- .../cmdletization/cim/clientSideQuery.cs | 18 +- .../management/ClearRecycleBinCommand.cs | 6 +- .../commands/management/Computer.cs | 16 +- .../commands/management/ComputerUnix.cs | 2 +- .../commands/management/ContentCommandBase.cs | 6 +- .../commands/management/GetChildrenCommand.cs | 2 +- .../management/GetComputerInfoCommand.cs | 12 +- .../commands/management/GetPropertyCommand.cs | 2 +- .../management/MovePropertyCommand.cs | 2 +- .../commands/management/Navigation.cs | 14 +- .../commands/management/PingPathCommand.cs | 4 +- .../commands/management/Process.cs | 20 +- .../commands/management/Service.cs | 20 +- .../management/SetClipboardCommand.cs | 2 +- .../commands/management/SetContentCommand.cs | 2 +- .../management/TestConnectionCommand.cs | 6 +- .../management/WriteContentCommandBase.cs | 2 +- .../commands/utility/AddMember.cs | 12 +- .../commands/utility/AddType.cs | 8 +- .../commands/utility/Compare-Object.cs | 16 +- .../utility/ConvertFrom-SddlString.cs | 2 +- .../utility/ConvertFromMarkdownCommand.cs | 2 +- .../commands/utility/ConvertTo-Html.cs | 8 +- .../commands/utility/CsvCommands.cs | 38 +-- .../commands/utility/CustomSerialization.cs | 10 +- .../commands/utility/DebugRunspaceCommand.cs | 6 +- .../EnableDisableRunspaceDebugCommand.cs | 10 +- .../commands/utility/ExportAliasCommand.cs | 2 +- .../FormatAndOutput/OutGridView/ColumnInfo.cs | 2 +- .../OutGridView/ExpressionColumnInfo.cs | 2 +- .../OutGridView/OriginalColumnInfo.cs | 2 +- .../OutGridView/OutGridViewCommand.cs | 10 +- .../OutGridView/OutWindowProxy.cs | 14 +- .../FormatAndOutput/OutGridView/TableView.cs | 12 +- .../common/GetFormatDataCommand.cs | 8 +- .../FormatAndOutput/out-file/Out-File.cs | 6 +- .../commands/utility/Get-PSBreakpoint.cs | 6 +- .../commands/utility/GetAliasCommand.cs | 2 +- .../commands/utility/GetMember.cs | 4 +- .../commands/utility/GetRandomCommand.cs | 16 +- .../commands/utility/GetRunspaceCommand.cs | 2 +- .../commands/utility/GetUnique.cs | 6 +- .../commands/utility/Group-Object.cs | 8 +- .../utility/ImplicitRemotingCommands.cs | 92 +++--- .../commands/utility/Import-LocalizedData.cs | 10 +- .../commands/utility/ImportAliasCommand.cs | 2 +- .../commands/utility/Join-String.cs | 2 +- .../utility/MarkdownOptionCommands.cs | 2 +- .../commands/utility/MatchString.cs | 8 +- .../commands/utility/Measure-Object.cs | 20 +- .../commands/utility/New-Object.cs | 6 +- .../commands/utility/ObjectCommandComparer.cs | 10 +- .../commands/utility/OrderObjectBase.cs | 22 +- .../utility/PSBreakpointCommandBase.cs | 2 +- .../utility/PSBreakpointUpdaterCommandBase.cs | 4 +- .../utility/RegisterPSEventCommand.cs | 2 +- .../commands/utility/RunspaceAttribute.cs | 4 +- .../commands/utility/Select-Object.cs | 22 +- .../commands/utility/Send-MailMessage.cs | 2 +- .../commands/utility/Set-PSBreakpoint.cs | 2 +- .../utility/ShowCommand/ShowCommand.cs | 10 +- .../ShowCommand/ShowCommandCommandInfo.cs | 4 +- .../ShowCommand/ShowCommandModuleInfo.cs | 4 +- .../ShowCommand/ShowCommandParameterInfo.cs | 4 +- .../ShowCommandParameterSetInfo.cs | 4 +- .../ShowCommand/ShowCommandParameterType.cs | 4 +- .../commands/utility/Sort-Object.cs | 2 +- .../commands/utility/Update-List.cs | 6 +- .../commands/utility/Update-TypeData.cs | 16 +- .../commands/utility/UtilityCommon.cs | 6 +- .../commands/utility/Var.cs | 12 +- .../commands/utility/WaitEventCommand.cs | 8 +- .../BasicHtmlWebResponseObject.Common.cs | 18 +- .../WebCmdlet/Common/ContentHelper.Common.cs | 4 +- .../Common/InvokeRestMethodCommand.Common.cs | 6 +- .../Common/WebRequestPSCmdlet.Common.cs | 56 ++-- .../Common/WebResponseObject.Common.cs | 8 +- .../WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs | 2 +- .../InvokeWebRequestCommand.CoreClr.cs | 2 +- .../utility/WebCmdlet/CoreCLR/WebProxy.cs | 4 +- .../commands/utility/WebCmdlet/JsonObject.cs | 8 +- .../commands/utility/WebCmdlet/PSUserAgent.cs | 2 +- .../utility/WebCmdlet/StreamHelper.cs | 6 +- .../utility/WebCmdlet/WebRequestSession.cs | 2 +- .../commands/utility/Write-Object.cs | 2 +- .../commands/utility/Write.cs | 4 +- .../utility/trace/GetTracerCommand.cs | 2 +- .../utility/trace/MshHostTraceListener.cs | 2 +- .../utility/trace/TraceExpressionCommand.cs | 6 +- .../utility/trace/TraceListenerCommandBase.cs | 6 +- .../WindowsTaskbarJumpList/PropVariant.cs | 2 +- .../WindowsTaskbarJumpList/PropertyKey.cs | 2 +- .../host/msh/CommandLineParameterParser.cs | 6 +- .../host/msh/ConsoleControl.cs | 4 +- .../host/msh/ConsoleHost.cs | 38 +-- .../host/msh/ConsoleHostRawUserInterface.cs | 8 +- .../host/msh/ConsoleHostTranscript.cs | 4 +- .../host/msh/ConsoleHostUserInterface.cs | 8 +- .../msh/ConsoleHostUserInterfaceProgress.cs | 8 +- .../msh/ConsoleHostUserInterfacePrompt.cs | 12 +- ...ConsoleHostUserInterfacePromptForChoice.cs | 4 +- .../msh/ConsoleHostUserInterfaceSecurity.cs | 6 +- .../host/msh/ConsoleShell.cs | 4 +- .../host/msh/Executor.cs | 16 +- .../host/msh/PendingProgress.cs | 30 +- .../host/msh/ProgressPane.cs | 8 +- .../host/msh/Serialization.cs | 2 +- .../host/msh/StartTranscriptCmdlet.cs | 2 +- .../host/msh/UpdatesNotification.cs | 2 +- .../DotNetCode/Eventing/EventProvider.cs | 6 +- .../Eventing/EventProviderTraceListener.cs | 6 +- .../LeafInlineRenderer.cs | 2 +- .../ListItemBlockRenderer.cs | 2 +- .../VT100EscapeSequences.cs | 2 +- .../security/AclCommands.cs | 28 +- .../security/CertificateCommands.cs | 4 +- .../security/CertificateProvider.cs | 28 +- .../security/CmsCommands.cs | 4 +- .../security/SecureStringCommands.cs | 4 +- .../security/SignatureCommands.cs | 8 +- .../ConfigProvider.cs | 72 ++--- src/Microsoft.WSMan.Management/CredSSP.cs | 22 +- .../CurrentConfigurations.cs | 10 +- .../NewWSManSession.cs | 2 +- .../WSManConnections.cs | 2 +- src/Microsoft.WSMan.Management/WsManHelper.cs | 12 +- .../CoreCLR/CorePsAssemblyLoadContext.cs | 2 +- .../CoreCLR/CorePsPlatform.cs | 6 +- .../DscSupport/CimDSCParser.cs | 80 ++--- .../FormatAndOutput/common/BaseCommand.cs | 10 +- .../common/BaseFormattingCommand.cs | 8 +- .../common/BaseFormattingCommandParameters.cs | 2 +- .../common/BaseOutputtingCommand.cs | 18 +- .../FormatAndOutput/common/ComplexWriter.cs | 4 +- .../common/DisplayDatabase/FormatTable.cs | 10 +- .../DisplayDatabase/displayDescriptionData.cs | 26 +- .../displayDescriptionData_Complex.cs | 8 +- .../displayDescriptionData_List.cs | 18 +- .../displayDescriptionData_Table.cs | 10 +- .../displayDescriptionData_Wide.cs | 18 +- .../displayResourceManagerCache.cs | 6 +- .../common/DisplayDatabase/typeDataManager.cs | 4 +- .../common/DisplayDatabase/typeDataQuery.cs | 22 +- .../DisplayDatabase/typeDataXmlLoader.cs | 108 +++---- .../typeDataXmlLoader_Complex.cs | 32 +- .../DisplayDatabase/typeDataXmlLoader_List.cs | 18 +- .../typeDataXmlLoader_Table.cs | 20 +- .../typeDataXmlLoader_Views.cs | 20 +- .../DisplayDatabase/typeDataXmlLoader_Wide.cs | 12 +- .../common/FormatGroupManager.cs | 6 +- .../common/FormatViewGenerator.cs | 14 +- .../common/FormatViewGenerator_Complex.cs | 22 +- .../common/FormatViewGenerator_List.cs | 2 +- .../common/FormatViewGenerator_Table.cs | 14 +- .../common/FormatViewGenerator_Wide.cs | 2 +- .../common/FormatViewManager.cs | 2 +- .../common/FormattingObjectsDeserializer.cs | 20 +- .../FormatAndOutput/common/ILineOutput.cs | 6 +- .../FormatAndOutput/common/ListWriter.cs | 10 +- .../FormatAndOutput/common/OutputManager.cs | 8 +- .../FormatAndOutput/common/OutputQueue.cs | 12 +- .../common/Utilities/MshObjectUtil.cs | 16 +- .../common/Utilities/MshParameter.cs | 12 +- .../Utilities/MshParameterAssociation.cs | 2 +- .../common/Utilities/Mshexpression.cs | 6 +- .../out-console/ConsoleLineOutput.cs | 6 +- .../out-textInterface/OutTextInterface.cs | 4 +- .../cmdletization/MethodInvocationInfo.cs | 4 +- .../cmdletization/ObjectModelWrapper.cs | 6 +- .../cimSupport/cmdletization/ScriptWriter.cs | 24 +- ...lets-over-objects.xmlSerializer.autogen.cs | 130 ++++---- .../other/ciminstancetypeadapter.cs | 24 +- .../engine/AliasInfo.cs | 2 +- .../engine/ApplicationInfo.cs | 6 +- .../engine/ArgumentTypeConverterAttribute.cs | 6 +- .../engine/Attributes.cs | 40 +-- .../engine/COM/ComAdapter.cs | 2 +- .../engine/COM/ComInvoker.cs | 4 +- .../engine/COM/ComMethod.cs | 4 +- .../engine/COM/ComProperty.cs | 10 +- .../ChildrenCmdletProviderInterfaces.cs | 4 +- .../engine/CmdletFamilyProviderInterfaces.cs | 4 +- .../engine/CmdletInfo.cs | 12 +- .../engine/CmdletParameterBinderController.cs | 68 ++--- .../engine/CodeMethods.cs | 10 +- .../engine/CommandBase.cs | 4 +- .../CommandCompletion/CommandCompletion.cs | 60 ++-- .../CommandCompletion/CompletionAnalysis.cs | 42 +-- .../CommandCompletion/CompletionCompleters.cs | 128 ++++---- .../CommandCompletion/ExtensibleCompletion.cs | 8 +- .../PseudoParameterBinder.cs | 36 +-- .../engine/CommandDiscovery.cs | 40 +-- .../engine/CommandInfo.cs | 22 +- .../engine/CommandMetadata.cs | 16 +- .../engine/CommandParameter.cs | 2 +- .../engine/CommandPathSearch.cs | 6 +- .../engine/CommandProcessor.cs | 8 +- .../engine/CommandProcessorBase.cs | 8 +- .../engine/CommandSearcher.cs | 26 +- .../engine/CommonCommandParameters.cs | 2 +- .../engine/CompiledCommandParameter.cs | 24 +- .../engine/ContentCmdletProviderInterfaces.cs | 4 +- .../engine/CoreAdapter.cs | 116 +++---- .../engine/Credential.cs | 14 +- .../engine/DataStoreAdapter.cs | 28 +- .../engine/DataStoreAdapterProvider.cs | 18 +- .../engine/DefaultCommandRuntime.cs | 4 +- .../engine/DriveInterfaces.cs | 2 +- .../engine/DscResourceSearcher.cs | 2 +- .../engine/EngineIntrinsics.cs | 2 +- .../engine/EnumExpressionEvaluator.cs | 2 +- .../engine/ErrorPackage.cs | 30 +- .../engine/EventManager.cs | 26 +- .../engine/ExecutionContext.cs | 56 ++-- ...EnableDisableExperimentalFeatureCommand.cs | 2 +- .../ExperimentalFeature.cs | 4 +- .../engine/ExtendedTypeSystemException.cs | 4 +- .../engine/ExternalScriptInfo.cs | 26 +- .../engine/ExtraAdapter.cs | 18 +- .../engine/FunctionInfo.cs | 12 +- .../engine/GetCommandCommand.cs | 34 +-- .../engine/InformationRecord.cs | 2 +- .../engine/InitialSessionState.cs | 94 +++--- .../engine/InternalCommands.cs | 16 +- .../engine/ItemCmdletProviderInterfaces.cs | 4 +- .../engine/LanguagePrimitives.cs | 112 +++---- .../engine/ManagementObjectAdapter.cs | 24 +- .../engine/MergedCommandParameterMetadata.cs | 2 +- .../MinishellParameterBinderController.cs | 6 +- .../engine/Modules/AnalysisCache.cs | 10 +- .../engine/Modules/GetModuleCommand.cs | 6 +- .../engine/Modules/ImportModuleCommand.cs | 50 +-- .../engine/Modules/ModuleCmdletBase.cs | 170 +++++------ .../engine/Modules/ModuleIntrinsics.cs | 32 +- .../engine/Modules/ModuleSpecification.cs | 10 +- .../engine/Modules/ModuleUtils.cs | 2 +- .../engine/Modules/NewModuleCommand.cs | 4 +- .../Modules/NewModuleManifestCommand.cs | 28 +- .../engine/Modules/PSModuleInfo.cs | 28 +- .../engine/Modules/RemoteDiscoveryHelper.cs | 24 +- .../engine/Modules/ScriptAnalysis.cs | 8 +- .../Modules/TestModuleManifestCommand.cs | 4 +- .../engine/MshCmdlet.cs | 20 +- .../engine/MshCommandRuntime.cs | 66 ++-- .../engine/MshMemberInfo.cs | 134 ++++----- .../engine/MshObject.cs | 98 +++--- .../engine/MshObjectTypeDescriptor.cs | 44 +-- .../engine/MshSecurityException.cs | 2 +- .../engine/MshSnapinQualifiedName.cs | 2 +- .../engine/NativeCommandParameterBinder.cs | 6 +- .../engine/NativeCommandProcessor.cs | 12 +- .../engine/PSClassSearcher.cs | 2 +- .../engine/PSConfiguration.cs | 4 +- .../engine/PSVersionInfo.cs | 20 +- .../engine/ParameterBinderBase.cs | 66 ++-- .../engine/ParameterBinderController.cs | 6 +- .../engine/ParameterInfo.cs | 2 +- .../engine/ParameterSetInfo.cs | 8 +- .../engine/ParameterSetSpecificMetadata.cs | 2 +- .../engine/PathInterfaces.cs | 2 +- .../engine/Pipe.cs | 16 +- .../engine/ProgressRecord.cs | 2 +- .../PropertyCmdletProviderInterfaces.cs | 4 +- .../engine/ProviderInterfaces.cs | 2 +- .../engine/ProxyCommand.cs | 20 +- .../engine/PseudoParameterBinder.cs | 4 +- .../engine/PseudoParameters.cs | 4 +- .../engine/ReflectionParameterBinder.cs | 2 +- .../engine/ScopedItemSearcher.cs | 10 +- .../engine/ScriptCommandProcessor.cs | 12 +- .../engine/ScriptInfo.cs | 2 +- ...urityDescriptorCmdletProviderInterfaces.cs | 4 +- .../engine/SessionState.cs | 4 +- .../engine/SessionStateAliasAPIs.cs | 4 +- .../engine/SessionStateContainer.cs | 98 +++--- .../engine/SessionStateContent.cs | 24 +- .../engine/SessionStateDriveAPIs.cs | 36 +-- .../engine/SessionStateDynamicProperty.cs | 80 ++--- .../engine/SessionStateFunctionAPIs.cs | 10 +- .../engine/SessionStateItem.cs | 32 +- .../engine/SessionStateLocationAPIs.cs | 12 +- .../engine/SessionStateNavigation.cs | 38 +-- .../engine/SessionStateProperty.cs | 32 +- .../engine/SessionStateProviderAPIs.cs | 68 ++--- .../engine/SessionStatePublic.cs | 10 +- .../engine/SessionStateScope.cs | 28 +- .../engine/SessionStateScopeAPIs.cs | 4 +- .../engine/SessionStateScopeEnumerator.cs | 4 +- ...SessionStateSecurityDescriptorInterface.cs | 22 +- .../engine/SessionStateUtils.cs | 2 +- .../engine/SessionStateVariableAPIs.cs | 38 +-- .../engine/ShellVariable.cs | 2 +- .../engine/ThirdPartyAdapter.cs | 8 +- .../engine/TypeMetadata.cs | 24 +- .../engine/TypeTable.cs | 110 +++---- .../engine/TypeTable_Types_Ps1Xml.cs | 2 +- .../engine/UserFeedbackParameters.cs | 4 +- .../engine/Utils.cs | 38 +-- .../engine/VariableAttributeCollection.cs | 2 +- .../engine/VariableInterfaces.cs | 2 +- .../engine/cmdlet.cs | 6 +- .../engine/debugger/Breakpoint.cs | 16 +- .../engine/debugger/debugger.cs | 104 +++---- .../engine/hostifaces/AsyncResult.cs | 6 +- .../engine/hostifaces/ChoiceDescription.cs | 4 +- .../engine/hostifaces/Command.cs | 6 +- .../engine/hostifaces/Connection.cs | 16 +- .../engine/hostifaces/ConnectionBase.cs | 22 +- .../engine/hostifaces/ConnectionFactory.cs | 12 +- .../engine/hostifaces/FieldDescription.cs | 6 +- .../engine/hostifaces/History.cs | 40 +-- .../engine/hostifaces/HostUtilities.cs | 12 +- .../engine/hostifaces/InformationalRecord.cs | 2 +- .../engine/hostifaces/InternalHost.cs | 10 +- .../InternalHostRawUserInterface.cs | 58 ++-- .../hostifaces/InternalHostUserInterface.cs | 72 ++--- .../engine/hostifaces/ListModifier.cs | 10 +- .../engine/hostifaces/LocalConnection.cs | 18 +- .../engine/hostifaces/LocalPipeline.cs | 10 +- .../hostifaces/MshHostRawUserInterface.cs | 6 +- .../engine/hostifaces/MshHostUserInterface.cs | 10 +- .../engine/hostifaces/PSCommand.cs | 16 +- .../engine/hostifaces/PSDataCollection.cs | 22 +- .../engine/hostifaces/PSTask.cs | 4 +- .../engine/hostifaces/Parameter.cs | 14 +- .../engine/hostifaces/Pipeline.cs | 2 +- .../engine/hostifaces/PowerShell.cs | 100 +++--- .../hostifaces/PowerShellProcessInstance.cs | 2 +- .../engine/hostifaces/RunspacePool.cs | 12 +- .../engine/hostifaces/RunspacePoolInternal.cs | 28 +- .../internalHostuserInterfacesecurity.cs | 4 +- .../engine/hostifaces/pipelinebase.cs | 10 +- .../engine/interpreter/BranchLabel.cs | 2 +- .../interpreter/CallInstruction.Generated.cs | 6 +- .../interpreter/ControlFlowInstructions.cs | 8 +- .../engine/interpreter/InstructionFactory.cs | 4 +- .../engine/interpreter/InstructionList.cs | 42 +-- .../engine/interpreter/InterpretedFrame.cs | 2 +- .../engine/interpreter/Interpreter.cs | 2 +- .../engine/interpreter/LabelInfo.cs | 12 +- .../engine/interpreter/LightCompiler.cs | 28 +- .../interpreter/LightDelegateCreator.cs | 2 +- .../interpreter/LightLambdaClosureVisitor.cs | 4 +- .../engine/interpreter/LocalAccess.cs | 2 +- .../engine/interpreter/LocalVariables.cs | 6 +- .../engine/interpreter/LoopCompiler.cs | 4 +- .../engine/interpreter/Utilities.cs | 16 +- .../engine/lang/interface/PSParser.cs | 4 +- .../engine/lang/parserutils.cs | 76 ++--- .../engine/lang/scriptblock.cs | 22 +- .../engine/parser/Compiler.cs | 64 ++-- .../engine/parser/ConstantValues.cs | 12 +- .../engine/parser/DebugViewWriter.cs | 10 +- .../engine/parser/FusionAssemblyIdentity.cs | 6 +- .../engine/parser/GlobalAssemblyCache.cs | 6 +- .../engine/parser/PSType.cs | 30 +- .../engine/parser/Parser.cs | 284 +++++++++--------- .../engine/parser/Position.cs | 2 +- .../engine/parser/SafeValues.cs | 16 +- .../engine/parser/SemanticChecks.cs | 42 +-- .../engine/parser/SymbolResolver.cs | 8 +- .../engine/parser/TypeInferenceVisitor.cs | 50 +-- .../engine/parser/TypeResolver.cs | 30 +- .../engine/parser/VariableAnalysis.cs | 24 +- .../engine/parser/ast.cs | 268 ++++++++--------- .../engine/parser/tokenizer.cs | 28 +- .../engine/pipeline.cs | 98 +++--- .../engine/regex.cs | 12 +- .../remoting/client/ClientMethodExecutor.cs | 4 +- .../remoting/client/ClientRemotePowerShell.cs | 6 +- .../engine/remoting/client/Job.cs | 60 ++-- .../engine/remoting/client/Job2.cs | 44 +-- .../engine/remoting/client/JobManager.cs | 18 +- .../remoting/client/JobSourceAdapter.cs | 18 +- .../client/RemoteRunspacePoolInternal.cs | 26 +- .../remoting/client/RemotingErrorRecord.cs | 4 +- .../remoting/client/RemotingProtocol2.cs | 12 +- .../engine/remoting/client/RunspaceRef.cs | 4 +- .../engine/remoting/client/ThrottlingJob.cs | 8 +- .../remoting/client/clientremotesession.cs | 8 +- ...clientremotesessionprotocolstatemachine.cs | 6 +- .../engine/remoting/client/remotepipeline.cs | 16 +- .../engine/remoting/client/remoterunspace.cs | 42 +-- .../remoting/client/remoterunspaceinfo.cs | 2 +- .../client/remotingprotocolimplementation.cs | 12 +- .../remoting/commands/ConnectPSSession.cs | 2 +- .../remoting/commands/CustomShellCommands.cs | 38 +-- .../engine/remoting/commands/DebugJob.cs | 6 +- .../remoting/commands/DisconnectPSSession.cs | 2 +- .../commands/EnterPSHostProcessCommand.cs | 8 +- .../remoting/commands/InvokeCommandCommand.cs | 16 +- .../engine/remoting/commands/JobRepository.cs | 4 +- .../commands/NewPSSessionConfigurationFile.cs | 48 +-- .../remoting/commands/PSRemotingCmdlet.cs | 42 +-- .../remoting/commands/PopRunspaceCommand.cs | 2 +- .../remoting/commands/PushRunspaceCommand.cs | 6 +- .../engine/remoting/commands/ReceiveJob.cs | 28 +- .../remoting/commands/ReceivePSSession.cs | 32 +- .../engine/remoting/commands/RemoveJob.cs | 10 +- .../engine/remoting/commands/StartJob.cs | 2 +- .../TestPSSessionConfigurationFile.cs | 4 +- .../engine/remoting/commands/WaitJob.cs | 2 +- .../remoting/commands/getrunspacecommand.cs | 4 +- .../remoting/commands/newrunspacecommand.cs | 8 +- .../remoting/commands/remotingcommandutil.cs | 4 +- .../engine/remoting/common/DispatchTable.cs | 2 +- .../engine/remoting/common/ObjectRef.cs | 2 +- .../common/RemoteSessionHyperVSocket.cs | 6 +- .../remoting/common/RemoteSessionNamedPipe.cs | 30 +- .../remoting/common/RunspaceConnectionInfo.cs | 32 +- .../common/WireDataFormat/EncodeAndDecode.cs | 90 +++--- .../RemoteDebuggingCapability.cs | 2 +- .../common/WireDataFormat/RemoteHost.cs | 18 +- .../WireDataFormat/RemoteHostEncoder.cs | 24 +- .../WireDataFormat/RemoteSessionCapability.cs | 10 +- .../engine/remoting/common/fragmentor.cs | 6 +- .../engine/remoting/common/misc.cs | 6 +- .../engine/remoting/common/psstreamobject.cs | 12 +- .../remoting/common/remotingexceptions.cs | 8 +- .../engine/remoting/common/throttlemanager.cs | 2 +- .../remoting/fanin/BaseTransportManager.cs | 4 +- .../fanin/InitialSessionStateProvider.cs | 68 ++--- .../fanin/OutOfProcTransportManager.cs | 28 +- .../engine/remoting/fanin/PSPrincipal.cs | 4 +- .../fanin/PSSessionConfigurationData.cs | 4 +- .../remoting/fanin/PriorityCollection.cs | 4 +- .../engine/remoting/fanin/WSManPlugin.cs | 60 ++-- .../remoting/fanin/WSManPluginFacade.cs | 2 +- .../remoting/fanin/WSManPluginShellSession.cs | 10 +- .../fanin/WSManPluginTransportManager.cs | 2 +- .../remoting/fanin/WSManTransportManager.cs | 12 +- .../server/OutOfProcServerMediator.cs | 4 +- .../remoting/server/ServerMethodExecutor.cs | 2 +- .../remoting/server/ServerRemoteHost.cs | 10 +- .../ServerRemoteHostRawUserInterface.cs | 4 +- .../server/ServerRemotingProtocol2.cs | 4 +- .../server/ServerRunspacePoolDriver.cs | 34 +-- .../server/ServerSteppablePipelineDriver.cs | 2 +- .../ServerSteppablePipelineSubscriber.cs | 2 +- .../remoting/server/serverremotesession.cs | 18 +- .../server/serverremotesessionstatemachine.cs | 42 +-- .../serverremotingprotocolimplementation.cs | 2 +- .../engine/runtime/Binding/Binders.cs | 218 +++++++------- .../engine/runtime/CompiledScriptBlock.cs | 70 ++--- .../engine/runtime/Operations/ArrayOps.cs | 6 +- .../engine/runtime/Operations/ClassOps.cs | 4 +- .../engine/runtime/Operations/MiscOps.cs | 76 ++--- .../engine/runtime/Operations/VariableOps.cs | 12 +- .../engine/runtime/ScriptBlockToPowerShell.cs | 18 +- .../engine/scriptparameterbindercontroller.cs | 2 +- .../engine/serialization.cs | 148 ++++----- .../help/AliasHelpInfo.cs | 6 +- .../help/AliasHelpProvider.cs | 4 +- .../help/BaseCommandHelpInfo.cs | 76 ++--- .../help/CabinetNativeApi.cs | 4 +- .../help/CommandHelpProvider.cs | 42 +-- .../help/DefaultCommandHelpObjectBuilder.cs | 2 +- .../help/DscResourceHelpProvider.cs | 4 +- .../help/HelpCategoryInvalidException.cs | 2 +- .../help/HelpCommands.cs | 10 +- .../help/HelpCommentsParser.cs | 28 +- .../help/HelpErrorTracer.cs | 2 +- .../help/HelpFileHelpInfo.cs | 2 +- .../help/HelpFileHelpProvider.cs | 2 +- .../help/HelpInfo.cs | 18 +- .../help/HelpNotFoundException.cs | 2 +- .../help/HelpRequest.cs | 8 +- .../help/HelpSystem.cs | 14 +- .../help/HelpUtils.cs | 2 +- .../help/MUIFileSearcher.cs | 6 +- .../help/MamlCommandHelpInfo.cs | 12 +- .../help/MamlNode.cs | 56 ++-- .../help/MamlUtil.cs | 10 +- .../help/PSClassHelpProvider.cs | 4 +- .../help/ProviderCommandHelpInfo.cs | 2 +- .../help/ProviderContext.cs | 6 +- .../help/ProviderHelpInfo.cs | 68 ++--- .../help/ProviderHelpProvider.cs | 14 +- .../help/RemoteHelpInfo.cs | 4 +- .../help/SaveHelpCommand.cs | 2 +- .../help/UpdatableHelpCommandBase.cs | 10 +- .../help/UpdatableHelpInfo.cs | 2 +- .../help/UpdatableHelpSystem.cs | 2 +- .../help/UpdateHelpCommand.cs | 6 +- .../logging/LogProvider.cs | 4 +- .../logging/MshLog.cs | 42 +-- .../namespaces/AliasProvider.cs | 2 +- .../namespaces/CoreCommandContext.cs | 26 +- .../namespaces/EnvironmentProvider.cs | 4 +- .../namespaces/FileSystemContentStream.cs | 6 +- .../namespaces/FileSystemProvider.cs | 76 ++--- .../namespaces/FileSystemSecurity.cs | 4 +- .../namespaces/FunctionProvider.cs | 2 +- .../namespaces/LocationGlobber.cs | 120 ++++---- .../namespaces/NavigationProviderBase.cs | 10 +- .../namespaces/PathInfo.cs | 10 +- .../namespaces/ProviderBase.cs | 62 ++-- .../namespaces/ProviderBaseSecurity.cs | 2 +- .../namespaces/RegistryProvider.cs | 98 +++--- .../namespaces/RegistrySecurity.cs | 6 +- .../namespaces/RegistryWrapper.cs | 8 +- .../namespaces/SessionStateProviderBase.cs | 6 +- .../namespaces/StackInfo.cs | 2 +- .../namespaces/VariableProvider.cs | 2 +- .../security/Authenticode.cs | 10 +- .../security/CredentialParameter.cs | 12 +- .../security/MshSignature.cs | 4 +- .../security/SecureStringHelper.cs | 6 +- .../security/SecurityManager.cs | 10 +- .../security/SecuritySupport.cs | 4 +- .../security/wldpNativeMethods.cs | 4 +- .../singleshell/config/MshSnapinInfo.cs | 50 +-- .../config/MshSnapinLoadException.cs | 4 +- .../utils/ClrFacade.cs | 8 +- .../utils/CommandDiscoveryExceptions.cs | 10 +- .../utils/CryptoUtils.cs | 10 +- .../utils/ExecutionExceptions.cs | 24 +- .../utils/ExtensionMethods.cs | 2 +- .../utils/MshArgumentException.cs | 4 +- .../utils/MshArgumentNullException.cs | 4 +- .../utils/MshArgumentOutOfRangeException.cs | 4 +- .../utils/MshInvalidOperationException.cs | 4 +- .../utils/MshNotImplementedException.cs | 4 +- .../utils/MshNotSupportedException.cs | 4 +- .../utils/MshObjectDisposedException.cs | 4 +- .../utils/MshTraceSource.cs | 4 +- .../utils/ObjectReader.cs | 10 +- .../utils/ObjectStream.cs | 36 +-- .../utils/ObjectWriter.cs | 2 +- .../utils/PSTelemetryWrapper.cs | 2 +- .../utils/ParameterBinderExceptions.cs | 10 +- .../utils/ParserException.cs | 6 +- .../utils/PowerShellETWTracer.cs | 8 +- .../utils/PowerShellExecutionHelper.cs | 12 +- .../utils/PsUtils.cs | 12 +- .../utils/ResourceManagerCache.cs | 6 +- .../utils/RuntimeException.cs | 22 +- .../utils/SessionStateExceptions.cs | 14 +- .../utils/StringUtil.cs | 4 +- .../utils/StructuredTraceSource.cs | 2 +- .../utils/tracing/EtwActivity.cs | 26 +- .../EtwActivityReverterMethodInvoker.cs | 2 +- .../utils/tracing/EtwEventCorrelator.cs | 2 +- .../utils/tracing/PSEtwLogProvider.cs | 2 +- .../utils/tracing/PSSysLogProvider.cs | 4 +- .../utils/tracing/SysLogProvider.cs | 4 +- .../utils/tracing/Tracing.cs | 6 +- test/xUnit/csharp/test_PSConfiguration.cs | 18 +- 581 files changed, 5031 insertions(+), 5031 deletions(-) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs index 0046b2a9a30..9cf9589326a 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs @@ -207,7 +207,7 @@ protected void AddCimSessionProxy(CimSessionProxy sessionproxy) { lock (cimSessionProxyCacheLock) { - if (this.cimSessionProxyCache is null) + if (this.cimSessionProxyCache == null) { this.cimSessionProxyCache = new List(); } @@ -349,7 +349,7 @@ protected virtual void SubscribeToCimSessionProxyEvent(CimSessionProxy proxy) protected object GetBaseObject(object value) { PSObject psObject = value as PSObject; - if (psObject is null) + if (psObject == null) { return value; } @@ -357,7 +357,7 @@ protected object GetBaseObject(object value) { object baseObject = psObject.BaseObject; var arrayObject = baseObject as object[]; - if (arrayObject is null) + if (arrayObject == null) { return baseObject; } @@ -389,7 +389,7 @@ protected object GetReferenceOrReferenceArrayObject(object value, ref CimType re { object baseObject = GetBaseObject(cimReference.Value); CimInstance cimInstance = baseObject as CimInstance; - if (cimInstance is null) + if (cimInstance == null) { return null; } @@ -400,7 +400,7 @@ protected object GetReferenceOrReferenceArrayObject(object value, ref CimType re else { object[] cimReferenceArray = value as object[]; - if (cimReferenceArray is null) + if (cimReferenceArray == null) { return null; } @@ -413,14 +413,14 @@ protected object GetReferenceOrReferenceArrayObject(object value, ref CimType re for (int i = 0; i < cimReferenceArray.Length; i++) { PSReference tempCimReference = cimReferenceArray[i] as PSReference; - if (tempCimReference is null) + if (tempCimReference == null) { return null; } object baseObject = GetBaseObject(tempCimReference.Value); cimInstanceArray[i] = baseObject as CimInstance; - if (cimInstanceArray[i] is null) + if (cimInstanceArray[i] == null) { return null; } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs index 87a6b3fda6a..2488490c514 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs @@ -336,7 +336,7 @@ internal void SetParameter(string parameterName, bool isBeginProcess) { DebugHelper.WriteLogEx("parameterset name = '{0}'; mandatory = '{1}'", 1, parameterDefinitionEntry.ParameterSetName, parameterDefinitionEntry.IsMandatory); ParameterSetEntry psEntry = this.parameterSetEntries[parameterDefinitionEntry.ParameterSetName]; - if (psEntry is null) + if (psEntry == null) continue; if (parameterDefinitionEntry.IsMandatory) @@ -460,7 +460,7 @@ internal string GetParameterSet() } // Looking for parameter set which has no mandatory parameters - if (boundParameterSetName is null) + if (boundParameterSetName == null) { // throw if there are > 1 parameter set if (noMandatoryParameterSet.Count > 1) @@ -474,13 +474,13 @@ internal string GetParameterSet() } // Looking for default parameter set - if (boundParameterSetName is null) + if (boundParameterSetName == null) { boundParameterSetName = defaultParameterSetName; } // throw if still can not find the parameter set name - if (boundParameterSetName is null) + if (boundParameterSetName == null) { throw new PSArgumentException(CimCmdletStrings.UnableToResolveParameterSetName); } @@ -552,7 +552,7 @@ internal void SetParameter(object value, string parameterName) // Null value could be set by caller unintentionally, // or by powershell to reset the parameter to default value // before the next parameter binding, and ProcessRecord call - if (value is null) + if (value == null) { return; } @@ -731,7 +731,7 @@ internal CimAsyncOperation AsyncOperation { lock (this.myLock) { - Debug.Assert(this.operation is null, "Caller should verify that operation is null"); + Debug.Assert(this.operation == null, "Caller should verify that operation is null"); this.operation = value; } } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetAssociatedInstance.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetAssociatedInstance.cs index fce4557432f..b0b95d14c50 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetAssociatedInstance.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetAssociatedInstance.cs @@ -39,7 +39,7 @@ public void GetCimAssociatedInstance(GetCimAssociatedInstanceCommand cmdlet) IEnumerable computerNames = ConstValue.GetComputerNames(cmdlet.ComputerName); // use the namespace from parameter string nameSpace = cmdlet.Namespace; - if ((nameSpace is null) && (cmdlet.ResourceUri is null)) + if ((nameSpace == null) && (cmdlet.ResourceUri == null)) { // try to use namespace of ciminstance, then fall back to default namespace nameSpace = ConstValue.GetNamespace(cmdlet.CimInstance.CimSystemProperties.Namespace); diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetCimClass.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetCimClass.cs index c3ea4debb01..a3826487e24 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetCimClass.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetCimClass.cs @@ -126,7 +126,7 @@ public void GetCimClass(GetCimClassCommand cmdlet) { List proxys = new List(); string nameSpace = ConstValue.GetNamespace(cmdlet.Namespace); - string className = (cmdlet.ClassName is null) ? @"*" : cmdlet.ClassName; + string className = (cmdlet.ClassName == null) ? @"*" : cmdlet.ClassName; CimGetCimClassContext context = new CimGetCimClassContext( cmdlet.ClassName, cmdlet.MethodName, diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs index af3a6d41f86..c462d5b9918 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs @@ -304,7 +304,7 @@ protected static string CreateQuery(CimBaseCommand cmdlet) if (cmd != null) { StringBuilder propertyList = new StringBuilder(); - if (cmd.SelectProperties is null) + if (cmd.SelectProperties == null) { propertyList.Append("*"); } @@ -321,7 +321,7 @@ protected static string CreateQuery(CimBaseCommand cmdlet) } } - return (cmd.Filter is null) ? + return (cmd.Filter == null) ? string.Format(CultureInfo.CurrentUICulture, queryWithoutWhere, propertyList, cmd.ClassName) : string.Format(CultureInfo.CurrentUICulture, queryWithWhere, propertyList, cmd.ClassName, cmd.Filter); } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs index 331057a1ab2..fd44d922009 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs @@ -81,7 +81,7 @@ public CimInstance NewEvent { get { - return (result is null) ? null : result.Instance; + return (result == null) ? null : result.Instance; } } @@ -92,7 +92,7 @@ public string MachineId { get { - return (result is null) ? null : result.MachineId; + return (result == null) ? null : result.MachineId; } } @@ -103,7 +103,7 @@ public string Bookmark { get { - return (result is null) ? null : result.Bookmark; + return (result == null) ? null : result.Bookmark; } } @@ -292,7 +292,7 @@ public void Start() { if (status == Status.Default) { - if (this.cimSession is null) + if (this.cimSession == null) { cimRegisterCimIndication.RegisterCimIndication( this.computerName, diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs index 94264208a4e..ba82ff9e432 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs @@ -359,7 +359,7 @@ private CimMethodParametersCollection CreateParametersCollection( DebugHelper.WriteLogEx(); CimMethodParametersCollection collection = null; - if (parameters is null) + if (parameters == null) { return collection; } @@ -389,7 +389,7 @@ private CimMethodParametersCollection CreateParametersCollection( { className = cimClass.CimSystemProperties.ClassName; declaration = cimClass.CimClassMethods[methodName]; - if (declaration is null) + if (declaration == null) { throw new ArgumentException(string.Format( CultureInfo.CurrentUICulture, CimCmdletStrings.InvalidMethod, methodName, className)); @@ -404,7 +404,7 @@ private CimMethodParametersCollection CreateParametersCollection( if (declaration != null) { CimMethodParameterDeclaration paramDeclaration = declaration.Parameters[parameterName]; - if (paramDeclaration is null) + if (paramDeclaration == null) { throw new ArgumentException(string.Format( CultureInfo.CurrentUICulture, CimCmdletStrings.InvalidMethodParameter, parameterName, methodName, className)); @@ -420,7 +420,7 @@ private CimMethodParametersCollection CreateParametersCollection( } else { - if (parameterValue is null) + if (parameterValue == null) { // try the best to get the type while value is null parameter = CimMethodParameter.Create( diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs index 22226fe908a..14c57c87888 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs @@ -181,14 +181,14 @@ internal void GetCimInstance(CimInstance cimInstance, XOperationContextBase cont DebugHelper.WriteLogEx(); CimNewCimInstanceContext newCimInstanceContext = context as CimNewCimInstanceContext; - if (newCimInstanceContext is null) + if (newCimInstanceContext == null) { DebugHelper.WriteLog("Invalid (null) CimNewCimInstanceContext", 1); return; } CimSessionProxy proxy = CreateCimSessionProxy(newCimInstanceContext.Proxy); - string nameSpace = (cimInstance.CimSystemProperties.Namespace is null) ? newCimInstanceContext.Namespace : cimInstance.CimSystemProperties.Namespace; + string nameSpace = (cimInstance.CimSystemProperties.Namespace == null) ? newCimInstanceContext.Namespace : cimInstance.CimSystemProperties.Namespace; proxy.GetInstanceAsync(nameSpace, cimInstance); } @@ -268,7 +268,7 @@ private CimInstance CreateCimInstance( NewCimInstanceCommand cmdlet) { CimInstance cimInstance = new CimInstance(className, cimNamespace); - if (properties is null) + if (properties == null) { return cimInstance; } @@ -332,7 +332,7 @@ private CimInstance CreateCimInstance( NewCimInstanceCommand cmdlet) { CimInstance cimInstance = new CimInstance(cimClass); - if (properties is null) + if (properties == null) { return cimInstance; } @@ -340,7 +340,7 @@ private CimInstance CreateCimInstance( List notfoundProperties = new List(); foreach (string property in properties.Keys) { - if (cimInstance.CimInstanceProperties[property] is null) + if (cimInstance.CimInstanceProperties[property] == null) { notfoundProperties.Add(property); cmdlet.ThrowInvalidProperty(notfoundProperties, cmdlet.CimClass.CimSystemProperties.ClassName, @"Property", action, properties); diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs index 9f9e72c6aab..559c58b8a11 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs @@ -167,7 +167,7 @@ public void RegisterCimIndication( UInt32 operationTimeout) { DebugHelper.WriteLogEx("queryDialect = '{0}'; queryExpression = '{1}'", 0, queryDialect, queryExpression); - if (cimSession is null) + if (cimSession == null) { throw new ArgumentNullException(string.Format(CultureInfo.CurrentUICulture, CimCmdletStrings.NullArgument, @"cimSession")); } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs index d9dca494c59..55cf540c0e8 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs @@ -331,7 +331,7 @@ public virtual void OnNext(T value) { DebugHelper.WriteLogEx("value = {0}.", 1, value); // do not allow null value - if (value is null) + if (value == null) { return; } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs index 846419b9939..0dd85ea213c 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs @@ -138,7 +138,7 @@ internal CimSessionWrapper( internal PSObject GetPSObject() { - if (psObject is null) + if (psObject == null) { psObject = new PSObject(this.cimSession); psObject.Properties.Add(new PSNoteProperty(CimSessionState.idPropName, this.sessionId)); @@ -965,7 +965,7 @@ internal void NewCimSession(NewCimSessionCommand cmdlet, foreach (string computerName in computerNames) { CimSessionProxy proxy; - if (sessionOptions is null) + if (sessionOptions == null) { DebugHelper.WriteLog("Create CimSessionOption due to NewCimSessionCommand has null sessionoption", 1); sessionOptions = CimSessionProxy.CreateCimSessionOption(computerName, @@ -1150,7 +1150,7 @@ public void GetCimSession(GetCimSessionCommand cmdlet) switch (cmdlet.ParameterSetName) { case CimBaseCommand.ComputerNameSet: - if (cmdlet.ComputerName is null) + if (cmdlet.ComputerName == null) { sessionToGet = this.sessionState.QuerySession(ConstValue.DefaultSessionName, out errorRecords); } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs index e6b65f0409b..084bad51d91 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs @@ -670,7 +670,7 @@ private void InitOption(CimOperationOptions operOptions) { this.options = new CimOperationOptions(operOptions); } - else if (this.options is null) + else if (this.options == null) { this.options = new CimOperationOptions(); } @@ -735,7 +735,7 @@ private void RemoveOperation(IObservable operation) this.operation = null; } - if (this.session != null && this.ContextObject is null) + if (this.session != null && this.ContextObject == null) { DebugHelper.WriteLog("Dispose this proxy object @ RemoveOperation"); this.Dispose(); @@ -1049,7 +1049,7 @@ internal void ResultEventHandler( /// private static void AddShowComputerNameMarker(object o) { - if (o is null) + if (o == null) { return; } @@ -1547,7 +1547,7 @@ internal CimOperationOptions OperationOptions /// private bool Completed { - get { return this.operation is null; } + get { return this.operation == null; } } /// @@ -1918,7 +1918,7 @@ private void CheckAvailability() /// private void AssertSession() { - if (this.IsDisposed || (this.session is null)) + if (this.IsDisposed || (this.session == null)) { DebugHelper.WriteLogEx("Invalid CimSessionProxy object, disposed? {0}; session object {1}", 1, this.IsDisposed, this.session); throw new ObjectDisposedException(this.ToString()); @@ -2094,7 +2094,7 @@ protected override bool PreNewActionEvent(CmdletActionEventArgs args) CimWriteResultObject writeResultObject = args.Action as CimWriteResultObject; CimClass cimClass = writeResultObject.Result as CimClass; - if (cimClass is null) + if (cimClass == null) { return true; } @@ -2248,7 +2248,7 @@ protected override bool PreNewActionEvent(CmdletActionEventArgs args) CimWriteResultObject writeResultObject = args.Action as CimWriteResultObject; CimInstance cimInstance = writeResultObject.Result as CimInstance; - if (cimInstance is null) + if (cimInstance == null) { return true; } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSetCimInstance.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSetCimInstance.cs index b156e5af79d..fbe0830318d 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSetCimInstance.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSetCimInstance.cs @@ -243,7 +243,7 @@ private bool SetProperty(IDictionary properties, ref CimInstance cimInstance, re else // For dynamic instance, it is valid to add a new property { CimProperty newProperty; - if (value is null) + if (value == null) { newProperty = CimProperty.Create( key, diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs index 676e4234a52..fbd780450ab 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs @@ -155,7 +155,7 @@ internal static ErrorRecord InitializeErrorRecordCore( theTargetObject = cimResultContext.ErrorSource; } - if (theTargetObject is null) + if (theTargetObject == null) { if (context != null) { @@ -172,7 +172,7 @@ internal static ErrorRecord InitializeErrorRecordCore( errorCategory: errorCategory, targetObject: theTargetObject); - if (context is null) + if (context == null) { return coreErrorRecord; } @@ -284,13 +284,13 @@ internal static ErrorCategory ConvertCimNativeErrorCodeToErrorCategory(NativeErr /// internal static ErrorCategory ConvertCimErrorToErrorCategory(CimInstance cimError) { - if (cimError is null) + if (cimError == null) { return ErrorCategory.NotSpecified; } CimProperty errorCategoryProperty = cimError.CimInstanceProperties[@"Error_Category"]; - if (errorCategoryProperty is null) + if (errorCategoryProperty == null) { return ErrorCategory.NotSpecified; } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs index 89b9a674bf0..eeb4cba4c4d 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs @@ -295,7 +295,7 @@ internal void BuildSessionOptions(out CimSessionOptions outputOptions, out CimCr if (portSet || (this.CertificateThumbprint != null)) { - WSManSessionOptions wsmanOptions = (options is null) ? new WSManSessionOptions() : options as WSManSessionOptions; + WSManSessionOptions wsmanOptions = (options == null) ? new WSManSessionOptions() : options as WSManSessionOptions; if (portSet) { wsmanOptions.DestinationPort = this.Port; @@ -328,7 +328,7 @@ internal void BuildSessionOptions(out CimSessionOptions outputOptions, out CimCr } CimCredential credentials = CreateCimCredentials(this.Credential, authentication, @"New-CimSession", @"Authentication"); - if (credentials is null) + if (credentials == null) { return; } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs index 911e4156e08..de7bd63feae 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs @@ -301,7 +301,7 @@ private void CheckArgument() /// private void SetParameter(object value, string parameterName) { - if (value is null) + if (value == null) { return; } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs index d7ba928f6fa..10fbc48a444 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs @@ -90,7 +90,7 @@ internal static bool IsDefaultComputerName(string computerName) /// internal static IEnumerable GetComputerNames(IEnumerable computerNames) { - return (computerNames is null) ? NullComputerNames : computerNames; + return (computerNames == null) ? NullComputerNames : computerNames; } /// @@ -112,7 +112,7 @@ internal static string GetComputerName(string computerName) /// internal static string GetNamespace(string nameSpace) { - return (nameSpace is null) ? DefaultNameSpace : nameSpace; + return (nameSpace == null) ? DefaultNameSpace : nameSpace; } /// @@ -124,7 +124,7 @@ internal static string GetNamespace(string nameSpace) /// internal static string GetQueryDialectWithDefault(string queryDialect) { - return (queryDialect is null) ? DefaultQueryDialect : queryDialect; + return (queryDialect == null) ? DefaultQueryDialect : queryDialect; } } @@ -390,7 +390,7 @@ internal static class ValidationHelper /// public static void ValidateNoNullArgument(object obj, string argumentName) { - if (obj is null) + if (obj == null) { throw new ArgumentNullException(argumentName); } diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSet.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSet.cs index 14695861837..c1474ec4209 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSet.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSet.cs @@ -19,7 +19,7 @@ internal CounterSet(string setName, ref Dictionary counterInstanceMapping) { _counterSetName = setName; - if (machineName is null || machineName.Length == 0) + if (machineName == null || machineName.Length == 0) { machineName = "."; } diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs index a596f861cfd..33e127565e6 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs @@ -890,7 +890,7 @@ private void ReadEvents(EventLogQuery logQuery) continue; } - if (evtObj is null) + if (evtObj == null) { break; } @@ -1454,7 +1454,7 @@ private string HandleContextHashValue(object value) WriteDebug(string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("InvalidSIDFormat"), value)); } - if (sidCandidate is null) + if (sidCandidate == null) { try { @@ -1839,7 +1839,7 @@ private void CheckHashTablesForNullValues() foreach (string key in hash.Keys) { object value = hash[key]; - if (value is null) + if (value == null) { string msg = _resourceMgr.GetString("NullNotAllowedInHashtable"); Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, key)); @@ -1852,7 +1852,7 @@ private void CheckHashTablesForNullValues() { foreach (object elt in eltArray) { - if (elt is null) + if (elt == null) { string msg = _resourceMgr.GetString("NullNotAllowedInHashtable"); Exception exc = new Exception(string.Format(CultureInfo.InvariantCulture, msg, key)); @@ -2052,7 +2052,7 @@ private void AddLogsForProviderToInternalMap(EventLogSession eventLogSession, st // private void FindLogNamesMatchingWildcards(EventLogSession eventLogSession, IEnumerable logPatterns) { - if (_logNamesMatchingWildcard is null) + if (_logNamesMatchingWildcard == null) { _logNamesMatchingWildcard = new StringCollection(); } diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs index 4147fe309d5..216e9bca7ea 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs @@ -164,7 +164,7 @@ private void LoadProvider() } } - if (_providerMetadata is null) + if (_providerMetadata == null) { string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("NoProviderFound"), _providerName); throw new ArgumentException(msg); @@ -211,7 +211,7 @@ private void LoadEventDescriptor() } } - if (matchedEvent is null) + if (matchedEvent == null) { string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("IncorrectEventVersion"), @@ -270,7 +270,7 @@ private bool VerifyTemplate(EventMetadata emd) } } - if ((_payload is null && definedParameterCount != 0) + if ((_payload == null && definedParameterCount != 0) || ((_payload != null) && _payload.Length != definedParameterCount)) { string warning = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("PayloadMismatch"), _id, emd.Template); @@ -322,7 +322,7 @@ protected override void ProcessRecord() { for (int i = 0; i < _payload.Length; i++) { - if (_payload[i] is null) + if (_payload[i] == null) { _payload[i] = string.Empty; } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs index ab74e6f1a38..9ad44f3a07f 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs @@ -79,7 +79,7 @@ protected TSession[] Session set { - if (value is null) + if (value == null) { throw new ArgumentNullException("value"); } @@ -149,7 +149,7 @@ private StartableJob DoCreateQueryJob(TSession sessionForJob, QueryBuilder query queryJob, sessionForJob, discardNonPipelineResults, - actionAgainstResults is null + actionAgainstResults == null ? (Action)null : delegate (PSObject pso) { @@ -241,7 +241,7 @@ private void HandleJobOutput(Job job, TSession sessionForJob, bool discardNonPip Action processOutput = delegate (PSObject pso) { - if (pso is null) + if (pso == null) { return; } @@ -460,13 +460,13 @@ private IEnumerable GetSessionsToActAgainst(TObjectInstance objectInst private TSession GetSessionAssociatedWithPipelineObject() { object inputVariableValue = this.Cmdlet.Context.GetVariableValue(SpecialVariables.InputVarPath, null); - if (inputVariableValue is null) + if (inputVariableValue == null) { return null; } IEnumerable inputEnumerable = LanguagePrimitives.GetEnumerable(inputVariableValue); - if (inputEnumerable is null) + if (inputEnumerable == null) { return null; } @@ -581,8 +581,8 @@ private TSession GetImpliedSession() /// true if successful method invocations should emit downstream the being operated on. public override void ProcessRecord(TObjectInstance objectInstance, MethodInvocationInfo methodInvocationInfo, bool passThru) { - if (objectInstance is null) throw new ArgumentNullException(nameof(objectInstance)); - if (methodInvocationInfo is null) throw new ArgumentNullException(nameof(methodInvocationInfo)); + if (objectInstance == null) throw new ArgumentNullException(nameof(objectInstance)); + if (methodInvocationInfo == null) throw new ArgumentNullException(nameof(methodInvocationInfo)); foreach (TSession sessionForJob in this.GetSessionsToActAgainst(objectInstance)) { @@ -607,7 +607,7 @@ public override void ProcessRecord(TObjectInstance objectInstance, MethodInvocat /// Method invocation details. public override void ProcessRecord(MethodInvocationInfo methodInvocationInfo) { - if (methodInvocationInfo is null) throw new ArgumentNullException(nameof(methodInvocationInfo)); + if (methodInvocationInfo == null) throw new ArgumentNullException(nameof(methodInvocationInfo)); foreach (TSession sessionForJob in this.GetSessionsToActAgainst(methodInvocationInfo)) { diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs index 69c7ee6bfb4..092103d6fe7 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs @@ -54,7 +54,7 @@ protected CimJobException( SerializationInfo info, StreamingContext context) : base(info, context) { - if (info is null) + if (info == null) { throw new ArgumentNullException(nameof(info)); } @@ -69,7 +69,7 @@ protected CimJobException( /// The that contains contextual information about the source or destination. public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) { throw new ArgumentNullException(nameof(info)); } @@ -328,13 +328,13 @@ private static ErrorCategory ConvertCimNativeErrorCodeToErrorCategory(NativeErro private static ErrorCategory ConvertCimErrorToErrorCategory(CimInstance cimError) { - if (cimError is null) + if (cimError == null) { return ErrorCategory.NotSpecified; } CimProperty errorCategoryProperty = cimError.CimInstanceProperties["Error_Category"]; - if (errorCategoryProperty is null) + if (errorCategoryProperty == null) { return ErrorCategory.NotSpecified; } @@ -363,13 +363,13 @@ internal bool IsTerminatingError get { var cimException = this.InnerException as CimException; - if ((cimException is null) || (cimException.ErrorData is null)) + if ((cimException == null) || (cimException.ErrorData == null)) { return false; } CimProperty perceivedSeverityProperty = cimException.ErrorData.CimInstanceProperties["PerceivedSeverity"]; - if ((perceivedSeverityProperty is null) || (perceivedSeverityProperty.CimType != CimType.UInt16) || (perceivedSeverityProperty.Value is null)) + if ((perceivedSeverityProperty == null) || (perceivedSeverityProperty.CimType != CimType.UInt16) || (perceivedSeverityProperty.Value == null)) { return false; } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CreateInstanceJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CreateInstanceJob.cs index 253f501160e..7f76ff98574 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CreateInstanceJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CreateInstanceJob.cs @@ -59,7 +59,7 @@ private IObservable GetGetInstanceOperation() internal override IObservable GetCimOperation() { - if (_resultFromCreateInstance is null) + if (_resultFromCreateInstance == null) { if (!this.ShouldProcess()) { @@ -78,7 +78,7 @@ internal override IObservable GetCimOperation() #if DEBUG Dbg.Assert(_createInstanceOperationGotStarted, "GetInstance should be started *after* CreateInstance"); Dbg.Assert(_getInstanceOperationGotStarted == false, "Should not start GetInstance operation twice"); - Dbg.Assert(_resultFromGetInstance is null, "GetInstance operation shouldn't happen twice"); + Dbg.Assert(_resultFromGetInstance == null, "GetInstance operation shouldn't happen twice"); _getInstanceOperationGotStarted = true; #endif return GetGetInstanceOperation(); @@ -88,13 +88,13 @@ internal override IObservable GetCimOperation() public override void OnNext(CimInstance item) { Dbg.Assert(item != null, "CreateInstance and GetInstance should never return null"); - if (_resultFromCreateInstance is null) + if (_resultFromCreateInstance == null) { _resultFromCreateInstance = item; } else { - Dbg.Assert(_resultFromGetInstance is null, "GetInstance operation shouldn't happen twice"); + Dbg.Assert(_resultFromGetInstance == null, "GetInstance operation shouldn't happen twice"); _resultFromGetInstance = item; } } @@ -123,7 +123,7 @@ public override void OnCompleted() // <=> (this._getInstanceOperationGotStarted => (this._resultFromGetInstance != null)) "GetInstance should cause OnNext to be called which should set this._resultFromGetInstance to non-null"); #endif - if (this.IsPassThruObjectNeeded() && (_resultFromGetInstance is null)) + if (this.IsPassThruObjectNeeded() && (_resultFromGetInstance == null)) { IObservable observable = this.GetGetInstanceOperation(); observable.Subscribe(this); diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs index 7fa2a0de7a2..3a8b0e2200c 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs @@ -58,7 +58,7 @@ private void ProcessOutParameter(CimMethodResult methodResult, MethodParameter m Dbg.Assert(this.MethodSubject != null, "MethodSubject property should be initialized before starting main job processing"); CimMethodParameter outParameter = methodResult.OutParameters[methodParameter.Name]; - object valueReturnedFromMethod = (outParameter is null) ? null : outParameter.Value; + object valueReturnedFromMethod = (outParameter == null) ? null : outParameter.Value; object dotNetValue = CimValueConverter.ConvertFromCimToDotNet(valueReturnedFromMethod, methodParameter.ParameterType); if (MethodParameterBindings.Out == (methodParameter.Bindings & MethodParameterBindings.Out)) @@ -106,7 +106,7 @@ private void OnNext(CimMethodResult methodResult) if (cmdletOutput.Count == 1) { var singleOutputParameter = cmdletOutput.Values.Single(); - if (singleOutputParameter.Value is null) + if (singleOutputParameter.Value == null) { return; } @@ -141,7 +141,7 @@ private void OnNext(CimMethodStreamedResult streamedResult) { MethodParameter methodParameter = this.GetMethodOutputParameters() .SingleOrDefault(p => p.Name.Equals(streamedResult.ParameterName, StringComparison.OrdinalIgnoreCase)); - if (methodParameter is null) + if (methodParameter == null) { string errorMessage = string.Format( CultureInfo.InvariantCulture, diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/MethodInvocationJobBase.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/MethodInvocationJobBase.cs index 57179290e33..075e218ea60 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/MethodInvocationJobBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/MethodInvocationJobBase.cs @@ -84,7 +84,7 @@ internal override CimCustomOptionsDictionary CalculateJobSpecificCustomOptions() .GetMethodInputParametersCore(p => p.Name.StartsWith(CustomOperationOptionPrefix, StringComparison.OrdinalIgnoreCase)); foreach (MethodParameter customOption in customOptions) { - if (customOption.Value is null) + if (customOption.Value == null) { continue; } 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 59bbc77d913..8ee336de383 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJobBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJobBase.cs @@ -29,7 +29,7 @@ public override void OnNext(CimInstance item) delegate { Dbg.Assert(item != null, "When OnNext is called from our IObservable, item parameter should always be != null"); - if (item is null) + if (item == null) { return; } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs index 549bd296c8f..730e54a6391 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs @@ -139,7 +139,7 @@ internal Exception GetExceptionIfBrokenSession( CimException cimException; potentiallyBrokenSession.TestConnection(out throwAwayCimInstance, out cimException); sessionException = cimException; - if (sessionException is null) + if (sessionException == null) { this.MarkSessionAsConnected(potentiallyBrokenSession); } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs index 0f1bbf842dd..3743d1965f0 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs @@ -85,7 +85,7 @@ private enum WsManErrorCode : uint private static bool IsWsManQuotaReached(Exception exception) { var cimException = exception as CimException; - if (cimException is null) + if (cimException == null) { return false; } @@ -96,13 +96,13 @@ private static bool IsWsManQuotaReached(Exception exception) } CimInstance cimError = cimException.ErrorData; - if (cimError is null) + if (cimError == null) { return false; } CimProperty errorCodeProperty = cimError.CimInstanceProperties["error_Code"]; - if (errorCodeProperty is null) + if (errorCodeProperty == null) { return false; } @@ -219,7 +219,7 @@ private void SleepAndRetry() } else { - Dbg.Assert(_sleepAndRetryTimer is null, "There should be only 1 active _sleepAndRetryTimer"); + Dbg.Assert(_sleepAndRetryTimer == null, "There should be only 1 active _sleepAndRetryTimer"); _sleepAndRetryTimer = new Timer( state: null, dueTime: delay, @@ -239,7 +239,7 @@ public override string Location // this.JobContext is set in the constructor of CimChildJobBase, // but the constructor of Job wants to access Location property // before CimChildJobBase is fully initialized - if (this.JobContext is null) + if (this.JobContext == null) { return null; } @@ -1011,7 +1011,7 @@ internal static bool IsShowComputerNameMarkerPresent(CimInstance cimInstance) { PSObject pso = PSObject.AsPSObject(cimInstance); PSPropertyInfo psShowComputerNameProperty = pso.InstanceMembers[RemotingConstants.ShowComputerNameNoteProperty] as PSPropertyInfo; - if (psShowComputerNameProperty is null) + if (psShowComputerNameProperty == null) { return false; } @@ -1055,13 +1055,13 @@ internal override void WriteObject(object outputObject) if (this.JobContext.ShowComputerName) { - if (pso is null) + if (pso == null) { pso = PSObject.AsPSObject(outputObject); } AddShowComputerNameMarker(pso); - if (cimInstance is null) + if (cimInstance == null) { pso.Properties.Add(new PSNoteProperty(RemotingConstants.ComputerNameNoteProperty, this.JobContext.Session.ComputerName)); } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs index 06cdb19cefc..033b8813534 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs @@ -38,7 +38,7 @@ internal SensitiveString(int numberOfCharacters) _string = new string('\0', numberOfCharacters); Debug.Assert( - string.IsInterned(_string) is null, + string.IsInterned(_string) == null, "We will overwrite string contents - we can't / shouldn't do this for interned strings."); /* The string is pinned (while still being filled with insignificant data) @@ -115,7 +115,7 @@ public void Dispose() /// private void Dispose(bool disposing) { - if (_string is null) + if (_string == null) { return; } @@ -160,7 +160,7 @@ private void Dispose(bool disposing) internal object ConvertFromDotNetToCim(object dotNetObject) { - if (dotNetObject is null) + if (dotNetObject == null) { return null; } @@ -236,7 +236,7 @@ internal static class CimValueConverter /// The only kind of exception this method can throw. internal static object ConvertFromDotNetToCim(object dotNetObject) { - if (dotNetObject is null) + if (dotNetObject == null) { return null; } @@ -260,7 +260,7 @@ internal static object ConvertFromDotNetToCim(object dotNetObject) if (typeof(PSReference).IsAssignableFrom(dotNetType)) { PSReference psReference = (PSReference)psObject.BaseObject; - if (psReference.Value is null) + if (psReference.Value == null) { return null; } @@ -352,9 +352,9 @@ internal static object ConvertFromDotNetToCim(object dotNetObject) /// The only kind of exception this method can throw. internal static object ConvertFromCimToDotNet(object cimObject, Type expectedDotNetType) { - if (expectedDotNetType is null) { throw new ArgumentNullException(nameof(expectedDotNetType)); } + if (expectedDotNetType == null) { throw new ArgumentNullException(nameof(expectedDotNetType)); } - if (cimObject is null) + if (cimObject == null) { return null; } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimJobContext.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimJobContext.cs index 9f2fb50801b..5dcca85a9b9 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimJobContext.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimJobContext.cs @@ -98,7 +98,7 @@ private static string GetCimNamespace(string cmdletizationClassName) internal string PrependComputerNameToMessage(string message) { string computerName = this.Session.ComputerName; - if (computerName is null) + if (computerName == null) { return message; } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimOperationOptionsHelper.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimOperationOptionsHelper.cs index d15e7e87eaf..17801923bf0 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimOperationOptionsHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimOperationOptionsHelper.cs @@ -46,7 +46,7 @@ internal static CimCustomOptionsDictionary Create(IEnumerable TestPowerShell(List computerNames, List psObjectCollection = powershell.Invoke(new object[] { credential, computerNames.ToArray() }); - if (psObjectCollection is null) + if (psObjectCollection == null) { Dbg.Diagnostics.Assert(false, "This should never happen. Invoke should never return null."); } @@ -1378,7 +1378,7 @@ private string ValidateComputerName() // Validate target name. ErrorRecord targetError = null; string targetComputer = ComputerWMIHelper.ValidateComputerName(ComputerName, _shortLocalMachineName, _fullLocalMachineName, ref targetError); - if (targetComputer is null) + if (targetComputer == null) { if (targetError != null) { @@ -1489,14 +1489,14 @@ private void DoRenameComputerWsman(string computer, string computerName, string "UserName", dUserName, Microsoft.Management.Infrastructure.CimType.String, - (dUserName is null) ? CimFlags.NullValue : CimFlags.None)); + (dUserName == null) ? CimFlags.NullValue : CimFlags.None)); methodParameters.Add( CimMethodParameter.Create( "Password", dPassword, Microsoft.Management.Infrastructure.CimType.String, - (dPassword is null) ? CimFlags.NullValue : CimFlags.None)); + (dPassword == null) ? CimFlags.NullValue : CimFlags.None)); if (!InternalTestHooks.TestRenameComputer) { @@ -1582,7 +1582,7 @@ private void DoRenameComputerWsman(string computer, string computerName, string protected override void ProcessRecord() { string targetComputer = ValidateComputerName(); - if (targetComputer is null) return; + if (targetComputer == null) return; bool isLocalhost = targetComputer.Equals("localhost", StringComparison.OrdinalIgnoreCase); if (isLocalhost) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ComputerUnix.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ComputerUnix.cs index 420312808b1..023fc1d0501 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ComputerUnix.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ComputerUnix.cs @@ -116,7 +116,7 @@ public void Dispose() /// protected override void StopProcessing() { - if (_process is null) { + if (_process == null) { return; } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs index da9c0cc4d00..b595c0195f9 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs @@ -343,7 +343,7 @@ internal ContentHolder( IContentReader reader, IContentWriter writer) { - if (pathInfo is null) + if (pathInfo == null) { throw PSTraceSource.NewArgumentNullException(nameof(pathInfo)); } @@ -365,7 +365,7 @@ internal ContentHolder( /// internal void CloseContent(List contentHolders, bool disposing) { - if (contentHolders is null) + if (contentHolders == null) { throw PSTraceSource.NewArgumentNullException(nameof(contentHolders)); } @@ -662,7 +662,7 @@ internal Collection ResolvePaths( } else { - if (pathNotFoundErrorRecord is null) + if (pathNotFoundErrorRecord == null) { // Detect if the path resolution failed to resolve to a file. string error = StringUtil.Format(NavigationResources.ItemNotFound, Path); diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetChildrenCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetChildrenCommand.cs index b6ff487fcdb..3dcd0d51c4a 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetChildrenCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetChildrenCommand.cs @@ -288,7 +288,7 @@ protected override void ProcessRecord() { CmdletProviderContext currentContext = CmdletProviderContext; - if (_paths is null || _paths.Length == 0) + if (_paths == null || _paths.Length == 0) { _paths = new string[] { string.Empty }; } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs index d7cb6dbd3f6..d73d191585e 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs @@ -226,7 +226,7 @@ protected override void ProcessRecord() private void UpdateProgress(string status) { ProgressRecord progress = new ProgressRecord(0, activity, status ?? ComputerResources.ProgressStatusCompleted); - progress.RecordType = status is null ? ProgressRecordType.Completed : ProgressRecordType.Processing; + progress.RecordType = status == null ? ProgressRecordType.Completed : ProgressRecordType.Processing; WriteProgress(progress); } @@ -314,7 +314,7 @@ private static NetworkAdapter[] GetNetworkAdapters(CimSession session) }; var status = EnumConverter.Convert(adapter.NetConnectionStatus); - nwAdapter.ConnectionStatus = status is null ? NetConnectionStatus.Other + nwAdapter.ConnectionStatus = status == null ? NetConnectionStatus.Other : status.Value; if (nwAdapter.ConnectionStatus == NetConnectionStatus.Connected) @@ -1130,7 +1130,7 @@ internal static string GetLocaleName(string locale) culture = CultureInfo.GetCultureInfo((int)localeNum); } - if (culture is null) + if (culture == null) { // If TryParse failed we'll try using the original string as culture name culture = CultureInfo.GetCultureInfo(locale); @@ -1142,7 +1142,7 @@ internal static string GetLocaleName(string locale) } } - return culture is null ? null : culture.Name; + return culture == null ? null : culture.Name; } /// @@ -1283,7 +1283,7 @@ public static RegWinNtCurrentVersion GetWinNtCurrentVersion() CurrentVersion = (string)key.GetValue("CurrentVersion"), EditionId = (string)key.GetValue("EditionID"), InstallationType = (string)key.GetValue("InstallationType"), - InstallDate = temp is null ? (DateTime?)null + InstallDate = temp == null ? (DateTime?)null : Conversion.UnixSecondsToDateTime((long)(int)temp), ProductId = (string)key.GetValue("ProductId"), ProductName = (string)key.GetValue("ProductName"), @@ -1886,7 +1886,7 @@ public string GetLocale() #region Private Methods private OSProductSuite[] MakeProductSuites(uint? suiteMask) { - if (suiteMask is null) + if (suiteMask == null) return null; var mask = suiteMask.Value; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetPropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetPropertyCommand.cs index 826bfb5d406..7f6e4c5b1b4 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetPropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetPropertyCommand.cs @@ -274,7 +274,7 @@ internal override object GetDynamicParameters(CmdletProviderContext context) /// protected override void ProcessRecord() { - if (Path is null || Path.Length == 0) + if (Path == null || Path.Length == 0) { paths = new string[] { "." }; } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/MovePropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/MovePropertyCommand.cs index eb4f9f8dc7d..0fcc8a3a244 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/MovePropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/MovePropertyCommand.cs @@ -57,7 +57,7 @@ public string[] Name set { - if (value is null) + if (value == null) { value = Array.Empty(); } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs index 1edb5c5f239..4389f657f69 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs @@ -505,7 +505,7 @@ protected override void ProcessRecord() } } // If the drive wasn't specified but the provider was - else if ((PSDrive is null || PSDrive.Length == 0) && + else if ((PSDrive == null || PSDrive.Length == 0) && (PSProvider != null && PSProvider.Length > 0)) { foreach (string providerName in PSProvider) @@ -1370,7 +1370,7 @@ internal List GetMatchingDrives( { List results = new List(); - if (providerNames is null || providerNames.Length == 0) + if (providerNames == null || providerNames.Length == 0) { providerNames = new string[] { "*" }; } @@ -1419,7 +1419,7 @@ internal List GetMatchingDrives( { pssnapinQualifiedProviderName = PSSnapinQualifiedName.GetInstance(providerName); - if (pssnapinQualifiedProviderName is null) + if (pssnapinQualifiedProviderName == null) { // This is a malformed pssnapin-qualified name so there is no chances for a match. continue; @@ -1582,7 +1582,7 @@ protected override void ProcessRecord() string resourceTemplate = NavigationResources.RemoveDriveConfirmResourceTemplate; bool verifyMatch = true; - if (_names is null) + if (_names == null) { _names = new string[] { string.Empty }; verifyMatch = false; @@ -2109,7 +2109,7 @@ internal override object GetDynamicParameters(CmdletProviderContext context) /// protected override void ProcessRecord() { - if (Path is null || Path.Length == 0) + if (Path == null || Path.Length == 0) { Path = new string[] { string.Empty }; } @@ -3329,7 +3329,7 @@ protected override void ProcessRecord() } Collection resolvedPaths = GetResolvedPaths(Path); - if (resolvedPaths is null) + if (resolvedPaths == null) { return; } @@ -4158,7 +4158,7 @@ public string[] PSProvider /// protected override void ProcessRecord() { - if (PSProvider is null || PSProvider.Length == 0) + if (PSProvider == null || PSProvider.Length == 0) { // Get all the providers diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/PingPathCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/PingPathCommand.cs index caf9b407252..29b905cb0ff 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/PingPathCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/PingPathCommand.cs @@ -168,7 +168,7 @@ internal override object GetDynamicParameters(CmdletProviderContext context) /// protected override void ProcessRecord() { - if (_paths is null || _paths.Length == 0) + if (_paths == null || _paths.Length == 0) { WriteError(new ErrorRecord( new ArgumentNullException(TestPathResources.PathIsNullOrEmptyCollection), @@ -185,7 +185,7 @@ protected override void ProcessRecord() { bool result = false; - if (path is null) + if (path == null) { WriteError(new ErrorRecord( new ArgumentNullException(TestPathResources.PathIsNullOrEmptyCollection), diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs index 888c6026c76..c20ef98a80d 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs @@ -168,7 +168,7 @@ private static int ProcessComparison(Process x, Process y) /// private void RetrieveMatchingProcessesByProcessName() { - if (processNames is null) + if (processNames == null) { _matchingProcesses = new List(AllProcesses); return; @@ -220,7 +220,7 @@ private void RetrieveMatchingProcessesByProcessName() /// private void RetrieveMatchingProcessesById() { - if (processIds is null) + if (processIds == null) { Diagnostics.Assert(false, "null processIds"); throw PSTraceSource.NewInvalidOperationException(); @@ -256,7 +256,7 @@ private void RetrieveMatchingProcessesById() /// private void RetrieveProcessesByInput() { - if (InputObject is null) + if (InputObject == null) { Diagnostics.Assert(false, "null InputObject"); throw PSTraceSource.NewInvalidOperationException(); @@ -282,7 +282,7 @@ internal Process[] AllProcesses { get { - if (_allProcesses is null) + if (_allProcesses == null) { List processes = new List(); processes.AddRange(Process.GetProcesses()); @@ -360,7 +360,7 @@ internal void WriteNonTerminatingError( string message = StringUtil.Format(resourceId, processName, processId, - (innerException is null) ? string.Empty : innerException.Message); + (innerException == null) ? string.Empty : innerException.Message); ProcessCommandException exception = new ProcessCommandException(message, innerException); exception.ProcessName = processName; @@ -1169,7 +1169,7 @@ public SwitchParameter PassThru /// protected override void ProcessRecord() { - if (myMode == MatchMode.All || (myMode == MatchMode.ByName && processNames is null)) + if (myMode == MatchMode.All || (myMode == MatchMode.ByName && processNames == null)) { Diagnostics.Assert(false, "trying to kill all processes"); throw PSTraceSource.NewInvalidOperationException(); @@ -1317,7 +1317,7 @@ private bool IsProcessOwnedByCurrentUser(Process process) { if (Win32Native.OpenProcessToken(process.Handle, TOKEN_QUERY, out ph)) { - if (_currentUserName is null) + if (_currentUserName == null) { using (var currentUser = WindowsIdentity.GetCurrent()) { @@ -1870,7 +1870,7 @@ protected override void BeginProcessing() // Linux relies on `xdg-open` and macOS relies on `open` which behave differently than Windows ShellExecute when running console commands // as a new console will be opened. So to avoid that, we only use ShellExecute on non-Windows if the filename is not an actual command (like a URI) - startInfo.UseShellExecute = (ArgumentList is null); + startInfo.UseShellExecute = (ArgumentList == null); #endif } @@ -2480,7 +2480,7 @@ private Process StartWithCreateProcess(ProcessStartInfo startinfo) IntPtr password = IntPtr.Zero; try { - password = (startinfo.Password is null) ? Marshal.StringToCoTaskMemUni(string.Empty) : Marshal.SecureStringToCoTaskMemUnicode(startinfo.Password); + password = (startinfo.Password == null) ? Marshal.StringToCoTaskMemUni(string.Empty) : Marshal.SecureStringToCoTaskMemUnicode(startinfo.Password); flag = ProcessNativeMethods.CreateProcessWithLogonW(startinfo.UserName, startinfo.Domain, password, logonFlags, null, cmdLine, creationFlags, AddressOfEnvironmentBlock, startinfo.WorkingDirectory, lpStartupInfo, lpProcessInformation); if (!flag) { @@ -3007,7 +3007,7 @@ public override void GetObjectData( { base.GetObjectData(info, context); - if (info is null) + if (info == null) throw new ArgumentNullException(nameof(info)); info.AddValue("ProcessName", _processName); diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs index 31fe60f93da..9e1d6c69c53 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs @@ -104,7 +104,7 @@ internal void WriteNonTerminatingError( string message = StringUtil.Format(errorMessage, serviceName, displayName, - (innerException is null) ? string.Empty : innerException.Message); + (innerException == null) ? string.Empty : innerException.Message); var exception = new ServiceCommandException(message, innerException); exception.ServiceName = serviceName; @@ -303,7 +303,7 @@ internal ServiceController[] AllServices { get { - if (_allServices is null) + if (_allServices == null) { _allServices = ServiceController.GetServices(); } @@ -383,7 +383,7 @@ private List MatchingServicesByServiceName() { List matchingServices = new List(); - if (serviceNames is null) + if (serviceNames == null) { foreach (ServiceController service in AllServices) { @@ -445,7 +445,7 @@ private List MatchingServicesByServiceName() private List MatchingServicesByDisplayName() { List matchingServices = new List(); - if (DisplayName is null) + if (DisplayName == null) { Diagnostics.Assert(false, "null DisplayName"); throw PSTraceSource.NewInvalidOperationException(); @@ -488,7 +488,7 @@ private List MatchingServicesByDisplayName() private List MatchingServicesByInput() { List matchingServices = new List(); - if (InputObject is null) + if (InputObject == null) { Diagnostics.Assert(false, "null InputObject"); throw PSTraceSource.NewInvalidOperationException(); @@ -545,7 +545,7 @@ private void IncludeExcludeAdd( /// private bool Matches(ServiceController service, string[] matchList) { - if (matchList is null) + if (matchList == null) throw PSTraceSource.NewArgumentNullException(nameof(matchList)); string serviceID = (selectionMode == SelectionMode.DisplayName) ? service.DisplayName @@ -914,7 +914,7 @@ internal bool DoStartService(ServiceController serviceController) catch (InvalidOperationException e) { Win32Exception eInner = e.InnerException as Win32Exception; - if (eInner is null + if (eInner == null || NativeMethods.ERROR_SERVICE_ALREADY_RUNNING != eInner.NativeErrorCode) { exception = e; @@ -1032,7 +1032,7 @@ internal List DoStopService(ServiceController serviceControll { Win32Exception eInner = e.InnerException as Win32Exception; - if (eInner is null + if (eInner == null || NativeMethods.ERROR_SERVICE_NOT_ACTIVE != eInner.NativeErrorCode) { exception = e; @@ -2563,7 +2563,7 @@ public ServiceCommandException(string message, Exception innerException) protected ServiceCommandException(SerializationInfo info, StreamingContext context) : base(info, context) { - if (info is null) + if (info == null) { throw new ArgumentNullException(nameof(info)); } @@ -2578,7 +2578,7 @@ protected ServiceCommandException(SerializationInfo info, StreamingContext conte [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) { throw new ArgumentNullException(nameof(info)); } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs index 29019bee06f..bcb7330c674 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs @@ -73,7 +73,7 @@ private void SetClipboardContent(List contentList, bool append) { string setClipboardShouldProcessTarget; - if ((contentList is null || contentList.Count == 0) && !append) + if ((contentList == null || contentList.Count == 0) && !append) { setClipboardShouldProcessTarget = string.Format(CultureInfo.InvariantCulture, ClipboardResources.ClipboardCleared); if (ShouldProcess(setClipboardShouldProcessTarget, "Set-Clipboard")) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetContentCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetContentCommand.cs index 6d17808ea19..4e040517b02 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetContentCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetContentCommand.cs @@ -26,7 +26,7 @@ public class SetContentCommand : WriteContentCommandBase /// internal override void BeforeOpenStreams(string[] paths) { - if (paths is null || paths.Length == 0) + if (paths == null || paths.Length == 0) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs index c21d73e25b4..c5d4f0395fa 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs @@ -244,7 +244,7 @@ protected override void BeginProcessing() /// protected override void ProcessRecord() { - if (TargetName is null) + if (TargetName == null) { return; } @@ -738,7 +738,7 @@ private bool TryResolveNameOrAddress( { targetAddress = GetHostAddress(hostEntry); - if (targetAddress is null) + if (targetAddress == null) { string message = StringUtil.Format( TestConnectionResources.NoPingResult, @@ -808,7 +808,7 @@ private byte[] GetSendBuffer(int bufferSize) sendBuffer[i] = (byte)((int)'a' + i % 23); } - if (bufferSize == DefaultSendBufferSize && s_DefaultSendBuffer is null) + if (bufferSize == DefaultSendBufferSize && s_DefaultSendBuffer == null) { s_DefaultSendBuffer = sendBuffer; } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/WriteContentCommandBase.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/WriteContentCommandBase.cs index 6045773b236..7ccf63cdf8e 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/WriteContentCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/WriteContentCommandBase.cs @@ -97,7 +97,7 @@ protected override void ProcessRecord() // Initialize the content - if (_content is null) + if (_content == null) { _content = Array.Empty(); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs index b81799eb6bc..2ea6d6e20ae 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs @@ -194,8 +194,8 @@ private static object GetParameterType(object sourceValue, Type destinationType) private void EnsureValue1AndValue2AreNotBothNull() { - if (_value1 is null && - (_value2 is null || !HasBeenSpecified(_value2))) + if (_value1 == null && + (_value2 == null || !HasBeenSpecified(_value2))) { ThrowTerminatingError(NewError("Value1AndValue2AreNotBothNull", "Value1AndValue2AreNotBothNull", null, _memberType)); } @@ -203,7 +203,7 @@ private void EnsureValue1AndValue2AreNotBothNull() private void EnsureValue1IsNotNull() { - if (_value1 is null) + if (_value1 == null) { ThrowTerminatingError(NewError("Value1ShouldNotBeNull", "Value1ShouldNotBeNull", null, _memberType)); } @@ -211,7 +211,7 @@ private void EnsureValue1IsNotNull() private void EnsureValue2IsNotNull() { - if (_value2 is null) + if (_value2 == null) { ThrowTerminatingError(NewError("Value2ShouldNotBeNull", "Value2ShouldNotBeNull", null, _memberType)); } @@ -288,7 +288,7 @@ private PSMemberInfo GetCodeProperty() private PSMemberInfo GetMemberSet() { EnsureValue2HasNotBeenSpecified(); - if (_value1 is null || !HasBeenSpecified(_value1)) + if (_value1 == null || !HasBeenSpecified(_value1)) { return new PSMemberSet(_memberName); } @@ -429,7 +429,7 @@ protected override void ProcessRecord() } } - if (member is null) + if (member == null) { return; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs index 008344e7366..4f7185a7e85 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs @@ -145,7 +145,7 @@ public string[] Path set { - if (value is null) + if (value == null) { _paths = null; return; @@ -192,7 +192,7 @@ public string[] LiteralPath set { - if (value is null) + if (value == null) { _paths = null; return; @@ -241,7 +241,7 @@ private void ProcessPaths(List resolvedPaths) break; } - if (activeExtension is null) + if (activeExtension == null) { activeExtension = currentExtension; } @@ -1259,7 +1259,7 @@ private string BuildErrorMessage(Diagnostic diagnisticRecord) { var location = diagnisticRecord.Location; - if (location.SourceTree is null) + if (location.SourceTree == null) { // For some error types (linker?) we don't have related source code. return diagnisticRecord.ToString(); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Compare-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Compare-Object.cs index 62276d857e4..5a1b944792d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Compare-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Compare-Object.cs @@ -264,7 +264,7 @@ private void InitComparer() _orderByProperty.OrderMatrix != null && _orderByProperty.OrderMatrix.Count == ReferenceObject.Length, "no OrderMatrix"); - if (_orderByProperty.Comparer is null || _orderByProperty.OrderMatrix is null || _orderByProperty.OrderMatrix.Count == 0) + if (_orderByProperty.Comparer == null || _orderByProperty.OrderMatrix == null || _orderByProperty.OrderMatrix.Count == 0) { return; } @@ -277,7 +277,7 @@ private OrderByPropertyEntry MatchAndRemove( OrderByPropertyEntry match, List list) { - if (match is null || list is null) + if (match == null || list == null) return null; Diagnostics.Assert(_comparer != null, "null comparer"); for (int i = 0; i < list.Count; i++) @@ -325,7 +325,7 @@ private void Emit(OrderByPropertyEntry entry, string sideIndicator) else { mshobj = new PSObject(); - if (Property is null || 0 == Property.Length) + if (Property == null || 0 == Property.Length) { PSNoteProperty inputNote = new PSNoteProperty( InputObjectPropertyName, entry.inputObject); @@ -395,18 +395,18 @@ protected override void BeginProcessing() /// protected override void ProcessRecord() { - if (ReferenceObject is null || ReferenceObject.Length == 0) + if (ReferenceObject == null || ReferenceObject.Length == 0) { HandleDifferenceObjectOnly(); return; } - else if (DifferenceObject is null || DifferenceObject.Length == 0) + else if (DifferenceObject == null || DifferenceObject.Length == 0) { HandleReferenceObjectOnly(); return; } - if (_comparer is null && 0 < DifferenceObject.Length) + if (_comparer == null && 0 < DifferenceObject.Length) { InitComparer(); } @@ -454,7 +454,7 @@ protected override void EndProcessing() private void HandleDifferenceObjectOnly() { - if (DifferenceObject is null || DifferenceObject.Length == 0) + if (DifferenceObject == null || DifferenceObject.Length == 0) { return; } @@ -474,7 +474,7 @@ private void HandleDifferenceObjectOnly() private void HandleReferenceObjectOnly() { - if (ReferenceObject is null || ReferenceObject.Length == 0) + if (ReferenceObject == null || ReferenceObject.Length == 0) { return; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs index d79677d6f54..1e64dfe7754 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs @@ -118,7 +118,7 @@ private Type GetRealAccessRightType(AccessRightTypeNames typeName) private string[] ConvertAccessControlListToStrings(CommonAcl acl, AccessRightTypeNames? typeName) { - if (acl is null || acl.Count == 0) + if (acl == null || acl.Count == 0) { return Array.Empty(); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFromMarkdownCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFromMarkdownCommand.cs index 316ba900334..dfa6bd6c4b0 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFromMarkdownCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFromMarkdownCommand.cs @@ -71,7 +71,7 @@ protected override void BeginProcessing() bool? supportsVT100 = this.Host?.UI.SupportsVirtualTerminal; - // supportsVT100 is null if the host is null. + // supportsVT100 == null if the host is null. // supportsVT100 == false if host does not support VT100. if (supportsVT100 != true) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs index 3a01d5f1e43..b0c3ff27f35 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs @@ -345,7 +345,7 @@ private List ProcessParameter(object[] properties) TerminatingErrorContext invocationContext = new TerminatingErrorContext(this); ParameterProcessor processor = new ParameterProcessor(new ConvertHTMLExpressionParameterDefinition()); - if (properties is null) + if (properties == null) { properties = new object[] { "*" }; } @@ -422,7 +422,7 @@ private static Hashtable CreateAuxPropertyHT( /// private static string SafeToString(object obj) { - if (obj is null) + if (obj == null) { return string.Empty; } @@ -689,7 +689,7 @@ protected override void ProcessRecord() // writes the table headers // it is not in BeginProcessing because the first inputObject is needed for // the number of columns and column name - if (_inputObject is null || _inputObject == AutomationNull.Value) + if (_inputObject == null || _inputObject == AutomationNull.Value) { return; } @@ -698,7 +698,7 @@ protected override void ProcessRecord() if (!_isTHWritten) { InitializeResolvedNameMshParameters(); - if (_resolvedNameMshParameters is null || _resolvedNameMshParameters.Count == 0) + if (_resolvedNameMshParameters == null || _resolvedNameMshParameters.Count == 0) { return; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs index ffb42452db2..0372298d7b5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs @@ -268,7 +268,7 @@ protected override void BeginProcessing() /// protected override void ProcessRecord() { - if (InputObject is null || _sw is null) + if (InputObject == null || _sw == null) { return; } @@ -279,7 +279,7 @@ protected override void ProcessRecord() } // Process first object - if (_propertyNames is null) + if (_propertyNames == null) { // figure out the column names (and lock-in their order) _propertyNames = ExportCsvHelper.BuildPropertyNames(InputObject, _propertyNames); @@ -334,7 +334,7 @@ protected override void EndProcessing() private void CreateFileStream() { - if (_path is null) + if (_path == null) { throw new InvalidOperationException(CsvCommandStrings.FileNameIsAMandatoryParameter); } @@ -430,7 +430,7 @@ private void ReconcilePreexistingPropertyNames() throw new InvalidOperationException(CsvCommandStrings.ReconcilePreexistingPropertyNamesMethodShouldOnlyGetCalledWhenAppending); } - if (_preexistingPropertyNames is null) + if (_preexistingPropertyNames == null) { throw new InvalidOperationException(CsvCommandStrings.ReconcilePreexistingPropertyNamesMethodShouldOnlyGetCalledWhenPreexistingPropertyNamesHaveBeenReadSuccessfully); } @@ -695,13 +695,13 @@ protected override void BeginProcessing() /// protected override void ProcessRecord() { - if (InputObject is null) + if (InputObject == null) { return; } // Process first object - if (_propertyNames is null) + if (_propertyNames == null) { _propertyNames = ExportCsvHelper.BuildPropertyNames(InputObject, _propertyNames); if (NoTypeInformation == false) @@ -823,12 +823,12 @@ protected override void ProcessRecord() this.ThrowTerminatingError(errorRecord); } - if ((Header is null) && (helper.Header != null)) + if ((Header == null) && (helper.Header != null)) { Header = helper.Header.ToArray(); } - if ((_typeName is null) && (helper.TypeName != null)) + if ((_typeName == null) && (helper.TypeName != null)) { _typeName = helper.TypeName; } @@ -867,7 +867,7 @@ internal ExportCsvHelper(char delimiter, BaseCsvWritingCommand.QuoteKind quoteKi { _delimiter = delimiter; _quoteKind = quoteKind; - _quoteFields = quoteFields is null ? null : new HashSet(quoteFields, StringComparer.OrdinalIgnoreCase); + _quoteFields = quoteFields == null ? null : new HashSet(quoteFields, StringComparer.OrdinalIgnoreCase); _outputString = new StringBuilder(128); } @@ -904,7 +904,7 @@ internal static IList BuildPropertyNames(PSObject source, IList /// Converted string. internal string ConvertPropertyNamesCSV(IList propertyNames) { - if (propertyNames is null) + if (propertyNames == null) { throw new ArgumentNullException(nameof(propertyNames)); } @@ -970,7 +970,7 @@ internal string ConvertPropertyNamesCSV(IList propertyNames) /// internal string ConvertPSObjectToCSV(PSObject mshObject, IList propertyNames) { - if (propertyNames is null) + if (propertyNames == null) { throw new ArgumentNullException(nameof(propertyNames)); } @@ -1044,7 +1044,7 @@ internal string ConvertPSObjectToCSV(PSObject mshObject, IList propertyN /// ToString() value. internal static string GetToStringValueForProperty(PSPropertyInfo property) { - if (property is null) + if (property == null) { throw new ArgumentNullException(nameof(property)); } @@ -1077,13 +1077,13 @@ internal static string GetTypeString(PSObject source) // get type of source Collection tnh = source.TypeNames; - if (tnh is null || tnh.Count == 0) + if (tnh == null || tnh.Count == 0) { type = "#TYPE"; } else { - if (tnh[0] is null) + if (tnh[0] == null) { throw new InvalidOperationException(CsvCommandStrings.TypeHierarchyShouldNotHaveNullValues); } @@ -1109,7 +1109,7 @@ internal static string GetTypeString(PSObject source) /// internal static void AppendStringWithEscapeAlways(StringBuilder dest, string source) { - if (source is null) + if (source == null) { return; } @@ -1209,12 +1209,12 @@ internal class ImportCsvHelper internal ImportCsvHelper(PSCmdlet cmdlet, char delimiter, IList header, string typeName, StreamReader streamReader) { - if (cmdlet is null) + if (cmdlet == null) { throw new ArgumentNullException(nameof(cmdlet)); } - if (streamReader is null) + if (streamReader == null) { throw new ArgumentNullException(nameof(streamReader)); } @@ -1274,14 +1274,14 @@ private bool PeekNextChar(char c) internal void ReadHeader() { // Read #Type record if available - if ((TypeName is null) && (!this.EOF)) + if ((TypeName == null) && (!this.EOF)) { TypeName = ReadTypeInformation(); } var values = new List(ValueCountGuestimate); var builder = new StringBuilder(LineLengthGuestimate); - while ((Header is null) && (!this.EOF)) + while ((Header == null) && (!this.EOF)) { ParseNextRecord(values, builder); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs index 91ec09a8034..465ef91f037 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs @@ -53,7 +53,7 @@ internal class CustomSerialization /// internal CustomSerialization(XmlWriter writer, bool notypeinformation, int depth) { - if (writer is null) + if (writer == null) { throw PSTraceSource.NewArgumentException(nameof(writer)); } @@ -271,7 +271,7 @@ internal void WriteOneObject(object source, string property, int depth) CheckIfStopping(); - if (source is null) + if (source == null) { WriteNull(property); return; @@ -711,7 +711,7 @@ private void WriteMemberInfoCollection( } PSPropertyInfo property = info as PSPropertyInfo; - if (property is null) + if (property == null) { continue; } @@ -773,7 +773,7 @@ private void WritePSObjectProperties(PSObject source, int depth) continue; } // Write the property - if (value is null) + if (value == null) { WritePropertyWithNullValue(_writer, prop, depth); } @@ -1014,7 +1014,7 @@ private static bool SerializeAsString(PSObject source) /// private static int GetDepthOfSerialization(PSObject source, int depth) { - if (source is null) + if (source == null) return depth; // get the depth from the PSObject diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs index 6ed5b66c8a1..355d94912af 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs @@ -156,7 +156,7 @@ protected override void EndProcessing() } } - if (_runspace is null) + if (_runspace == null) { ThrowTerminatingError( new ErrorRecord( @@ -168,7 +168,7 @@ protected override void EndProcessing() } Runspace defaultRunspace = LocalRunspace.DefaultRunspace; - if (defaultRunspace is null || defaultRunspace.Debugger is null) + if (defaultRunspace == null || defaultRunspace.Debugger == null) { ThrowTerminatingError( new ErrorRecord( @@ -190,7 +190,7 @@ protected override void EndProcessing() ); } - if (this.Host is null || this.Host.UI is null) + if (this.Host == null || this.Host.UI == null) { ThrowTerminatingError( new ErrorRecord( diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs index 3a33974abeb..c1294a08535 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs @@ -218,7 +218,7 @@ protected IReadOnlyList GetRunspaces() { IReadOnlyList results = null; - if ((ParameterSetName == CommonRunspaceCommandBase.RunspaceNameParameterSet) && ((RunspaceName is null) || RunspaceName.Length == 0)) + if ((ParameterSetName == CommonRunspaceCommandBase.RunspaceNameParameterSet) && ((RunspaceName == null) || RunspaceName.Length == 0)) { results = GetRunspaceUtils.GetAllRunspaces(); } @@ -261,7 +261,7 @@ protected System.Management.Automation.Debugger GetDebuggerFromRunspace(Runspace } catch (PSInvalidOperationException) { } - if (debugger is null) + if (debugger == null) { WriteError( new ErrorRecord( @@ -291,7 +291,7 @@ protected void SetDebugPreferenceHelper(string processName, string[] appDomainNa { if (!string.IsNullOrEmpty(currentAppDomainName)) { - if (appDomainNames is null) + if (appDomainNames == null) { appDomainNames = new List(); } @@ -381,7 +381,7 @@ protected override void ProcessRecord() } System.Management.Automation.Debugger debugger = GetDebuggerFromRunspace(runspace); - if (debugger is null) + if (debugger == null) { continue; } @@ -460,7 +460,7 @@ protected override void ProcessRecord() } System.Management.Automation.Debugger debugger = GetDebuggerFromRunspace(runspace); - if (debugger is null) + if (debugger == null) { continue; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs index 6b362465c8b..1ac3e781ab7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs @@ -59,7 +59,7 @@ public string LiteralPath set { - if (value is null) + if (value == null) { _path = "."; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ColumnInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ColumnInfo.cs index 92bb3b6ad19..0d2db93302a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ColumnInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ColumnInfo.cs @@ -49,7 +49,7 @@ internal Type GetValueType(PSObject liveObject, out object columnValue) internal static object LimitString(object src) { string srcString = src as string; - if (srcString is null) + if (srcString == null) { return src; } 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 296f2968063..a9d60def958 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 @@ -36,7 +36,7 @@ internal override object GetValue(PSObject liveObject) } object objectResult = result.Result; - return objectResult is null ? string.Empty : ColumnInfo.LimitString(objectResult.ToString()); + return objectResult == null ? string.Empty : ColumnInfo.LimitString(objectResult.ToString()); } } } 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 7e9315f3b95..48a9004e604 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 @@ -26,7 +26,7 @@ internal override object GetValue(PSObject liveObject) try { PSPropertyInfo propertyInfo = liveObject.Properties[_liveObjectPropertyName]; - if (propertyInfo is null) + if (propertyInfo == null) { return null; } 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 03318bae365..b95e9968c5c 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 @@ -136,7 +136,7 @@ protected override void EndProcessing() { base.EndProcessing(); - if (_windowProxy is null) + if (_windowProxy == null) { return; } @@ -154,13 +154,13 @@ protected override void EndProcessing() { foreach (PSObject selectedItem in selectedItems) { - if (selectedItem is null) + if (selectedItem == null) { continue; } PSPropertyInfo originalObjectProperty = selectedItem.Properties[OutWindowProxy.OriginalObjectPropertyName]; - if (originalObjectProperty is null) + if (originalObjectProperty == null) { return; } @@ -175,7 +175,7 @@ protected override void EndProcessing() /// protected override void ProcessRecord() { - if (InputObject is null || InputObject == AutomationNull.Value) + if (InputObject == null || InputObject == AutomationNull.Value) { return; } @@ -274,7 +274,7 @@ baseObject is FormatInfoData || this.ThrowTerminatingError(error); } - if (_gridHeader is null) + if (_gridHeader == null) { // Columns have not been added yet; Start the main window and add columns. _windowProxy.ShowWindow(); 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 e422f78ec35..55158034368 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 @@ -58,17 +58,17 @@ internal OutWindowProxy(string title, OutputModeOption outPutMode, OutGridViewCo /// An array of types to add. internal void AddColumns(string[] propertyNames, string[] displayNames, Type[] types) { - if (propertyNames is null) + if (propertyNames == null) { throw new ArgumentNullException(nameof(propertyNames)); } - if (displayNames is null) + if (displayNames == null) { throw new ArgumentNullException(nameof(displayNames)); } - if (types is null) + if (types == null) { throw new ArgumentNullException(nameof(types)); } @@ -177,12 +177,12 @@ private void AddExtraProperties(PSObject staleObject, PSObject liveObject) /// internal void AddItem(PSObject livePSObject) { - if (livePSObject is null) + if (livePSObject == null) { throw new ArgumentNullException(nameof(livePSObject)); } - if (_headerInfo is null) + if (_headerInfo == null) { throw new InvalidOperationException(); } @@ -203,12 +203,12 @@ internal void AddItem(PSObject livePSObject) /// internal void AddHeteroViewItem(PSObject livePSObject) { - if (livePSObject is null) + if (livePSObject == null) { throw new ArgumentNullException(nameof(livePSObject)); } - if (_headerInfo is null) + if (_headerInfo == null) { throw new InvalidOperationException(); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs index cac172ffae5..dc967889e69 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs @@ -72,7 +72,7 @@ internal HeaderInfo GenerateHeaderInfo(PSObject input, TableControlBody tableBod FieldPropertyToken fpt = token as FieldPropertyToken; if (fpt != null) { - if (displayName is null) + if (displayName == null) { // Database does not provide a label(DisplayName) for the current property, use the expression value instead. displayName = fpt.expression.expressionValue; @@ -170,7 +170,7 @@ internal HeaderInfo GenerateHeaderInfo(PSObject input, OutGridViewCommand parent propertyName = (string)key; } - if (propertyName is null) + if (propertyName == null) { propertyName = association.ResolvedExpression.ToString(); } @@ -233,12 +233,12 @@ private List GetActiveTableRowDefinition(TableControlBod } } - if (matchingRowDefinition is null) + if (matchingRowDefinition == null) { matchingRowDefinition = match.BestMatch as TableRowDefinition; } - if (matchingRowDefinition is null) + if (matchingRowDefinition == null) { Collection typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames); if (typesWithoutPrefix != null) @@ -254,14 +254,14 @@ private List GetActiveTableRowDefinition(TableControlBod } } - if (matchingRowDefinition is null) + if (matchingRowDefinition == null) { matchingRowDefinition = match.BestMatch as TableRowDefinition; } } } - if (matchingRowDefinition is null) + if (matchingRowDefinition == null) { // no matching override, use default return tableBody.defaultDefinition.rowItemDefinitionList; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs index b4e743c524e..70967aa897b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs @@ -42,7 +42,7 @@ public string[] TypeName { _typename = value; - if (_typename is null) + if (_typename == null) { _filter = Array.Empty(); } @@ -70,7 +70,7 @@ public string[] TypeName /// protected override void BeginProcessing() { - if (_filter[0] is null) + if (_filter[0] == null) { _filter[0] = WildcardPattern.Get("*", WildcardOptions.None); } @@ -105,7 +105,7 @@ protected override void ProcessRecord() // presumably because only the latter type deserializes type-faithfully. var clientVersion = PowerShellVersion; PSSenderInfo remotingClientInfo = GetVariableValue("PSSenderInfo") as PSSenderInfo; - if (clientVersion is null && remotingClientInfo != null) + if (clientVersion == null && remotingClientInfo != null) { clientVersion = PSObject.Base((PSObject.Base(remotingClientInfo.ApplicationArguments["PSVersionTable"]) as PSPrimitiveDictionary)?["PSVersion"]) as Version; } @@ -113,7 +113,7 @@ protected override void ProcessRecord() // During remoting, remain compatible with v5.0- clients by default. // Passing a -PowerShellVersion argument allows overriding the client version. bool writeOldWay = - (remotingClientInfo != null && clientVersion is null) // To be safe: Remoting client version could unexpectedly not be determined. + (remotingClientInfo != null && clientVersion == null) // To be safe: Remoting client version could unexpectedly not be determined. || (clientVersion != null && diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs index f1131e2e24e..f3f84c6da37 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs @@ -167,7 +167,7 @@ protected override void BeginProcessing() // cleanup code will be called in IDisposable.Dispose() outInner.LineOutput = InstantiateLineOutputInterface(); - if (_sw is null) + if (_sw == null) { return; } @@ -227,7 +227,7 @@ private LineOutput InstantiateLineOutputInterface() protected override void ProcessRecord() { _processRecordExecuted = true; - if (_sw is null) + if (_sw == null) { return; } @@ -254,7 +254,7 @@ protected override void EndProcessing() return; } - if (_sw is null) + if (_sw == null) { return; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs index 9d2c967e1d3..4f8903facfd 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs @@ -122,7 +122,7 @@ protected override void ProcessRecord() { CommandBreakpoint commandBreakpoint = breakpoint as CommandBreakpoint; - if (commandBreakpoint is null) + if (commandBreakpoint == null) { return false; } @@ -139,7 +139,7 @@ protected override void ProcessRecord() { VariableBreakpoint variableBreakpoint = breakpoint as VariableBreakpoint; - if (variableBreakpoint is null) + if (variableBreakpoint == null) { return false; } @@ -197,7 +197,7 @@ protected override void ProcessRecord() Script, delegate (Breakpoint breakpoint, string script) { - if (breakpoint.Script is null) + if (breakpoint.Script == null) { return false; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetAliasCommand.cs index cb3cef0bad4..49baa9bd296 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetAliasCommand.cs @@ -190,7 +190,7 @@ private void WriteMatches(string value, string parametersetname) this.WriteObject(alias); } - if (!matchfound && !ContainsWildcard && (excludePatterns is null || excludePatterns.Count == 0)) + if (!matchfound && !ContainsWildcard && (excludePatterns == null || excludePatterns.Count == 0)) { // Need to write an error if the user tries to get an alias // tat doesn't exist and they are not globbing. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs index d7492ced51b..daa870d9b1a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs @@ -139,7 +139,7 @@ public SwitchParameter Force /// protected override void ProcessRecord() { - if (this.InputObject is null || this.InputObject == AutomationNull.Value) + if (this.InputObject == null || this.InputObject == AutomationNull.Value) { return; } @@ -202,7 +202,7 @@ protected override void ProcessRecord() } if (((View & PSMemberViewTypes.Base) == PSMemberViewTypes.Base) && - (InputObject.InternalBaseDotNetAdapter is null)) + (InputObject.InternalBaseDotNetAdapter == null)) { // the input object don't have a custom adapter.. // for this case adapted view and base view are the same. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs index cad052a58e2..01cf6534c48 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs @@ -48,7 +48,7 @@ private MyParameterSet EffectiveParameterSet // cache MyParameterSet enum instead of doing string comparison every time if (_effectiveParameterSet == MyParameterSet.Unknown) { - if ((MyInvocation.ExpectingInput) && (Maximum is null) && (Minimum is null)) + if ((MyInvocation.ExpectingInput) && (Maximum == null) && (Minimum == null)) { _effectiveParameterSet = MyParameterSet.RandomListItem; } @@ -85,12 +85,12 @@ private MyParameterSet EffectiveParameterSet private void ThrowMinGreaterThanOrEqualMax(object minValue, object maxValue) { - if (minValue is null) + if (minValue == null) { throw PSTraceSource.NewArgumentNullException("min"); } - if (maxValue is null) + if (maxValue == null) { throw PSTraceSource.NewArgumentNullException("max"); } @@ -143,7 +143,7 @@ private PolymorphicRandomNumberGenerator Generator { get { - if (_generator is null) + if (_generator == null) { Guid runspaceId = Context.CurrentRunspace.InstanceId; @@ -219,7 +219,7 @@ private PolymorphicRandomNumberGenerator Generator private bool IsInt(object o) { - if (o is null || o is int) + if (o == null || o is int) { return true; } @@ -229,7 +229,7 @@ private bool IsInt(object o) private bool IsInt64(object o) { - if (o is null || o is Int64) + if (o == null || o is Int64) { return true; } @@ -239,7 +239,7 @@ private bool IsInt64(object o) private object ProcessOperand(object o) { - if (o is null) + if (o == null) { return null; } @@ -259,7 +259,7 @@ private object ProcessOperand(object o) private double ConvertToDouble(object o, double defaultIfNull) { - if (o is null) + if (o == null) { return defaultIfNull; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRunspaceCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRunspaceCommand.cs index d98e7a79740..0aedd4c9d06 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRunspaceCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRunspaceCommand.cs @@ -79,7 +79,7 @@ protected override void ProcessRecord() { IReadOnlyList results; - if ((ParameterSetName == GetRunspaceCommand.NameParameterSet) && ((Name is null) || Name.Length == 0)) + if ((ParameterSetName == GetRunspaceCommand.NameParameterSet) && ((Name == null) || Name.Length == 0)) { results = GetRunspaceUtils.GetAllRunspaces(); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUnique.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUnique.cs index a222a772779..ea33f7c28d7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUnique.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUnique.cs @@ -58,7 +58,7 @@ public SwitchParameter OnType protected override void ProcessRecord() { bool isUnique = true; - if (_lastObject is null) + if (_lastObject == null) { // always write first object, but return nothing // on "MSH> get-unique" @@ -72,7 +72,7 @@ protected override void ProcessRecord() else if (AsString) { string inputString = InputObject.ToString(); - if (_lastObjectAsString is null) + if (_lastObjectAsString == null) { _lastObjectAsString = _lastObject.ToString(); } @@ -91,7 +91,7 @@ protected override void ProcessRecord() } else // compare as objects { - if (_comparer is null) + if (_comparer == null) { _comparer = new ObjectCommandComparer( true, // ascending (doesn't matter) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Group-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Group-Object.cs index 70e8f7eb557..9938dc15c7f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Group-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Group-Object.cs @@ -393,7 +393,7 @@ protected override void ProcessRecord() if (!_hasProcessedFirstInputObject) { - if (Property is null) + if (Property == null) { Property = OrderByProperty.GetDefaultKeyPropertySet(InputObject); } @@ -442,7 +442,7 @@ protected override void ProcessRecord() private void UpdateOrderPropertyTypeInfo(List currentEntryOrderValues) { - if (_propertyTypesCandidate is null) + if (_propertyTypesCandidate == null) { _propertyTypesCandidate = currentEntryOrderValues.Select(c => PSObject.Base(c.PropertyValue)?.GetType()).ToArray(); return; @@ -461,7 +461,7 @@ private void UpdateOrderPropertyTypeInfo(List curren { var candidateType = _propertyTypesCandidate[i]; var propertyType = PSObject.Base(currentEntryOrderValues[i].PropertyValue)?.GetType(); - if (propertyType is null) + if (propertyType == null) { // we ignore properties without values. We can always compare against null. continue; @@ -470,7 +470,7 @@ private void UpdateOrderPropertyTypeInfo(List curren // if we haven't gotten a type for a property yet, update it when we do get a value if (propertyType != candidateType) { - if (candidateType is null) + if (candidateType == null) { _propertyTypesCandidate[i] = propertyType; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs index 8cf01d456cb..58d9d762ab7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs @@ -184,7 +184,7 @@ public sealed class ImportPSSessionCommand : ImplicitRemotingCommandBase private void RegisterModuleCleanUp(PSModuleInfo moduleInfo) { - if (moduleInfo is null) + if (moduleInfo == null) { throw PSTraceSource.NewArgumentNullException(nameof(moduleInfo)); } @@ -429,7 +429,7 @@ public string[] Module set { - if (value is null) + if (value == null) { value = Array.Empty(); } @@ -703,7 +703,7 @@ private ErrorRecord GetErrorFromRemoteCommand(string commandName, RuntimeExcepti throw PSTraceSource.NewArgumentNullException(nameof(commandName)); } - if (runtimeException is null) + if (runtimeException == null) { throw PSTraceSource.NewArgumentNullException(nameof(runtimeException)); } @@ -830,7 +830,7 @@ private Dictionary ExistingCommands { get { - if (_existingCommands is null) + if (_existingCommands == null) { _existingCommands = new Dictionary(StringComparer.OrdinalIgnoreCase); CommandSearcher searcher = new CommandSearcher( @@ -901,7 +901,7 @@ private List CommandSkipListFromServer get { // try to get the list from server's application private data - if (_commandSkipListFromServer is null) + if (_commandSkipListFromServer == null) { string[] serverDeclaredListOfCommandsToSkip; if (PSPrimitiveDictionary.TryPathGet( @@ -919,7 +919,7 @@ private List CommandSkipListFromServer } // fallback to the default list that hardcodes ... - if (_commandSkipListFromServer is null) + if (_commandSkipListFromServer == null) { _commandSkipListFromServer = new List(); @@ -977,7 +977,7 @@ private T ConvertTo(string commandName, object value) private T ConvertTo(string commandName, object value, bool nullOk) { - if (value is null) + if (value == null) { if (nullOk) { @@ -1006,7 +1006,7 @@ private T GetPropertyValue(string commandName, PSObject pso, string propertyN private T GetPropertyValue(string commandName, PSObject pso, string propertyName, bool nullOk) { PSPropertyInfo property = pso.Properties[propertyName]; - if (property is null) + if (property == null) { this.ThrowTerminatingError(this.GetErrorMalformedDataFromRemoteCommand(commandName)); } @@ -1030,7 +1030,7 @@ private List RehydrateList(string commandName, PSObject deserializedObject private List RehydrateList(string commandName, object deserializedList, Func itemRehydrator) { - if (itemRehydrator is null) + if (itemRehydrator == null) { itemRehydrator = delegate (PSObject pso) { return ConvertTo(commandName, pso); }; } @@ -1057,7 +1057,7 @@ private Dictionary RehydrateDictionary(string commandName, PSObject Dbg.Assert(deserializedObject != null, "deserializedObject parameter != null"); Dbg.Assert(!string.IsNullOrEmpty(propertyName), "propertyName parameter != null"); - if (valueRehydrator is null) + if (valueRehydrator == null) { valueRehydrator = delegate (PSObject pso) { return ConvertTo(commandName, pso); }; } @@ -1125,7 +1125,7 @@ private static bool IsSafeParameterName(string parameterName) /// true if the type is safe; false otherwise. private static bool IsSafeTypeConstraint(Type type) { - if (type is null) + if (type == null) { return true; // no type constraint => safe } @@ -1190,14 +1190,14 @@ private bool IsSafeCommandMetadata(CommandMetadata commandMetadata) return false; } - Dbg.Assert(commandMetadata.CommandType is null, "CommandType shouldn't get rehydrated"); + Dbg.Assert(commandMetadata.CommandType == null, "CommandType shouldn't get rehydrated"); Dbg.Assert(commandMetadata.ImplementsDynamicParameters == false, "Proxies shouldn't do dynamic parameters"); if (commandMetadata.Parameters != null) { foreach (ParameterMetadata parameter in commandMetadata.Parameters.Values) { - Dbg.Assert(parameter.Attributes is null || parameter.Attributes.Count == 0, + Dbg.Assert(parameter.Attributes == null || parameter.Attributes.Count == 0, "Attributes shouldn't get rehydrated"); // sanitize - remove type constraint that are not allowed @@ -1269,7 +1269,7 @@ private Type RehydrateParameterType(PSObject deserializedParameterMetadata) private ParameterMetadata RehydrateParameterMetadata(PSObject deserializedParameterMetadata) { - if (deserializedParameterMetadata is null) + if (deserializedParameterMetadata == null) { throw PSTraceSource.NewArgumentNullException(nameof(deserializedParameterMetadata)); } @@ -1285,7 +1285,7 @@ private ParameterMetadata RehydrateParameterMetadata(PSObject deserializedParame parameterSets.Add(ParameterAttribute.AllParameterSets, parameterSetMetadata); return new ParameterMetadata( - aliases is null ? new Collection() : new Collection(aliases), + aliases == null ? new Collection() : new Collection(aliases), isDynamic, name, parameterSets, @@ -1310,7 +1310,7 @@ private bool IsProxyForCmdlet(Dictionary parameters) private CommandMetadata RehydrateCommandMetadata(PSObject deserializedCommandInfo, out string resolvedCommandName) { - if (deserializedCommandInfo is null) + if (deserializedCommandInfo == null) { throw PSTraceSource.NewArgumentNullException(nameof(deserializedCommandInfo)); } @@ -1494,14 +1494,14 @@ private int CountRemoteObjects(PowerShell powerShell) measurements = powerShell.Invoke(); } - if ((measurements is null) || (measurements.Count != 1)) + if ((measurements == null) || (measurements.Count != 1)) { _assumeMeasureObjectIsAvailable = false; return -1; } PSPropertyInfo countProperty = measurements[0].Properties["Count"]; - if (countProperty is null) + if (countProperty == null) { _assumeMeasureObjectIsAvailable = false; return -1; @@ -1584,7 +1584,7 @@ private PowerShell BuildPowerShellForGetFormatData() /// (rehydrated) CommandMetadata objects. internal List GetRemoteFormatData() { - if ((this.FormatTypeName is null) || (this.FormatTypeName.Length == 0) || + if ((this.FormatTypeName == null) || (this.FormatTypeName.Length == 0) || (_commandParameterSpecified && !_formatTypeNamesSpecified)) { return new List(); @@ -1691,7 +1691,7 @@ internal List GetRemoteCommandMetadata(out Dictionary(StringComparer.OrdinalIgnoreCase); - if ((this.CommandName is null) || (this.CommandName.Length == 0) || + if ((this.CommandName == null) || (this.CommandName.Length == 0) || (!_commandParameterSpecified && _formatTypeNamesSpecified)) { return new List(); @@ -1963,7 +1963,7 @@ private string GetConnectionString() private string EscapeFunctionNameForRemoteHelp(string name) { - if (name is null) + if (name == null) { throw PSTraceSource.NewArgumentNullException(nameof(name)); } @@ -2013,7 +2013,7 @@ private void GenerateSectionSeparator(TextWriter writer) private void GenerateManifest(TextWriter writer, string psm1fileName, string formatPs1xmlFileName) { - if (writer is null) + if (writer == null) { throw PSTraceSource.NewArgumentNullException(nameof(writer)); } @@ -2086,7 +2086,7 @@ private void GenerateTopComment(TextWriter writer) private void GenerateModuleHeader(TextWriter writer) { - if (writer is null) + if (writer == null) { throw PSTraceSource.NewArgumentNullException(nameof(writer)); } @@ -2123,7 +2123,7 @@ function Write-PSImplicitRemotingMessage private void GenerateHelperFunctionsWriteMessage(TextWriter writer) { - if (writer is null) + if (writer == null) { throw PSTraceSource.NewArgumentNullException(nameof(writer)); } @@ -2178,7 +2178,7 @@ function Set-PSImplicitRemotingSession private void GenerateHelperFunctionsSetImplicitRunspace(TextWriter writer) { - if (writer is null) + if (writer == null) { throw PSTraceSource.NewArgumentNullException(nameof(writer)); } @@ -2210,7 +2210,7 @@ function Get-PSImplicitRemotingSessionOption private void GenerateHelperFunctionsGetSessionOption(TextWriter writer) { - if (writer is null) + if (writer == null) { throw PSTraceSource.NewArgumentNullException(nameof(writer)); } @@ -2318,7 +2318,7 @@ private string GenerateNewPSSessionOption() private string GenerateProxyCredentialParameter(WSManConnectionInfo wsmanConnectionInfo) { - if ((wsmanConnectionInfo is null) || (wsmanConnectionInfo.ProxyCredential is null)) + if ((wsmanConnectionInfo == null) || (wsmanConnectionInfo.ProxyCredential == null)) { return string.Empty; } @@ -2405,7 +2405,7 @@ function Get-PSImplicitRemotingSession private void GenerateHelperFunctionsGetImplicitRunspace(TextWriter writer) { - if (writer is null) + if (writer == null) { throw PSTraceSource.NewArgumentNullException(nameof(writer)); } @@ -2564,7 +2564,7 @@ private string GenerateNewRunspaceExpression() private string GenerateConnectionStringForNewRunspace() { WSManConnectionInfo connectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as WSManConnectionInfo; - if (connectionInfo is null) + if (connectionInfo == null) { VMConnectionInfo vmConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as VMConnectionInfo; if (vmConnectionInfo != null) @@ -2610,7 +2610,7 @@ private string GenerateConnectionStringForNewRunspace() private string GenerateAllowRedirectionParameter() { WSManConnectionInfo wsmanConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as WSManConnectionInfo; - if (wsmanConnectionInfo is null) + if (wsmanConnectionInfo == null) { return string.Empty; } @@ -2637,7 +2637,7 @@ private string GenerateAuthenticationMechanismParameter() } WSManConnectionInfo wsmanConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as WSManConnectionInfo; - if (wsmanConnectionInfo is null) + if (wsmanConnectionInfo == null) { return string.Empty; } @@ -2657,7 +2657,7 @@ private string GenerateAuthenticationMechanismParameter() private string GenerateCredentialParameter() { - if (_remoteRunspaceInfo.Runspace.ConnectionInfo.Credential is null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo.Credential == null) { return string.Empty; } @@ -2677,7 +2677,7 @@ private string GenerateCredentialParameter() private string GenerateCertificateThumbprintParameter() { - if (_remoteRunspaceInfo.Runspace.ConnectionInfo.CertificateThumbprint is null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo.CertificateThumbprint == null) { return string.Empty; } @@ -2757,7 +2757,7 @@ function Get-PSImplicitRemotingClientSideParameters private void GenerateHelperFunctionsClientSideParameters(TextWriter writer) { - if (writer is null) + if (writer == null) { throw PSTraceSource.NewArgumentNullException(nameof(writer)); } @@ -2836,7 +2836,7 @@ private void GenerateHelperFunctions(TextWriter writer) private void GenerateCommandProxy(TextWriter writer, CommandMetadata commandMetadata) { - if (writer is null) + if (writer == null) { throw PSTraceSource.NewArgumentNullException(nameof(writer)); } @@ -2858,12 +2858,12 @@ private void GenerateCommandProxy(TextWriter writer, CommandMetadata commandMeta private void GenerateCommandProxy(TextWriter writer, IEnumerable listOfCommandMetadata) { - if (writer is null) + if (writer == null) { throw PSTraceSource.NewArgumentNullException(nameof(writer)); } - if (listOfCommandMetadata is null) + if (listOfCommandMetadata == null) { throw PSTraceSource.NewArgumentNullException(nameof(listOfCommandMetadata)); } @@ -2885,12 +2885,12 @@ private void GenerateCommandProxy(TextWriter writer, IEnumerable listOfCommandMetadata) { - if (writer is null) + if (writer == null) { throw PSTraceSource.NewArgumentNullException(nameof(writer)); } - if (listOfCommandMetadata is null) + if (listOfCommandMetadata == null) { throw PSTraceSource.NewArgumentNullException(nameof(listOfCommandMetadata)); } @@ -2904,7 +2904,7 @@ private void GenerateExportDeclaration(TextWriter writer, IEnumerable GetListOfCommandNames(IEnumerable listOfCommandMetadata) { - if (listOfCommandMetadata is null) + if (listOfCommandMetadata == null) { throw PSTraceSource.NewArgumentNullException(nameof(listOfCommandMetadata)); } @@ -2920,7 +2920,7 @@ private List GetListOfCommandNames(IEnumerable listOfCo private string GenerateArrayString(IEnumerable listOfStrings) { - if (listOfStrings is null) + if (listOfStrings == null) { throw PSTraceSource.NewArgumentNullException(nameof(listOfStrings)); } @@ -2981,12 +2981,12 @@ private void GenerateAliases(TextWriter writer, Dictionary alias private void GenerateFormatFile(TextWriter writer, List listOfFormatData) { - if (writer is null) + if (writer == null) { throw PSTraceSource.NewArgumentNullException(nameof(writer)); } - if (listOfFormatData is null) + if (listOfFormatData == null) { throw PSTraceSource.NewArgumentNullException(nameof(listOfFormatData)); } @@ -3043,7 +3043,7 @@ internal List GenerateProxyModule( FileShare.None); using (TextWriter writer = new StreamWriter(psm1, encoding)) { - if (listOfCommandMetadata is null) + if (listOfCommandMetadata == null) { listOfCommandMetadata = new List(); } @@ -3064,7 +3064,7 @@ internal List GenerateProxyModule( FileShare.None); using (TextWriter writer = new StreamWriter(formatPs1xml, encoding)) { - if (listOfFormatData is null) + if (listOfFormatData == null) { listOfFormatData = new List(); } @@ -3079,7 +3079,7 @@ internal List GenerateProxyModule( ExecutionPolicy executionPolicy = SecuritySupport.GetExecutionPolicy(Utils.DefaultPowerShellShellID); if (executionPolicy == ExecutionPolicy.Restricted || executionPolicy == ExecutionPolicy.AllSigned) { - if (certificate is null) + if (certificate == null) { string message = ImplicitRemotingStrings.CertificateNeeded; throw new PSInvalidOperationException(message); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs index ef46d22c717..4749d28322c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs @@ -130,7 +130,7 @@ protected override void ProcessRecord() { string path = GetFilePath(); - if (path is null) + if (path == null) { return; } @@ -159,7 +159,7 @@ protected override void ProcessRecord() } string script = GetScript(path); - if (script is null) + if (script == null) { return; } @@ -204,7 +204,7 @@ protected override void ProcessRecord() SessionStateScope scope = null; PSVariable variable = SessionState.Internal.GetVariableItem(variablePath, out scope); - if (variable is null) + if (variable == null) { variable = new PSVariable(variablePath.UnqualifiedPath, result, ScopedItemOptions.None); Context.EngineSessionState.SetVariable(variablePath, variable, false, CommandOrigin.Internal); @@ -245,7 +245,7 @@ private string GetFilePath() { if (string.IsNullOrEmpty(_fileName)) { - if (InvocationExtent is null || string.IsNullOrEmpty(InvocationExtent.File)) + if (InvocationExtent == null || string.IsNullOrEmpty(InvocationExtent.File)) { throw PSTraceSource.NewInvalidOperationException(ImportLocalizedDataStrings.NotCalledFromAScriptFile); } @@ -283,7 +283,7 @@ private string GetFilePath() fileName = Path.GetFileNameWithoutExtension(fileName); CultureInfo culture = null; - if (_uiculture is null) + if (_uiculture == null) { culture = CultureInfo.CurrentUICulture; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs index 83b47dda771..3da62e88d25 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs @@ -230,7 +230,7 @@ private Dictionary ExistingCommands { get { - if (_existingCommands is null) + if (_existingCommands == null) { _existingCommands = new Dictionary(StringComparer.OrdinalIgnoreCase); CommandSearcher searcher = new CommandSearcher( diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Join-String.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Join-String.cs index 152a64f6e37..652e32652ce 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Join-String.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Join-String.cs @@ -113,7 +113,7 @@ protected override void ProcessRecord() { if (inputObject != null && inputObject != AutomationNull.Value) { - var inputValue = Property is null + var inputValue = Property == null ? inputObject : Property.GetValues(inputObject, false, true).FirstOrDefault()?.Result; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MarkdownOptionCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MarkdownOptionCommands.cs index 9182060a6ae..0ee80712123 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MarkdownOptionCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MarkdownOptionCommands.cs @@ -155,7 +155,7 @@ protected override void EndProcessing() object baseObj = InputObject.BaseObject; mdOptionInfo = baseObj as PSMarkdownOptionInfo; - if (mdOptionInfo is null) + if (mdOptionInfo == null) { var errorMessage = StringUtil.Format(ConvertMarkdownStrings.InvalidInputObjectType, baseObj.GetType()); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs index 17147af4c6d..3a5d4c77a5f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs @@ -269,7 +269,7 @@ private string ToString(string directory, string line) // Just return a single line if the user didn't // enable context-tracking. - if (Context is null) + if (Context == null) { return FormatLine(line, this.LineNumber, displayPath, EmptyPrefix); } @@ -532,7 +532,7 @@ public bool Contains(T item) public void CopyTo(T[] array, int arrayIndex) { - if (array is null) + if (array == null) { throw new ArgumentNullException(nameof(array)); } @@ -1478,7 +1478,7 @@ protected override void ProcessRecord() if (Path != null) { expandedPaths = ResolveFilePaths(Path, _isLiteralPath); - if (expandedPaths is null) + if (expandedPaths == null) { return; } @@ -1539,7 +1539,7 @@ protected override void ProcessRecord() if (matched) { // Don't re-write the line number if it was already set... - if (matchInfo is null) + if (matchInfo == null) { result.LineNumber = _inputRecordNumber; } 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 8e488e38c3a..67a9e43c3b9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs @@ -478,14 +478,14 @@ protected override void BeginProcessing() /// protected override void ProcessRecord() { - if (InputObject is null || InputObject == AutomationNull.Value) + if (InputObject == null || InputObject == AutomationNull.Value) { return; } _totalRecordCount++; - if (Property is null) + if (Property == null) AnalyzeValue(null, InputObject.BaseObject); else AnalyzeObjectProperties(InputObject); @@ -509,7 +509,7 @@ private void AnalyzeObjectProperties(PSObject inObj) foreach (var expression in Property) { List resolvedNames = expression.ResolveNames(inObj); - if (resolvedNames is null || resolvedNames.Count == 0) + if (resolvedNames == null || resolvedNames.Count == 0) { // Insert a blank entry so we can track // property misses in EndProcessing. @@ -535,7 +535,7 @@ private void AnalyzeObjectProperties(PSObject inObj) } List tempExprRes = resolvedName.GetValues(inObj); - if (tempExprRes is null || tempExprRes.Count == 0) + if (tempExprRes == null || tempExprRes.Count == 0) { // Shouldn't happen - would somehow mean // that the property went away between when @@ -560,7 +560,7 @@ private void AnalyzeObjectProperties(PSObject inObj) /// private void AnalyzeValue(string propertyName, object objValue) { - if (propertyName is null) + if (propertyName == null) propertyName = thisObject; Statistics stat = _statistics.EnsureEntry(propertyName); @@ -570,7 +570,7 @@ private void AnalyzeValue(string propertyName, object objValue) if (_measureCharacters || _measureWords || _measureLines) { - string strValue = (objValue is null) ? string.Empty : objValue.ToString(); + string strValue = (objValue == null) ? string.Empty : objValue.ToString(); AnalyzeString(strValue, stat); } @@ -634,7 +634,7 @@ private object Compare(object objValue, object statMinOrMaxValue, bool isMin) statValue = PSObject.AsPSObject(statValue).ToString(); } - if ((statValue is null) || + if ((statValue == null) || ((LanguagePrimitives.Compare(statValue, currentValue, false, CultureInfo.CurrentCulture) * factor) > 0)) { return objValue; @@ -808,7 +808,7 @@ protected override void EndProcessing() // Fix for 917114: If Property is not set, // and we aren't passed any records at all, // output 0s to emulate wc behavior. - if (_totalRecordCount == 0 && Property is null) + if (_totalRecordCount == 0 && Property == null) { _statistics.EnsureEntry(thisObject); } @@ -828,8 +828,8 @@ protected override void EndProcessing() if (IsMeasuringGeneric) { double temp; - if ((stat.min is null || LanguagePrimitives.TryConvertTo(stat.min, out temp)) && - (stat.max is null || LanguagePrimitives.TryConvertTo(stat.max, out temp))) + if ((stat.min == null || LanguagePrimitives.TryConvertTo(stat.min, out temp)) && + (stat.max == null || LanguagePrimitives.TryConvertTo(stat.max, out temp))) { mi = CreateGenericMeasureInfo(stat, true); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs index 984281c4d70..39fd390b1ce 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs @@ -202,7 +202,7 @@ protected override void BeginProcessing() "CannotInstantiateWinRTType", ErrorCategory.InvalidOperation, null)); } - if (ArgumentList is null || ArgumentList.Length == 0) + if (ArgumentList == null || ArgumentList.Length == 0) { ConstructorInfo ci = type.GetConstructor(Type.EmptyTypes); if (ci != null && ci.IsPublic) @@ -413,7 +413,7 @@ private void STAComCreateThreadProc(object createstruct) PSArgumentException mshArgE = null; type = Type.GetTypeFromCLSID(_comObjectClsId); - if (type is null) + if (type == null) { mshArgE = PSTraceSource.NewArgumentException( "ComObject", @@ -443,7 +443,7 @@ private object CreateComObject() try { type = Marshal.GetTypeFromCLSID(_comObjectClsId); - if (type is null) + if (type == null) { mshArgE = PSTraceSource.NewArgumentException("ComObject", NewObjectStrings.CannotLoadComObjectType, ComObject); ThrowTerminatingError( diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs index c782bef104e..fd69a2011fb 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs @@ -78,7 +78,7 @@ internal CultureInfo Culture public override bool Equals(object inputObject) { ObjectCommandPropertyValue objectCommandPropertyValueObject = inputObject as ObjectCommandPropertyValue; - if (objectCommandPropertyValueObject is null) + if (objectCommandPropertyValueObject == null) { return false; } @@ -92,7 +92,7 @@ public override bool Equals(object inputObject) return success && result == 0; } - if (baseObject is null && inComingbaseObjectPropertyValue is null) + if (baseObject == null && inComingbaseObjectPropertyValue == null) { return true; } @@ -112,13 +112,13 @@ public override bool Equals(object inputObject) /// Hashcode in the form of an integer. public override int GetHashCode() { - if (PropertyValue is null) + if (PropertyValue == null) { return 0; } object baseObject = PSObject.Base(PropertyValue); - if (baseObject is null) + if (baseObject == null) { return 0; } @@ -154,7 +154,7 @@ internal ObjectCommandComparer(bool ascending, CultureInfo cultureInfo, bool cas private static bool IsValueNull(object value) { object val = PSObject.Base(value); - return (val is null); + return (val == null); } internal int Compare(ObjectCommandPropertyValue first, ObjectCommandPropertyValue second) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs index 258cf507091..c2ebc9261a1 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs @@ -217,7 +217,7 @@ private static void ProcessExpressionParameter( new ParameterProcessor(new SortObjectExpressionParameterDefinition()) : new ParameterProcessor(new GroupObjectExpressionParameterDefinition()); - if (expr is null && inputObjects != null && inputObjects.Count > 0) + if (expr == null && inputObjects != null && inputObjects.Count > 0) { expr = GetDefaultKeyPropertySet(inputObjects[0]); } @@ -243,7 +243,7 @@ internal void ProcessExpressionParameter( if (expr != null) { - if (_unexpandedParameterList is null) + if (_unexpandedParameterList == null) { _unexpandedParameterList = processor.ProcessParameters(expr, invocationContext); @@ -256,7 +256,7 @@ internal void ProcessExpressionParameter( } else { - if (_unExpandedParametersWithWildCardPattern is null) + if (_unExpandedParametersWithWildCardPattern == null) { _unExpandedParametersWithWildCardPattern = new List(); } @@ -290,7 +290,7 @@ private static List ExpandExpressions(List inputObjects, { foreach (object inputObject in inputObjects) { - if (inputObject is null) + if (inputObject == null) { continue; } @@ -328,7 +328,7 @@ private static void ExpandExpressions(PSObject inputObject, List U PSPropertyExpression ex = (PSPropertyExpression)unexpandedParameter.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey); SortedDictionary expandedPropertyNames = new SortedDictionary(StringComparer.OrdinalIgnoreCase); - if (inputObject is null) + if (inputObject == null) { continue; } @@ -353,14 +353,14 @@ private static void ExpandExpressions(PSObject inputObject, List U internal static string[] GetDefaultKeyPropertySet(PSObject mshObj) { PSMemberSet standardNames = mshObj.PSStandardMembers; - if (standardNames is null) + if (standardNames == null) { return null; } PSPropertySet defaultKeys = standardNames.Members["DefaultKeyPropertySet"] as PSPropertySet; - if (defaultKeys is null) + if (defaultKeys == null) { return null; } @@ -382,7 +382,7 @@ List mshParameterList for (int index = 0; index < inputObjects.Count; index++) { PSObject so = inputObjects[index]; - if (so is null || so == AutomationNull.Value) + if (so == null || so == AutomationNull.Value) continue; List evaluationErrors = new List(); List propertyNotFoundMsgs = new List(); @@ -416,7 +416,7 @@ private static OrderByPropertyComparer CreateComparer( CultureInfo cultureInfo, bool caseSensitive) { - if (orderMatrix is null || orderMatrix.Count == 0) + if (orderMatrix == null || orderMatrix.Count == 0) { return null; } @@ -549,7 +549,7 @@ internal static OrderByPropertyEntry ProcessObject(PSObject inputObject, List protected override void BeginProcessing() { - if (Runspace is null) + if (Runspace == null) { Runspace = Context.CurrentRunspace; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/PSBreakpointUpdaterCommandBase.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/PSBreakpointUpdaterCommandBase.cs index 2aeb38b499c..0b1452b0709 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/PSBreakpointUpdaterCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/PSBreakpointUpdaterCommandBase.cs @@ -99,7 +99,7 @@ private bool TryGetRunspace(Breakpoint breakpoint) // Breakpoints retrieved from another runspace will have a RunspaceId note property of type Guid on them. var pso = new PSObject(breakpoint); var runspaceInstanceIdProperty = pso.Properties[RemotingConstants.RunspaceIdNoteProperty]; - if (runspaceInstanceIdProperty is null) + if (runspaceInstanceIdProperty == null) { Runspace = Context.CurrentRunspace; return true; @@ -134,7 +134,7 @@ private bool TryGetBreakpoint(int id, out Breakpoint breakpoint) { breakpoint = Runspace.Debugger.GetBreakpoint(id); - if (breakpoint is null) + if (breakpoint == null) { WriteError( new ErrorRecord( diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterPSEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterPSEventCommand.cs index ea221096f72..f04124e9a4c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterPSEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterPSEventCommand.cs @@ -38,7 +38,7 @@ protected override object GetSourceObject() // If it's not a forwarded event, the user must specify // an action if ( - (Action is null) && + (Action == null) && (!(bool)Forward) ) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RunspaceAttribute.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RunspaceAttribute.cs index 79406814685..696813449cb 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RunspaceAttribute.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RunspaceAttribute.cs @@ -31,12 +31,12 @@ public sealed class RunspaceAttribute : ArgumentTransformationAttribute /// A runspace object representing the inputData. public override object Transform(EngineIntrinsics engineIntrinsics, object inputData) { - if (engineIntrinsics?.Host?.UI is null) + if (engineIntrinsics?.Host?.UI == null) { throw PSTraceSource.NewArgumentNullException("engineIntrinsics"); } - if (inputData is null) + if (inputData == null) { return 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 51a6c8f04fc..bba2ac2873d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs @@ -23,7 +23,7 @@ internal sealed class PSPropertyExpressionFilter /// Array of pattern strings to use. internal PSPropertyExpressionFilter(string[] wildcardPatternsStrings) { - if (wildcardPatternsStrings is null) + if (wildcardPatternsStrings == null) { throw new ArgumentNullException(nameof(wildcardPatternsStrings)); } @@ -361,7 +361,7 @@ private void ProcessExpressionParameter() { _exclusionFilter = new PSPropertyExpressionFilter(ExcludeProperty); // ExcludeProperty implies -Property * for better UX - if ((Property is null) || (Property.Length == 0)) + if ((Property == null) || (Property.Length == 0)) { Property = new object[] { "*" }; _propertyMshParameterList = processor.ProcessParameters(Property, invocationContext); @@ -371,7 +371,7 @@ private void ProcessExpressionParameter() private void ProcessObject(PSObject inputObject) { - if ((Property is null || Property.Length == 0) && string.IsNullOrEmpty(ExpandProperty)) + if ((Property == null || Property.Length == 0) && string.IsNullOrEmpty(ExpandProperty)) { FilteredWriteObject(inputObject, new List()); return; @@ -430,10 +430,10 @@ private void ProcessParameter(MshParameter p, PSObject inputObject, List expressionResults = new List(); foreach (PSPropertyExpression resolvedName in ex.ResolveNames(inputObject)) { - if (_exclusionFilter is null || !_exclusionFilter.IsMatch(resolvedName)) + if (_exclusionFilter == null || !_exclusionFilter.IsMatch(resolvedName)) { List tempExprResults = resolvedName.GetValues(inputObject); - if (tempExprResults is null) continue; + if (tempExprResults == null) continue; foreach (PSPropertyExpressionResult mshExpRes in tempExprResults) { expressionResults.Add(mshExpRes); @@ -521,13 +521,13 @@ private void ProcessExpandParameter(MshParameter p, PSObject inputObject, } PSPropertyExpressionResult r = expressionResults[0]; - if (r.Exception is null) + if (r.Exception == null) { // ignore the property value if it's null - if (r.Result is null) { return; } + if (r.Result == null) { return; } System.Collections.IEnumerable results = LanguagePrimitives.GetEnumerable(r.Result); - if (results is null) + if (results == null) { // add NoteProperties if there is any // If r.Result is a base object, we don't want to associate the NoteProperty @@ -544,7 +544,7 @@ private void ProcessExpandParameter(MshParameter p, PSObject inputObject, foreach (object expandedValue in results) { // ignore the element if it's null - if (expandedValue is null) { continue; } + if (expandedValue == null) { continue; } // add NoteProperties if there is any // If expandedValue is a base object, we don't want to associate the NoteProperty @@ -628,7 +628,7 @@ private void FilteredWriteObject(PSObject obj, List addedNotePro foreach (PSNoteProperty note in addedNoteProperties) { PSMemberInfo prop = uniqueObj.WrittenObject.Properties[note.Name]; - if (prop is null || comparer.Compare(prop.Value, note.Value) != 0) + if (prop == null || comparer.Compare(prop.Value, note.Value) != 0) { found = false; break; @@ -826,7 +826,7 @@ protected override void EndProcessing() { foreach (UniquePSObjectHelper obj in _uniques) { - if (obj.WrittenObject is null || obj.WrittenObject == AutomationNull.Value) + if (obj.WrittenObject == null || obj.WrittenObject == AutomationNull.Value) { continue; } 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 17086561ce2..78e65d806a3 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs @@ -273,7 +273,7 @@ protected override void BeginProcessing() // globalEmailServer might be null if it is deleted by: PS> del variable:PSEmailServer PSVariable globalEmailServer = SessionState.Internal.GetVariable(SpecialVariables.PSEmailServer); - if (SmtpServer is null && globalEmailServer != null) + if (SmtpServer == null && globalEmailServer != null) { SmtpServer = Convert.ToString(globalEmailServer.Value, CultureInfo.InvariantCulture); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Set-PSBreakpoint.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Set-PSBreakpoint.cs index c8d9d77ec11..e628da48244 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Set-PSBreakpoint.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Set-PSBreakpoint.cs @@ -87,7 +87,7 @@ protected override void BeginProcessing() // Check whether we are executing on a remote session and if so // whether the RemoteScript debug option is selected. if (this.Context.InternalHost.ExternalHost is System.Management.Automation.Remoting.ServerRemoteHost && - ((this.Context.CurrentRunspace is null) || (this.Context.CurrentRunspace.Debugger is null) || + ((this.Context.CurrentRunspace == null) || (this.Context.CurrentRunspace.Debugger == null) || ((this.Context.CurrentRunspace.Debugger.DebugMode & DebugModes.RemoteScript) != DebugModes.RemoteScript) && (this.Context.CurrentRunspace.Debugger.DebugMode != DebugModes.None))) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs index bf108968b08..f4788fd89bc 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs @@ -129,7 +129,7 @@ public SwitchParameter PassThru /// Script to execute. public void RunScript(string script) { - if (_showCommandProxy is null || string.IsNullOrEmpty(script)) + if (_showCommandProxy == null || string.IsNullOrEmpty(script)) { return; } @@ -206,7 +206,7 @@ protected override void BeginProcessing() /// protected override void ProcessRecord() { - if (Name is null) + if (Name == null) { _hasOpenedWindow = this.CanProcessRecordForAllCommands(); } @@ -331,7 +331,7 @@ private void GetCommandInfoAndModules(out CommandInfo command, out Dictionary public ShowCommandCommandInfo(CommandInfo other) { - if (other is null) + if (other == null) { throw new ArgumentNullException(nameof(other)); } @@ -69,7 +69,7 @@ public ShowCommandCommandInfo(CommandInfo other) /// public ShowCommandCommandInfo(PSObject other) { - if (other is null) + if (other == null) { throw new ArgumentNullException(nameof(other)); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandModuleInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandModuleInfo.cs index 6320f52f42b..457cf6d7028 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandModuleInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandModuleInfo.cs @@ -19,7 +19,7 @@ public class ShowCommandModuleInfo /// public ShowCommandModuleInfo(PSModuleInfo other) { - if (other is null) + if (other == null) { throw new ArgumentNullException(nameof(other)); } @@ -35,7 +35,7 @@ public ShowCommandModuleInfo(PSModuleInfo other) /// public ShowCommandModuleInfo(PSObject other) { - if (other is null) + if (other == null) { throw new ArgumentNullException(nameof(other)); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterInfo.cs index 9f7f13b02d8..665fa039929 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterInfo.cs @@ -21,7 +21,7 @@ public class ShowCommandParameterInfo /// public ShowCommandParameterInfo(CommandParameterInfo other) { - if (other is null) + if (other == null) { throw new ArgumentNullException(nameof(other)); } @@ -48,7 +48,7 @@ public ShowCommandParameterInfo(CommandParameterInfo other) /// public ShowCommandParameterInfo(PSObject other) { - if (other is null) + if (other == null) { throw new ArgumentNullException(nameof(other)); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterSetInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterSetInfo.cs index d55b87e03c2..e3c4cbf2cb7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterSetInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterSetInfo.cs @@ -21,7 +21,7 @@ public class ShowCommandParameterSetInfo /// public ShowCommandParameterSetInfo(CommandParameterSetInfo other) { - if (other is null) + if (other == null) { throw new ArgumentNullException(nameof(other)); } @@ -39,7 +39,7 @@ public ShowCommandParameterSetInfo(CommandParameterSetInfo other) /// public ShowCommandParameterSetInfo(PSObject other) { - if (other is null) + if (other == null) { throw new ArgumentNullException(nameof(other)); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterType.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterType.cs index 24c4b954c43..d7a3258d27b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterType.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterType.cs @@ -20,7 +20,7 @@ public class ShowCommandParameterType /// public ShowCommandParameterType(Type other) { - if (other is null) + if (other == null) { throw new ArgumentNullException(nameof(other)); } @@ -49,7 +49,7 @@ public ShowCommandParameterType(Type other) /// public ShowCommandParameterType(PSObject other) { - if (other is null) + if (other == null) { throw new ArgumentNullException(nameof(other)); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Sort-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Sort-Object.cs index a1b158e2358..5f66b39753f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Sort-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Sort-Object.cs @@ -244,7 +244,7 @@ protected override void EndProcessing() var dataToProcess = orderByProperty.OrderMatrix; var comparer = orderByProperty.Comparer; - if (comparer is null || dataToProcess is null || dataToProcess.Count == 0) + if (comparer == null || dataToProcess == null || dataToProcess.Count == 0) { return; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-List.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-List.cs index 52fb4e99f11..dbff09ef36a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-List.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-List.cs @@ -77,13 +77,13 @@ protected override void ProcessRecord() { if (Property != null) { - if (InputObject is null) + if (InputObject == null) { WriteError(NewError("MissingInputObjectParameter", "MissingInputObjectParameter", null)); } else { - if (_listModifier is null) + if (_listModifier == null) { _listModifier = CreatePSListModifier(); } @@ -114,7 +114,7 @@ protected override void ProcessRecord() /// protected override void EndProcessing() { - if (Property is null) + if (Property == null) { if (InputObject != null) { 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 1f01235effc..de7d2590176 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs @@ -603,7 +603,7 @@ private void EnsureValue1NotNullOrEmpty() return; } - if (_value1 is null) + if (_value1 == null) { ThrowTerminatingError(NewError("ValueShouldBeSpecified", UpdateDataStrings.ShouldNotBeNull, null, "Value", _memberType)); } @@ -619,7 +619,7 @@ private void EnsureValue2HasNotBeenSpecified() private void EnsureValue1AndValue2AreNotBothNull() { - if (_value1 is null && _value2 is null) + if (_value1 == null && _value2 == null) { ThrowTerminatingError(NewError("ValueAndSecondValueAreNotBothNull", UpdateDataStrings.Value1AndValue2AreNotBothNull, null, _memberType)); } @@ -633,10 +633,10 @@ private void EnsureValue1AndValue2AreNotBothNull() private bool EnsureTypeDataIsNotEmpty(TypeData typeData) { if (typeData.Members.Count == 0 && typeData.StandardMembers.Count == 0 - && typeData.TypeConverter is null && typeData.TypeAdapter is null - && typeData.DefaultDisplayPropertySet is null - && typeData.DefaultKeyPropertySet is null - && typeData.PropertySerializationSet is null) + && typeData.TypeConverter == null && typeData.TypeAdapter == null + && typeData.DefaultDisplayPropertySet == null + && typeData.DefaultKeyPropertySet == null + && typeData.PropertySerializationSet == null) { this.WriteError(NewError("TypeDataEmpty", UpdateDataStrings.TypeDataEmpty, null, typeData.TypeName)); return false; @@ -1127,7 +1127,7 @@ protected override void ProcessRecord() for (int index = 0; index < Context.InitialSessionState.Types.Count; index++) { string fileName = Context.InitialSessionState.Types[index].FileName; - if (fileName is null) { continue; } + if (fileName == null) { continue; } // Resolving the file path because the path to the types file in module manifest is now specified as // ..\..\types.ps1xml which expands to C:\Windows\System32\WindowsPowerShell\v1.0\Modules\Microsoft.PowerShell.Core\..\..\types.ps1xml @@ -1286,7 +1286,7 @@ public class GetTypeDataCommand : PSCmdlet private void ValidateTypeName() { - if (TypeName is null) + if (TypeName == null) { _filter = new WildcardPattern[] { WildcardPattern.Get("*", WildcardOptions.None) }; return; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs index 912da745ea9..aa4c2634266 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs @@ -119,7 +119,7 @@ public ByteCollection(uint offset, byte[] value, string path) /// Indicates the path of the file whose contents are wrapped in the ByteCollection. public ByteCollection(ulong offset, byte[] value, string path) { - if (value is null) + if (value == null) { throw PSTraceSource.NewArgumentNullException(nameof(value)); } @@ -148,7 +148,7 @@ public ByteCollection(uint offset, byte[] value) /// Underlying bytes stored in the collection. public ByteCollection(ulong offset, byte[] value) { - if (value is null) + if (value == null) { throw PSTraceSource.NewArgumentNullException(nameof(value)); } @@ -177,7 +177,7 @@ public ByteCollection(ulong offset, string label, byte[] value) /// Underlying bytes stored in the collection. public ByteCollection(byte[] value) { - if (value is null) + if (value == null) { throw PSTraceSource.NewArgumentNullException(nameof(value)); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs index fdffcb029e9..6739dbb38e5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs @@ -40,7 +40,7 @@ protected string[] IncludeFilters set { - if (value is null) + if (value == null) { value = Array.Empty(); } @@ -63,7 +63,7 @@ protected string[] ExcludeFilters set { - if (value is null) + if (value == null) { value = Array.Empty(); } @@ -260,7 +260,7 @@ public string[] Name set { - if (value is null) + if (value == null) { value = new string[] { "*" }; } @@ -745,7 +745,7 @@ protected override void ProcessRecord() { if (Value != AutomationNull.Value) { - if (_valueList is null) + if (_valueList == null) { _valueList = new List(); } @@ -875,7 +875,7 @@ private void SetVariable(string[] varNames, object varValue) newVarValue, newOptions); - if (Description is null) + if (Description == null) { Description = string.Empty; } @@ -1107,7 +1107,7 @@ protected override void ProcessRecord() // Removal of variables only happens in the local scope if the // scope wasn't explicitly specified by the user. - if (Scope is null) + if (Scope == null) { Scope = "local"; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs index 54fa9f2af1b..7aeb864e2ba 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs @@ -115,7 +115,7 @@ protected override void StopProcessing() private void ReceivedEvents_PSEventReceived(object sender, PSEventArgs e) { // If they want to wait on just any event - if (_sourceIdentifier is null) + if (_sourceIdentifier == null) { NotifyEvent(e); } @@ -135,7 +135,7 @@ private void ScanEventQueue() foreach (PSEventArgs eventArg in Events.ReceivedEvents) { // If they specified a subscription identifier and we don't match, continue - if ((_matchPattern is null) || (_matchPattern.IsMatch(eventArg.SourceIdentifier))) + if ((_matchPattern == null) || (_matchPattern.IsMatch(eventArg.SourceIdentifier))) { NotifyEvent(eventArg); return; @@ -147,11 +147,11 @@ private void ScanEventQueue() // Notify that an event has arrived private void NotifyEvent(PSEventArgs e) { - if (_receivedEvent is null) + if (_receivedEvent == null) { lock (_receivedEventLock) { - if (_receivedEvent is null) + if (_receivedEvent == null) { _receivedEvent = e; _eventArrived.Set(); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs index e00117bd6aa..1d33957d624 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs @@ -84,7 +84,7 @@ public WebCmdletElementCollection InputFields { get { - if (_inputFields is null) + if (_inputFields == null) { EnsureHtmlParser(); @@ -111,7 +111,7 @@ public WebCmdletElementCollection Links { get { - if (_links is null) + if (_links == null) { EnsureHtmlParser(); @@ -138,7 +138,7 @@ public WebCmdletElementCollection Images { get { - if (_images is null) + if (_images == null) { EnsureHtmlParser(); @@ -200,37 +200,37 @@ private PSObject CreateHtmlObject(string html, string tagName) private void EnsureHtmlParser() { - if (s_tagRegex is null) + if (s_tagRegex == null) { s_tagRegex = new Regex(@"<\w+((\s+[^""'>/=\s\p{Cc}]+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)+\s*|\s*)/?>", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); } - if (s_attribsRegex is null) + if (s_attribsRegex == null) { s_attribsRegex = new Regex(@"(?<=\s+)([^""'>/=\s\p{Cc}]+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); } - if (s_attribNameValueRegex is null) + if (s_attribNameValueRegex == null) { s_attribNameValueRegex = new Regex(@"([^""'>/=\s\p{Cc}]+)(?:\s*=\s*(?:""(.*?)""|'(.*?)'|([^'"">\s]+)))?", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); } - if (s_inputFieldRegex is null) + if (s_inputFieldRegex == null) { s_inputFieldRegex = new Regex(@"]*(/>|>.*?)", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); } - if (s_linkRegex is null) + if (s_linkRegex == null) { s_linkRegex = new Regex(@"]*(/>|>.*?)", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); } - if (s_imageRegex is null) + if (s_imageRegex == null) { s_imageRegex = new Regex(@"]*?>", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs index df689537472..8e28c630e17 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs @@ -83,12 +83,12 @@ internal static StringBuilder GetRawContentHeader(HttpResponseMessage response) HttpHeaders[] headerCollections = { response.Headers, - response.Content is null ? null : response.Content.Headers + response.Content == null ? null : response.Content.Headers }; foreach (var headerCollection in headerCollections) { - if (headerCollection is null) + if (headerCollection == null) { continue; } 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 b609d019dad..273fae835c3 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 @@ -189,7 +189,7 @@ private bool TryConvertToJson(string json, out object obj, ref Exception exRef) ErrorRecord error; obj = JsonObject.ConvertFromJson(json, out error); - if (obj is null) + if (obj == null) { // This ensures that a null returned by ConvertFromJson() is the actual JSON null literal. // if not, the ArgumentException will be caught. @@ -380,7 +380,7 @@ public partial class InvokeRestMethodCommand : WebRequestPSCmdlet /// internal override void ProcessResponse(HttpResponseMessage response) { - if (response is null) { throw new ArgumentNullException(nameof(response)); } + if (response == null) { throw new ArgumentNullException(nameof(response)); } var baseResponseStream = StreamHelper.GetResponseStream(response); @@ -480,7 +480,7 @@ internal override void ProcessResponse(HttpResponseMessage response) private RestReturnType CheckReturnType(HttpResponseMessage response) { - if (response is null) { throw new ArgumentNullException(nameof(response)); } + if (response == null) { throw new ArgumentNullException(nameof(response)); } RestReturnType rt = RestReturnType.Detect; string contentType = ContentHelper.GetContentType(response); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 5173d703fa9..f38446ed57f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -418,14 +418,14 @@ internal virtual void ValidateParameters() ThrowTerminatingError(error); } - if ((Authentication == WebAuthenticationType.Basic) && (Credential is null)) + if ((Authentication == WebAuthenticationType.Basic) && (Credential == null)) { ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationCredentialNotSupplied, "WebCmdletAuthenticationCredentialNotSuppliedException"); ThrowTerminatingError(error); } - if ((Authentication == WebAuthenticationType.OAuth || Authentication == WebAuthenticationType.Bearer) && (Token is null)) + if ((Authentication == WebAuthenticationType.OAuth || Authentication == WebAuthenticationType.Bearer) && (Token == null)) { ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationTokenNotSupplied, "WebCmdletAuthenticationTokenNotSuppliedException"); @@ -461,7 +461,7 @@ internal virtual void ValidateParameters() "WebCmdletProxyCredentialConflictException"); ThrowTerminatingError(error); } - else if ((Proxy is null) && ((ProxyCredential != null) || ProxyUseDefaultCredentials)) + else if ((Proxy == null) && ((ProxyCredential != null) || ProxyUseDefaultCredentials)) { ErrorRecord error = GetValidationError(WebCmdletStrings.ProxyUriNotSupplied, "WebCmdletProxyUriNotSuppliedException"); @@ -550,7 +550,7 @@ internal virtual void ValidateParameters() } // output ?? - if (PassThru && (OutFile is null)) + if (PassThru && (OutFile == null)) { ErrorRecord error = GetValidationError(WebCmdletStrings.OutFileMissing, "WebCmdletOutFileMissingException", nameof(PassThru)); @@ -558,7 +558,7 @@ internal virtual void ValidateParameters() } // Resume requires OutFile. - if (Resume.IsPresent && OutFile is null) + if (Resume.IsPresent && OutFile == null) { ErrorRecord error = GetValidationError(WebCmdletStrings.OutFileMissing, "WebCmdletOutFileMissingException", nameof(Resume)); @@ -569,7 +569,7 @@ internal virtual void ValidateParameters() internal virtual void PrepareSession() { // make sure we have a valid WebRequestSession object to work with - if (WebSession is null) + if (WebSession == null) { WebSession = new WebRequestSession(); } @@ -751,7 +751,7 @@ private Uri PrepareUri(Uri uri) private Uri CheckProtocol(Uri uri) { - if (uri is null) { throw new ArgumentNullException(nameof(uri)); } + if (uri == null) { throw new ArgumentNullException(nameof(uri)); } if (!uri.IsAbsoluteUri) { @@ -769,7 +769,7 @@ private string QualifyFilePath(string path) private string FormatDictionary(IDictionary content) { - if (content is null) + if (content == null) throw new ArgumentNullException(nameof(content)); StringBuilder bodyBuilder = new StringBuilder(); @@ -1165,7 +1165,7 @@ internal virtual HttpRequestMessage GetRequest(Uri uri) internal virtual void FillRequestStream(HttpRequestMessage request) { - if (request is null) { throw new ArgumentNullException(nameof(request)); } + if (request == null) { throw new ArgumentNullException(nameof(request)); } // set the content type if (ContentType != null) @@ -1173,7 +1173,7 @@ internal virtual void FillRequestStream(HttpRequestMessage request) WebSession.ContentHeaders[HttpKnownHeaderNames.ContentType] = ContentType; // request } - // ContentType is null + // ContentType == null else if (Method == WebRequestMethod.Post || (IsCustomMethodSet() && CustomMethod.ToUpperInvariant() == "POST")) { // Win8:545310 Invoke-WebRequest does not properly set MIME type for POST @@ -1259,7 +1259,7 @@ internal virtual void FillRequestStream(HttpRequestMessage request) } // Add the content headers - if (request.Content is null) + if (request.Content == null) { request.Content = new StringContent(string.Empty); request.Content.Headers.Clear(); @@ -1338,9 +1338,9 @@ private bool ShouldRetry(HttpStatusCode code) internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestMessage request, bool keepAuthorization) { - if (client is null) { throw new ArgumentNullException(nameof(client)); } + if (client == null) { throw new ArgumentNullException(nameof(client)); } - if (request is null) { throw new ArgumentNullException(nameof(request)); } + if (request == null) { throw new ArgumentNullException(nameof(request)); } // Add 1 to account for the first request. int totalRequests = WebSession.MaximumRetryCount + 1; @@ -1452,7 +1452,7 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM internal virtual void UpdateSession(HttpResponseMessage response) { - if (response is null) { throw new ArgumentNullException(nameof(response)); } + if (response == null) { throw new ArgumentNullException(nameof(response)); } } #endregion Virtual Methods @@ -1657,9 +1657,9 @@ protected override void StopProcessing() /// internal long SetRequestContent(HttpRequestMessage request, byte[] content) { - if (request is null) + if (request == null) throw new ArgumentNullException(nameof(request)); - if (content is null) + if (content == null) return 0; var byteArrayContent = new ByteArrayContent(content); @@ -1680,10 +1680,10 @@ internal long SetRequestContent(HttpRequestMessage request, byte[] content) /// internal long SetRequestContent(HttpRequestMessage request, string content) { - if (request is null) + if (request == null) throw new ArgumentNullException(nameof(request)); - if (content is null) + if (content == null) return 0; Encoding encoding = null; @@ -1729,10 +1729,10 @@ internal long SetRequestContent(HttpRequestMessage request, string content) internal long SetRequestContent(HttpRequestMessage request, XmlNode xmlNode) { - if (request is null) + if (request == null) throw new ArgumentNullException(nameof(request)); - if (xmlNode is null) + if (xmlNode == null) return 0; byte[] bytes = null; @@ -1766,9 +1766,9 @@ internal long SetRequestContent(HttpRequestMessage request, XmlNode xmlNode) /// internal long SetRequestContent(HttpRequestMessage request, Stream contentStream) { - if (request is null) + if (request == null) throw new ArgumentNullException(nameof(request)); - if (contentStream is null) + if (contentStream == null) throw new ArgumentNullException(nameof(contentStream)); var streamContent = new StreamContent(contentStream); @@ -1789,12 +1789,12 @@ internal long SetRequestContent(HttpRequestMessage request, Stream contentStream /// internal long SetRequestContent(HttpRequestMessage request, MultipartFormDataContent multipartContent) { - if (request is null) + if (request == null) { throw new ArgumentNullException(nameof(request)); } - if (multipartContent is null) + if (multipartContent == null) { throw new ArgumentNullException(nameof(multipartContent)); } @@ -1806,9 +1806,9 @@ internal long SetRequestContent(HttpRequestMessage request, MultipartFormDataCon internal long SetRequestContent(HttpRequestMessage request, IDictionary content) { - if (request is null) + if (request == null) throw new ArgumentNullException(nameof(request)); - if (content is null) + if (content == null) throw new ArgumentNullException(nameof(content)); string body = FormatDictionary(content); @@ -1817,7 +1817,7 @@ internal long SetRequestContent(HttpRequestMessage request, IDictionary content) internal void ParseLinkHeader(HttpResponseMessage response, System.Uri requestUri) { - if (_relationLink is null) + if (_relationLink == null) { // Must ignore the case of relation links. See RFC 8288 (https://tools.ietf.org/html/rfc8288) _relationLink = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -1862,7 +1862,7 @@ internal void ParseLinkHeader(HttpResponseMessage response, System.Uri requestUr /// If true, collection types in will be enumerated. If false, collections will be treated as single value. private void AddMultipartContent(object fieldName, object fieldValue, MultipartFormDataContent formData, bool enumerate) { - if (formData is null) + if (formData == null) { throw new ArgumentNullException("formDate"); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs index 01fafabbfa7..70c5721dbc1 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs @@ -53,7 +53,7 @@ public MemoryStream RawContentStream /// public long RawContentLength { - get { return (RawContentStream is null ? -1 : RawContentStream.Length); } + get { return (RawContentStream == null ? -1 : RawContentStream.Length); } } /// @@ -123,7 +123,7 @@ public Dictionary> Headers { get { - if (_headers is null) + if (_headers == null) { _headers = WebResponseHelper.GetHeadersDictionary(BaseResponse); } @@ -182,7 +182,7 @@ private void InitializeRawContent(HttpResponseMessage baseResponse) private void SetResponse(HttpResponseMessage response, Stream contentStream) { - if (response is null) { throw new ArgumentNullException(nameof(response)); } + if (response == null) { throw new ArgumentNullException(nameof(response)); } BaseResponse = response; @@ -194,7 +194,7 @@ private void SetResponse(HttpResponseMessage response, Stream contentStream) else { Stream st = contentStream; - if (contentStream is null) + if (contentStream == null) { st = StreamHelper.GetResponseStream(response); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs index 904ae4be42a..80d07a54ddf 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs @@ -84,7 +84,7 @@ internal static HashSet ContentHeaders { get { - if (s_contentHeaderSet is null) + if (s_contentHeaderSet == null) { s_contentHeaderSet = new HashSet(StringComparer.OrdinalIgnoreCase); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs index ae16ade8993..b0f849490cd 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs @@ -31,7 +31,7 @@ public InvokeWebRequestCommand() : base() /// internal override void ProcessResponse(HttpResponseMessage response) { - if (response is null) { throw new ArgumentNullException(nameof(response)); } + if (response == null) { throw new ArgumentNullException(nameof(response)); } Stream responseStream = StreamHelper.GetResponseStream(response); if (ShouldWriteToPipeline) 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 7720c8eca8d..5cb4f2b4fde 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 @@ -13,7 +13,7 @@ internal class WebProxy : IWebProxy internal WebProxy(Uri address) { - if (address is null) + if (address == null) { throw new ArgumentNullException(nameof(address)); } @@ -48,7 +48,7 @@ internal bool UseDefaultCredentials public Uri GetProxy(Uri destination) { - if (destination is null) + if (destination == null) { throw new ArgumentNullException(nameof(destination)); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs index 82baa0a5d34..2b15f150984 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs @@ -152,7 +152,7 @@ public static object ConvertFromJson(string input, bool returnHashtable, out Err [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Preferring Json over JSON")] public static object ConvertFromJson(string input, bool returnHashtable, int? maxDepth, out ErrorRecord error) { - if (input is null) + if (input == null) { throw new ArgumentNullException(nameof(input)); } @@ -622,7 +622,7 @@ private static object AddPsProperties(object psObj, object obj, int depth, bool { PSObject pso = psObj as PSObject; - if (pso is null) + if (pso == null) { return obj; } @@ -636,7 +636,7 @@ private static object AddPsProperties(object psObj, object obj, int depth, bool bool wasDictionary = true; IDictionary dict = obj as IDictionary; - if (dict is null) + if (dict == null) { wasDictionary = false; dict = new Dictionary(); @@ -702,7 +702,7 @@ private static object ProcessDictionary(IDictionary dict, int depth, in ConvertT foreach (DictionaryEntry entry in dict) { string name = entry.Key as string; - if (name is null) + if (name == null) { // use the error string that matches the message from JavaScriptSerializer string errorMsg = string.Format( diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs index 5c78b595da3..a730c043216 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs @@ -128,7 +128,7 @@ internal static string PlatformName if (Platform.IsWindows) { // only generate the windows user agent once - if (s_windowsUserAgent is null) + if (s_windowsUserAgent == null) { // find the version in the windows operating system description Regex pattern = new Regex(@"\d+(\.\d+)+"); 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 f5cfcecbaec..58d63c36ca3 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs @@ -277,7 +277,7 @@ internal static class StreamHelper internal static void WriteToStream(Stream input, Stream output, PSCmdlet cmdlet, CancellationToken cancellationToken) { - if (cmdlet is null) + if (cmdlet == null) { throw new ArgumentNullException(nameof(cmdlet)); } @@ -418,7 +418,7 @@ internal static bool TryGetEncoding(string characterSet, out Encoding encoding) internal static string DecodeStream(Stream stream, ref Encoding encoding) { bool isDefaultEncoding = false; - if (encoding is null) + if (encoding == null) { // Use the default encoding if one wasn't provided encoding = ContentHelper.GetDefaultEncoding(); @@ -453,7 +453,7 @@ internal static string DecodeStream(Stream stream, ref Encoding encoding) internal static byte[] EncodeToBytes(string str, Encoding encoding) { - if (encoding is null) + if (encoding == null) { // just use the default encoding if one wasn't provided encoding = ContentHelper.GetDefaultEncoding(); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs index 56e9812371c..a28f07c842c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs @@ -104,7 +104,7 @@ public WebRequestSession() /// The certificate to be added. internal void AddCertificate(X509Certificate certificate) { - if (Certificates is null) + if (Certificates == null) { Certificates = new X509CertificateCollection(); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write-Object.cs index d205754c5e8..2d7fc9d233d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write-Object.cs @@ -31,7 +31,7 @@ public sealed class WriteOutputCommand : PSCmdlet /// protected override void ProcessRecord() { - if (InputObject is null) + if (InputObject == null) { WriteObject(InputObject); return; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs index 5676a122776..6f374336da5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs @@ -312,7 +312,7 @@ protected override void ProcessRecord() { Exception e = this.Exception; string msg = Message; - if (e is null) + if (e == null) { e = new WriteErrorException(msg); } @@ -339,7 +339,7 @@ protected override void ProcessRecord() string recact = RecommendedAction; if (!string.IsNullOrEmpty(recact)) { - if (errorRecord.ErrorDetails is null) + if (errorRecord.ErrorDetails == null) { errorRecord.ErrorDetails = new ErrorDetails(errorRecord.ToString()); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/GetTracerCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/GetTracerCommand.cs index 3b792b1f8bd..b37f06b2b2f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/GetTracerCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/GetTracerCommand.cs @@ -30,7 +30,7 @@ public string[] Name set { - if (value is null || value.Length == 0) + if (value == null || value.Length == 0) { value = new string[] { "*" }; } 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 d451046d9ad..9b225bdc141 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs @@ -29,7 +29,7 @@ internal class PSHostTraceListener internal PSHostTraceListener(PSCmdlet cmdlet) : base(string.Empty) { - if (cmdlet is null) + if (cmdlet == null) { throw new PSArgumentNullException(nameof(cmdlet)); } 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 b29ae28ae76..12f8e5b4e09 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs @@ -211,7 +211,7 @@ protected override void ProcessRecord() ResetTracing(_matchingSources); - if (result is null) + if (result == null) { return; } @@ -332,12 +332,12 @@ internal TracePipelineWriter( bool writeError, Collection matchingSources) { - if (cmdlet is null) + if (cmdlet == null) { throw new ArgumentNullException(nameof(cmdlet)); } - if (matchingSources is null) + if (matchingSources == null) { throw new ArgumentNullException(nameof(matchingSources)); } 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 1351c2f4dc1..3eecdd51cba 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceListenerCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceListenerCommandBase.cs @@ -194,7 +194,7 @@ internal void AddTraceListenersToSources(Collection matchingSourc { if (DebuggerListener) { - if (_defaultListener is null) + if (_defaultListener == null) { _defaultListener = new DefaultTraceListener(); @@ -208,7 +208,7 @@ internal void AddTraceListenersToSources(Collection matchingSourc if (PSHostListener) { - if (_hostListener is null) + if (_hostListener == null) { ((MshCommandRuntime)this.CommandRuntime).DebugPreference = ActionPreference.Continue; _hostListener = new PSHostTraceListener(this); @@ -222,7 +222,7 @@ internal void AddTraceListenersToSources(Collection matchingSourc if (FileListener != null) { - if (_fileListeners is null) + if (_fileListeners == null) { _fileListeners = new Collection(); FileStreams = new Collection(); diff --git a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs index b00ba105c15..5c76d6051b8 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs @@ -29,7 +29,7 @@ internal sealed class PropVariant : IDisposable /// internal PropVariant(string value) { - if (value is null) + if (value == null) { throw new ArgumentException("PropVariantNullString", nameof(value)); } diff --git a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropertyKey.cs b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropertyKey.cs index feaf8558bf9..be45b0d8d84 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropertyKey.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropertyKey.cs @@ -72,7 +72,7 @@ public override int GetHashCode() /// Equality result. public override bool Equals(object obj) { - if (obj is null) + if (obj == null) return false; if (!(obj is PropertyKey)) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs index dcb4e2e2418..cb3f9f01e8c 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs @@ -225,7 +225,7 @@ internal class CommandLineParameterParser internal CommandLineParameterParser(PSHostUserInterface hostUI, string bannerText, string helpText) { - if (hostUI is null) + if (hostUI == null) { throw new PSArgumentNullException(nameof(hostUI)); } @@ -544,7 +544,7 @@ private static string GetConfigurationNameFromGroupPolicy() /// internal static void EarlyParse(string[] args) { - if (args is null) + if (args == null) { Dbg.Assert(args != null, "Argument 'args' to EarlyParseHelper should never be null"); return; @@ -897,7 +897,7 @@ private void ParseHelper(string[] args) } else if (MatchSwitch(switchKey, "modules", "mod")) { - if (ConsoleHost.DefaultInitialSessionState is null) + if (ConsoleHost.DefaultInitialSessionState == null) { WriteCommandLineError( "The -module option can only be specified with the -iss option.", diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs index cc94a51d97e..6159e349497 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs @@ -1083,7 +1083,7 @@ internal static void WriteConsoleOutput(ConsoleHandle consoleHandle, Coordinates { Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed"); - if (contents is null) + if (contents == null) { throw PSTraceSource.NewArgumentNullException(nameof(contents)); } @@ -1746,7 +1746,7 @@ internal static void ReadConsoleOutput if (origin.X + (contentsRegion.Right - contentsRegion.Left) + 1 < bufferInfo.BufferSize.X && ShouldCheck(contentsRegion.Right, contents, contentsRegion)) { - if (cellArray is null) + if (cellArray == null) { cellArray = new BufferCell[cellArrayRegion.Bottom + 1, 2]; } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index 5db4ca48169..39a32d77c22 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -409,7 +409,7 @@ private static void SpinUpBreakHandlerThread(bool shouldEndSession) // after it is created and before started and call join on it. This will result // in ThreadStateException. // NTRAID#Windows OutofBand Bugs-938289-2006/07/27-hiteshr - if (bht is null) + if (bht == null) { // we're not already running HandleBreak on a separate thread, so run it now. @@ -498,7 +498,7 @@ private static bool StopPipeline(Pipeline cmd) /// internal static ConsoleHost CreateSingletonInstance() { - Dbg.Assert(s_theConsoleHost is null, "CreateSingletonInstance should not be called multiple times"); + Dbg.Assert(s_theConsoleHost == null, "CreateSingletonInstance should not be called multiple times"); s_theConsoleHost = new ConsoleHost(); return s_theConsoleHost; } @@ -575,7 +575,7 @@ public override PSHostUserInterface UI /// public void PushRunspace(Runspace newRunspace) { - if (_runspaceRef is null) { return; } + if (_runspaceRef == null) { return; } RemoteRunspace remoteRunspace = newRunspace as RemoteRunspace; Dbg.Assert(remoteRunspace != null, "Expected remoteRunspace != null"); @@ -648,7 +648,7 @@ private void HandleRemoteRunspaceStateChanged(object sender, RunspaceStateEventA /// public void PopRunspace() { - if (_runspaceRef is null || + if (_runspaceRef == null || !_runspaceRef.IsRunspaceOverridden) { return; @@ -708,7 +708,7 @@ public Runspace Runspace { get { - if (this.RunspaceRef is null) { return null; } + if (this.RunspaceRef == null) { return null; } return this.RunspaceRef.Runspace; } @@ -723,7 +723,7 @@ internal LocalRunspace LocalRunspace return RunspaceRef.OldRunspace as LocalRunspace; } - if (RunspaceRef is null) { return null; } + if (RunspaceRef == null) { return null; } return RunspaceRef.Runspace as LocalRunspace; } @@ -735,7 +735,7 @@ public class ConsoleColorProxy public ConsoleColorProxy(ConsoleHostUserInterface ui) { - if (ui is null) throw new ArgumentNullException(nameof(ui)); + if (ui == null) throw new ArgumentNullException(nameof(ui)); _ui = ui; } @@ -928,7 +928,7 @@ public override PSObject PrivateData { get { - if (ui is null) return null; + if (ui == null) return null; return _consoleColorProxy ?? (_consoleColorProxy = PSObject.AsPSObject(new ConsoleColorProxy(ui))); } } @@ -1094,7 +1094,7 @@ bool IHostProvidesTelemetryData.HostIsInteractive get { return !s_cpp.NonInteractive && !s_cpp.AbortStartup && - ((s_cpp.InitialCommand is null && s_cpp.File is null) || s_cpp.NoExit); + ((s_cpp.InitialCommand == null && s_cpp.File == null) || s_cpp.NoExit); } } @@ -1337,7 +1337,7 @@ internal WrappedSerializer OutputSerializer { get { - if (_outputSerializer is null) + if (_outputSerializer == null) { _outputSerializer = new WrappedSerializer( @@ -1354,7 +1354,7 @@ internal WrappedSerializer ErrorSerializer { get { - if (_errorSerializer is null) + if (_errorSerializer == null) { _errorSerializer = new WrappedSerializer( @@ -1499,7 +1499,7 @@ private uint DoRunspaceLoop(string initialCommand, bool skipProfiles, Collection bool dollarHook = exec.ExecuteCommandAndGetResultAsBool("$global:?") ?? false; - if (dollarHook && (_lastRunspaceInitializationException is null)) + if (dollarHook && (_lastRunspaceInitializationException == null)) { ExitCode = ExitCodeSuccess; } @@ -1603,7 +1603,7 @@ private bool LoadPSReadline() // Note that PSReadline doesn't support redirected stdin/stdout, but we don't check that here because // a future version might, and we should automatically load it at that unknown point in the future. // PSReadline will ideally fall back to Console.ReadLine or whatever when stdin/stdout is redirected. - return ((s_cpp.InitialCommand is null && s_cpp.File is null) || s_cpp.NoExit) && !s_cpp.NonInteractive; + return ((s_cpp.InitialCommand == null && s_cpp.File == null) || s_cpp.NoExit) && !s_cpp.NonInteractive; } /// @@ -1613,7 +1613,7 @@ private bool LoadPSReadline() private void DoCreateRunspace(string initialCommand, bool skipProfiles, bool staMode, string configurationName, Collection initialCommandArgs) { - Dbg.Assert(_runspaceRef is null, "runspace should be null"); + Dbg.Assert(_runspaceRef == null, "runspace should be null"); Dbg.Assert(DefaultInitialSessionState != null, "DefaultInitialSessionState should not be null"); s_runspaceInitTracer.WriteLine("Calling RunspaceFactory.CreateRunspace"); @@ -1657,7 +1657,7 @@ private void DoCreateRunspace(string initialCommand, bool skipProfiles, bool sta } } - if (consoleRunspace is null) + if (consoleRunspace == null) { if (psReadlineFailed) { @@ -2098,7 +2098,7 @@ private void ReportExceptionFallback(Exception e, string header) Console.Error.WriteLine(header); } - if (e is null) + if (e == null) { return; } @@ -2458,7 +2458,7 @@ internal void Run(bool inputLoopIsNested) prompt = EvaluateDebugPrompt(); } - if (prompt is null) + if (prompt == null) { prompt = EvaluatePrompt(); } @@ -2473,7 +2473,7 @@ internal void Run(bool inputLoopIsNested) // line will be null in the case that Ctrl-C terminated the input - if (line is null) + if (line == null) { previousResponseWasEmpty = true; @@ -2734,7 +2734,7 @@ private bool IsIncompleteParseException(Exception e) // If it is remote exception ferret out the real exception. RemoteException remoteException = e as RemoteException; - if (remoteException is null || remoteException.ErrorRecord is null) + if (remoteException == null || remoteException.ErrorRecord == null) { return false; } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs index aec2aa527cb..91aceef2fbd 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs @@ -878,7 +878,7 @@ public override void SetBufferContents(Coordinates origin, BufferCell[,] contents) { - if (contents is null) + if (contents == null) { PSTraceSource.NewArgumentNullException(nameof(contents)); } @@ -1228,7 +1228,7 @@ int LengthInBufferCells(string s) public override int LengthInBufferCells(string s, int offset) { - if (s is null) + if (s == null) { throw PSTraceSource.NewArgumentNullException("str"); } @@ -1620,7 +1620,7 @@ public override void SetBufferContents(Coordinates origin, BufferCell[,] contents) { // if there are no contents, there is nothing to set the buffer to - if (contents is null) + if (contents == null) { PSTraceSource.NewArgumentNullException("contents"); } @@ -1702,7 +1702,7 @@ int LengthInBufferCells(string s) public override int LengthInBufferCells(string s, int offset) { - if (s is null) + if (s == null) { throw PSTraceSource.NewArgumentNullException("str"); } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostTranscript.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostTranscript.cs index 419e2d52d56..fd1b91574b4 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostTranscript.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostTranscript.cs @@ -36,7 +36,7 @@ internal void StartTranscribing(string transcriptFilename, bool shouldAppend) lock (transcriptionStateLock) { - Dbg.Assert(transcriptionWriter is null, "writer should not exist"); + Dbg.Assert(transcriptionWriter == null, "writer should not exist"); this.transcriptFileName = transcriptFilename; transcriptionWriter = new StreamWriter(transcriptFilename, shouldAppend, new System.Text.UnicodeEncoding()); @@ -67,7 +67,7 @@ internal string StopTranscribing() { lock (_transcriptionStateLock) { - if (_transcriptionWriter is null) + if (_transcriptionWriter == null) { return null; } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs index 51703ee385f..1154715e4fb 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs @@ -1333,7 +1333,7 @@ public override void WriteWarningLine(string message) public override void WriteProgress(Int64 sourceId, ProgressRecord record) { - if (record is null) + if (record == null) { Dbg.Assert(false, "WriteProgress called with null ProgressRecord"); } @@ -1849,7 +1849,7 @@ private string ReadLineFromConsole(bool endOnTab, string initialContent, bool ca } Dbg.Assert( - (s is null && result == ReadLineResult.endedOnBreak) + (s == null && result == ReadLineResult.endedOnBreak) || (s != null && result != ReadLineResult.endedOnBreak), "s should only be null if input ended with a break"); @@ -1956,7 +1956,7 @@ internal string ReadLineWithTabCompletion(Executor exec) input = ReadLine(true, lastInput, out rlResult, false, false); - if (input is null) + if (input == null) { break; } @@ -1992,7 +1992,7 @@ internal string ReadLineWithTabCompletion(Executor exec) input = input.Remove(tabIndex); - if (input != lastCompletion || commandCompletion is null) + if (input != lastCompletion || commandCompletion == null) { completionInput = input; commandCompletion = GetNewCompletionResults(input); diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs index f5091bee082..ffc5735f35f 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs @@ -62,16 +62,16 @@ class ConsoleHostUserInterface : System.Management.Automation.Host.PSHostUserInt { Dbg.Assert(record != null, "record should not be null"); - if (_pendingProgress is null) + if (_pendingProgress == null) { - Dbg.Assert(_progPane is null, "If there is no data struct, there shouldn't be a pane, either."); + Dbg.Assert(_progPane == null, "If there is no data struct, there shouldn't be a pane, either."); _pendingProgress = new PendingProgress(); } _pendingProgress.Update(sourceId, record); - if (_progPane is null) + if (_progPane == null) { // This is the first time we've received a progress record // Create a progress pane @@ -80,7 +80,7 @@ class ConsoleHostUserInterface : System.Management.Automation.Host.PSHostUserInt _progPane = new ProgressPane(this); - if (_progPaneUpdateTimer is null) + if (_progPaneUpdateTimer == null) { // Show a progress pane at the first time we've received a progress record progPaneUpdateFlag = 1; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs index 2b9aa7d799c..e1f9c9abbce 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs @@ -95,7 +95,7 @@ public override // Need to implement EchoOnPrompt HandleThrowOnReadAndPrompt(); - if (descriptions is null) + if (descriptions == null) { throw PSTraceSource.NewArgumentNullException(nameof(descriptions)); } @@ -137,7 +137,7 @@ public override foreach (FieldDescription desc in descriptions) { descIndex++; - if (desc is null) + if (desc == null) { throw PSTraceSource.NewArgumentException(nameof(descriptions), ConsoleHostUserInterfaceStrings.NullErrorTemplate, @@ -160,7 +160,7 @@ public override } Type fieldType = InternalHostUserInterface.GetFieldType(desc); - if (fieldType is null) + if (fieldType == null) { if (InternalHostUserInterface.IsSecuritySensitiveType(desc.ParameterTypeName)) { @@ -291,7 +291,7 @@ out object convertedObj WriteToConsole(printFieldPrompt, true); SecureString secureString = ReadLineAsSecureString(); convertedObj = secureString; - cancelInput = (convertedObj is null); + cancelInput = (convertedObj == null); if ((secureString != null) && (secureString.Length == 0) && listInput) { endListInput = true; @@ -308,7 +308,7 @@ out object convertedObj userName: null, targetName: string.Empty); convertedObj = credential; - cancelInput = (convertedObj is null); + cancelInput = (convertedObj == null); if ((credential != null) && (credential.Password.Length == 0) && listInput) { endListInput = true; @@ -368,7 +368,7 @@ private string PromptReadInput(string fieldPrompt, FieldDescription desc, bool f rawInputString = userInputString; } - if (rawInputString is null) + if (rawInputString == null) { // processedInputString is null as well. No need to assign null to it. cancelled = true; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs index d05dee0e446..0dfe3f63739 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs @@ -44,7 +44,7 @@ public override int PromptForChoice(string caption, string message, Collection PromptForChoice(string caption, { HandleThrowOnReadAndPrompt(); - if (choices is null) + if (choices == null) { throw PSTraceSource.NewArgumentNullException(nameof(choices)); } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceSecurity.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceSecurity.cs index dfe5a5e5828..120bd38dcde 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceSecurity.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceSecurity.cs @@ -118,7 +118,7 @@ public override PSCredential PromptForCredential( { WriteToConsole(userPrompt, true); userName = ReadLine(); - if (userName is null) + if (userName == null) { return null; } @@ -133,7 +133,7 @@ public override PSCredential PromptForCredential( { WriteToConsole(passwordPrompt, true); password = ReadLineAsSecureString(); - if (password is null) + if (password == null) { return null; } @@ -148,7 +148,7 @@ public override PSCredential PromptForCredential( // now, prompt to re-enter the password. WriteToConsole(confirmPasswordPrompt, true); reenterPassword = ReadLineAsSecureString(); - if (reenterPassword is null) + if (reenterPassword == null) { return null; } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleShell.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleShell.cs index 46c71a7a30a..cd8364fc7ce 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleShell.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleShell.cs @@ -32,12 +32,12 @@ public static int Start(string bannerText, string helpText, string[] args) /// An integer value which should be used as exit code for the process. public static int Start(InitialSessionState initialSessionState, string bannerText, string helpText, string[] args) { - if (initialSessionState is null) + if (initialSessionState == null) { throw PSTraceSource.NewArgumentNullException(nameof(initialSessionState)); } - if (args is null) + if (args == null) { throw PSTraceSource.NewArgumentNullException(nameof(args)); } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs index 8e79059141a..24b48837005 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs @@ -119,7 +119,7 @@ private void AsyncPipelineFailureHandler(Exception ex) er = new ErrorRecord(er, ex); } - if (er is null) + if (er == null) { er = new ErrorRecord(ex, "ConsoleHostAsyncPipelineFailure", ErrorCategory.NotSpecified, null); } @@ -185,7 +185,7 @@ internal void ExecuteCommandAsyncHelper(Pipeline tempPipeline, out Exception exc lock (_instanceStateLock) { - Dbg.Assert(_pipeline is null, "no other pipeline should exist"); + Dbg.Assert(_pipeline == null, "no other pipeline should exist"); _pipeline = tempPipeline; } @@ -224,7 +224,7 @@ internal void ExecuteCommandAsyncHelper(Pipeline tempPipeline, out Exception exc while (!des.AtEnd) { object o = des.Deserialize(); - if (o is null) + if (o == null) { break; } @@ -415,7 +415,7 @@ internal Collection ExecuteCommandHelper(Pipeline tempPipeline, out Ex lock (_instanceStateLock) { - Dbg.Assert(_pipeline is null, "no other pipeline should exist"); + Dbg.Assert(_pipeline == null, "no other pipeline should exist"); _pipeline = tempPipeline; } @@ -454,7 +454,7 @@ internal Collection ExecuteCommand(string command) break; } - if (result is null) + if (result == null) { break; } @@ -493,13 +493,13 @@ internal string ExecuteCommandAndGetResultAsString(string command, out Exception break; } - if (streamResults is null || streamResults.Count == 0) + if (streamResults == null || streamResults.Count == 0) { break; } // we got back one or more objects. Pick off the first result. - if (streamResults[0] is null) + if (streamResults[0] == null) return string.Empty; // And convert the base object into a string. We can't use the proxied @@ -569,7 +569,7 @@ internal string ExecuteCommandAndGetResultAsString(string command, out Exception break; } - if (streamResults is null || streamResults.Count == 0) + if (streamResults == null || streamResults.Count == 0) { break; } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs index 269115eb1e2..2ca795447d0 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs @@ -121,7 +121,7 @@ class PendingProgress ProgressNode parentNode = FindNodeById(newNode.SourceId, newNode.ParentActivityId); if (parentNode != null) { - if (parentNode.Children is null) + if (parentNode.Children == null) { parentNode.Children = new ArrayList(); } @@ -154,7 +154,7 @@ class PendingProgress int indexWhereFound = -1; ProgressNode oldestNode = FindOldestLeafmostNode(out listWhereFound, out indexWhereFound); - if (oldestNode is null) + if (oldestNode == null) { // Well that's a surprise. There's got to be at least one node there that's older than 0. @@ -190,7 +190,7 @@ class PendingProgress Dbg.Assert(nodes != null, "can't remove nodes from a null list"); Dbg.Assert(indexToRemove < nodes.Count, "index is not in list"); Dbg.Assert(nodes[indexToRemove] != null, "no node at specified index"); - Dbg.Assert(nodeToRemove.Children is null || nodeToRemove.Children.Count == 0, "can't remove a node with children"); + Dbg.Assert(nodeToRemove.Children == null || nodeToRemove.Children.Count == 0, "can't remove a node with children"); #endif nodes.RemoveAt(indexToRemove); @@ -211,7 +211,7 @@ class PendingProgress Dbg.Assert(indexToRemove < nodes.Count, "index is not in list"); Dbg.Assert(nodeToRemove != null, "no node at specified index"); - if (nodeToRemove is null) + if (nodeToRemove == null) { return; } @@ -316,9 +316,9 @@ internal override indexWhereFound = v.IndexWhereFound; #if DEBUG || ASSERTIONS_TRACE - if (v.FoundNode is null) + if (v.FoundNode == null) { - Dbg.Assert(listWhereFound is null, "list should be null when no node found"); + Dbg.Assert(listWhereFound == null, "list should be null when no node found"); Dbg.Assert(indexWhereFound == -1, "index should indicate no node found"); Dbg.Assert(_topLevelNodes.Count == 0, "if there is no oldest node, then the tree must be empty"); Dbg.Assert(_nodeCount == 0, "if there is no oldest node, then the tree must be empty"); @@ -340,7 +340,7 @@ internal override while (true) { result = FindOldestLeafmostNodeHelper(treeToSearch, out listWhereFound, out indexWhereFound); - if (result is null || result.Children is null || result.Children.Count == 0) + if (result == null || result.Children == null || result.Children.Count == 0) { break; } @@ -442,9 +442,9 @@ internal override indexWhereFound = v.IndexWhereFound; #if DEBUG || ASSERTIONS_TRACE - if (v.FoundNode is null) + if (v.FoundNode == null) { - Dbg.Assert(listWhereFound is null, "list should be null when no node found"); + Dbg.Assert(listWhereFound == null, "list should be null when no node found"); Dbg.Assert(indexWhereFound == -1, "index should indicate no node found"); } #endif @@ -470,7 +470,7 @@ internal override ProgressNode FindOldestNodeOfGivenStyle(ArrayList nodes, int oldestSoFar, ProgressNode.RenderStyle style) { - if (nodes is null) + if (nodes == null) { return null; } @@ -570,7 +570,7 @@ internal override Dbg.Assert(maxWidth > 0, "maxWidth is too small"); Dbg.Assert(maxHeight >= 3, "maxHeight is too small"); - if (_topLevelNodes is null || _topLevelNodes.Count <= 0) + if (_topLevelNodes == null || _topLevelNodes.Count <= 0) { // we have nothing to render. @@ -639,7 +639,7 @@ internal override Dbg.Assert(strings != null, "strings should not be null"); Dbg.Assert(nodes != null, "nodes should not be null"); - if (nodes is null) + if (nodes == null) { return; } @@ -729,7 +729,7 @@ private int TallyHeight(PSHostRawUserInterface rawUi, int maxHeight, int maxWidt bool AllNodesHaveGivenStyle(ArrayList nodes, ProgressNode.RenderStyle style) { - if (nodes is null) + if (nodes == null) { return false; } @@ -841,7 +841,7 @@ internal override while (true) { ProgressNode node = FindOldestNodeOfGivenStyle(_topLevelNodes, age, priorStyle); - if (node is null) + if (node == null) { // We've compressed every node of the prior style already. @@ -992,7 +992,7 @@ internal static void VisitNodes(ArrayList nodes, NodeVisitor v) { - if (nodes is null) + if (nodes == null) { return; } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs index f34125fb4f0..55dba38d6b4 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs @@ -27,7 +27,7 @@ class ProgressPane internal ProgressPane(ConsoleHostUserInterface ui) { - if (ui is null) throw new ArgumentNullException(nameof(ui)); + if (ui == null) throw new ArgumentNullException(nameof(ui)); _ui = ui; _rawui = ui.RawUI; } @@ -64,7 +64,7 @@ class ProgressPane // Get temporary reference to the progress region since it can be // changed at any time by a call to WriteProgress. BufferCell[,] tempProgressRegion = _progressRegion; - if (tempProgressRegion is null) + if (tempProgressRegion == null) { return; } @@ -180,7 +180,7 @@ class ProgressPane int maxHeight = Math.Max(5, _rawui.WindowSize.Height / 3); string[] contents = pendingProgress.Render(maxWidth, maxHeight, _rawui); - if (contents is null) + if (contents == null) { // There's nothing to show. @@ -194,7 +194,7 @@ class ProgressPane BufferCell[,] newRegion = _rawui.NewBufferCellArray(contents, _ui.ProgressForegroundColor, _ui.ProgressBackgroundColor); Dbg.Assert(newRegion != null, "NewBufferCellArray has failed!"); - if (_progressRegion is null) + if (_progressRegion == null) { // we've never shown this pane before. diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs index 47fd6df2c7e..696b95ca049 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs @@ -214,7 +214,7 @@ class WrappedDeserializer : Serialization else { o = textReader.ReadLine(); - if (o is null) + if (o == null) { _atEnd = true; } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs index 75cef89b93f..1587f91d3f9 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs @@ -166,7 +166,7 @@ protected override void BeginProcessing() object value = this.GetVariableValue("global:TRANSCRIPT", null); // $TRANSCRIPT is not set, so create a file name (the default: $HOME/My Documents/PowerShell_transcript.YYYYMMDDmmss.txt) - if (value is null) + if (value == null) { // If they've specified an output directory, use it. Otherwise, use "My Documents" if (OutputDirectory != null) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/UpdatesNotification.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/UpdatesNotification.cs index 8052015248f..5c202eb32b1 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/UpdatesNotification.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/UpdatesNotification.cs @@ -244,7 +244,7 @@ internal static async Task CheckForUpdates() string newUpdateFilePath = Path.Combine(s_cacheDirectory, newUpdateFileName); - if (updateFilePath is null) + if (updateFilePath == null) { new FileStream(newUpdateFilePath, FileMode.CreateNew, FileAccess.Write, FileShare.None).Close(); } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs index 2ffa18d2132..a1eba143e28 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs @@ -298,7 +298,7 @@ to fill the passed in ETW data descriptor. return sRet; } - if (data is null) + if (data == null) { dataDescriptor->Size = 0; dataDescriptor->DataPointer = 0; @@ -437,7 +437,7 @@ public bool WriteMessageEvent(string eventMessage, byte eventLevel, long eventKe { int status = 0; - if (eventMessage is null) + if (eventMessage == null) { throw new ArgumentNullException(nameof(eventMessage)); } @@ -508,7 +508,7 @@ public bool WriteEvent(ref EventDescriptor eventDescriptor, string data) { uint status = 0; - if (data is null) + if (data == null) { throw new ArgumentNullException("dataString"); } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs index 8af9fa53e9d..97c10d167ef 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs @@ -41,7 +41,7 @@ public string Delimiter [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] set { - if (value is null) + if (value == null) throw new ArgumentNullException("Delimiter"); if (value.Length == 0) @@ -72,7 +72,7 @@ public EventProviderTraceListener(string providerId, string name) public EventProviderTraceListener(string providerId, string name, string delimiter) : base(name) { - if (delimiter is null) + if (delimiter == null) throw new ArgumentNullException(nameof(delimiter)); if (delimiter.Length == 0) @@ -262,7 +262,7 @@ public sealed override void TraceEvent(TraceEventCache eventCache, string source return; } - if (args is null) + if (args == null) { _provider.WriteMessageEvent(format, (byte)eventType, diff --git a/src/Microsoft.PowerShell.MarkdownRender/LeafInlineRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/LeafInlineRenderer.cs index 3919ae1fd23..55a8ff32a73 100644 --- a/src/Microsoft.PowerShell.MarkdownRender/LeafInlineRenderer.cs +++ b/src/Microsoft.PowerShell.MarkdownRender/LeafInlineRenderer.cs @@ -20,7 +20,7 @@ protected override void Write(VT100Renderer renderer, LeafInline obj) // If the next sibling is null, then this is the last line in the paragraph. // Add new line character at the end. // Else just write without newline at the end. - if (obj.NextSibling is null) + if (obj.NextSibling == null) { renderer.WriteLine(obj.ToString()); } diff --git a/src/Microsoft.PowerShell.MarkdownRender/ListItemBlockRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/ListItemBlockRenderer.cs index 90bf71df074..281cec47d54 100644 --- a/src/Microsoft.PowerShell.MarkdownRender/ListItemBlockRenderer.cs +++ b/src/Microsoft.PowerShell.MarkdownRender/ListItemBlockRenderer.cs @@ -73,7 +73,7 @@ internal static string Padding(int countOfSpaces) var result = IndentCache[countOfSpaces]; - if (result is null) + if (result == null) { Interlocked.CompareExchange(ref IndentCache[countOfSpaces], new string(' ', countOfSpaces), comparand: null); result = IndentCache[countOfSpaces]; diff --git a/src/Microsoft.PowerShell.MarkdownRender/VT100EscapeSequences.cs b/src/Microsoft.PowerShell.MarkdownRender/VT100EscapeSequences.cs index 58b3220a4e3..0827fdf049f 100644 --- a/src/Microsoft.PowerShell.MarkdownRender/VT100EscapeSequences.cs +++ b/src/Microsoft.PowerShell.MarkdownRender/VT100EscapeSequences.cs @@ -287,7 +287,7 @@ public class VT100EscapeSequences /// PSMarkdownOptionInfo object to initialize with. public VT100EscapeSequences(PSMarkdownOptionInfo optionInfo) { - if (optionInfo is null) + if (optionInfo == null) { throw new ArgumentNullException(nameof(optionInfo)); } diff --git a/src/Microsoft.PowerShell.Security/security/AclCommands.cs b/src/Microsoft.PowerShell.Security/security/AclCommands.cs index df839b708e9..03fa060154b 100644 --- a/src/Microsoft.PowerShell.Security/security/AclCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/AclCommands.cs @@ -176,7 +176,7 @@ internal static void AddBrokeredProperties( /// public static string GetPath(PSObject instance) { - if (instance is null) + if (instance == null) { throw PSTraceSource.NewArgumentNullException(nameof(instance)); } @@ -203,13 +203,13 @@ public static string GetPath(PSObject instance) /// public static string GetOwner(PSObject instance) { - if (instance is null) + if (instance == null) { throw PSTraceSource.NewArgumentNullException(nameof(instance)); } ObjectSecurity sd = instance.BaseObject as ObjectSecurity; - if (sd is null) + if (sd == null) { throw PSTraceSource.NewArgumentNullException(nameof(instance)); } @@ -243,13 +243,13 @@ public static string GetOwner(PSObject instance) /// public static string GetGroup(PSObject instance) { - if (instance is null) + if (instance == null) { throw PSTraceSource.NewArgumentNullException(nameof(instance)); } ObjectSecurity sd = instance.BaseObject as ObjectSecurity; - if (sd is null) + if (sd == null) { throw PSTraceSource.NewArgumentNullException(nameof(instance)); } @@ -282,13 +282,13 @@ public static string GetGroup(PSObject instance) /// public static AuthorizationRuleCollection GetAccess(PSObject instance) { - if (instance is null) + if (instance == null) { throw PSTraceSource.NewArgumentNullException(nameof(instance)); } ObjectSecurity sd = instance.BaseObject as ObjectSecurity; - if (sd is null) + if (sd == null) { PSTraceSource.NewArgumentException(nameof(instance)); } @@ -321,13 +321,13 @@ public static AuthorizationRuleCollection GetAccess(PSObject instance) /// public static AuthorizationRuleCollection GetAudit(PSObject instance) { - if (instance is null) + if (instance == null) { throw PSTraceSource.NewArgumentNullException(nameof(instance)); } ObjectSecurity sd = instance.BaseObject as ObjectSecurity; - if (sd is null) + if (sd == null) { PSTraceSource.NewArgumentException(nameof(instance)); } @@ -443,7 +443,7 @@ public static SecurityIdentifier GetCentralAccessPolicyId(PSObject instance) public static string GetCentralAccessPolicyName(PSObject instance) { SecurityIdentifier capId = GetCentralAccessPolicyId(instance); - if (capId is null) + if (capId == null) { return null; // file does not have the scope ace } @@ -583,13 +583,13 @@ public static string[] GetAllCentralAccessPolicies(PSObject instance) /// public static string GetSddl(PSObject instance) { - if (instance is null) + if (instance == null) { throw PSTraceSource.NewArgumentNullException(nameof(instance)); } ObjectSecurity sd = instance.BaseObject as ObjectSecurity; - if (sd is null) + if (sd == null) { throw PSTraceSource.NewArgumentNullException(nameof(instance)); } @@ -1392,7 +1392,7 @@ protected override void ProcessRecord() } else { - if (Path is null) + if (Path == null) { Exception e = new ArgumentException("Path"); WriteError(new ErrorRecord( @@ -1403,7 +1403,7 @@ protected override void ProcessRecord() return; } - if (aclObjectSecurity is null) + if (aclObjectSecurity == null) { Exception e = new ArgumentException("AclObject"); WriteError(new ErrorRecord( diff --git a/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs b/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs index 4c9a518f66b..28163845d22 100644 --- a/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs @@ -135,13 +135,13 @@ protected override void ProcessRecord() string resolvedProviderPath = SecurityUtils.GetFilePathOfExistingFile(this, resolvedPath); - if (resolvedProviderPath is null) + if (resolvedProviderPath == null) { _filesNotFound.Add(p); } else { - if (Password is null && !NoPromptForPassword.IsPresent) + if (Password == null && !NoPromptForPassword.IsPresent) { try { diff --git a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs index 173f6c2f423..3436ddb6062 100644 --- a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs +++ b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs @@ -172,7 +172,7 @@ public bool Equals(DnsNameRepresentation dnsName) match = true; } } - else if (_unicodeName is null && dnsName._unicodeName is null) + else if (_unicodeName == null && dnsName._unicodeName == null) { match = true; } @@ -312,7 +312,7 @@ public void Open(bool includeArchivedCerts) _storeHandle = null; // release the old handle } - if (_storeHandle is null) + if (_storeHandle == null) { _valid = false; _open = false; @@ -634,7 +634,7 @@ private static Regex CertPathRegex { lock (s_staticLock) { - if (s_certPathRegex is null) + if (s_certPathRegex == null) { RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Compiled; s_certPathRegex = new Regex(certPathPattern, options); @@ -656,7 +656,7 @@ public CertificateProvider() // lock (s_staticLock) { - if (s_storeLocations is null) + if (s_storeLocations == null) { s_pathCache = new Hashtable(StringComparer.OrdinalIgnoreCase); s_storeLocations = @@ -1241,7 +1241,7 @@ protected override void GetItem(string path) if (!isContainer) // certificate { // If the filter is null, output the certificate we got. - if (filter is null) + if (filter == null) { WriteItemObject(item, path, isContainer); } @@ -1338,7 +1338,7 @@ private void AttemptToImportPkiModule() { const string moduleName = "pki"; - if (Runspaces.Runspace.DefaultRunspace is null) + if (Runspaces.Runspace.DefaultRunspace == null) { // // Requires default runspace. Only import the module. @@ -2049,7 +2049,7 @@ private object GetItemAtPath(string path, bool test, out bool isContainer) // item = GetCachedItem(path); - if (item is null) + if (item == null) { switch (pathElements.Length) { @@ -2368,7 +2368,7 @@ private void GetChildItemsOrNames( // false. Then we should return the names whether 'filter' // is null or not. - if (filter is null || returnNames) + if (filter == null || returnNames) { WriteItemObject(thingToReturn, l.LocationName, true); } @@ -2496,7 +2496,7 @@ private X509StoreLocation GetStoreLocation(string path) X509StoreLocation location = GetCachedItem(path) as X509StoreLocation; - if (location is null) + if (location == null) { ThrowItemNotFound(path, CertificateProviderItem.StoreLocation); } @@ -2516,7 +2516,7 @@ private X509NativeStore GetStore(string path, bool test, string[] pathElements) X509StoreLocation location = GetStoreLocation(pathElements[0]); X509NativeStore store = GetStore(path, pathElements[1], location); - if (store is null) + if (store == null) { if (test) { @@ -2560,7 +2560,7 @@ private X509NativeStore GetStore(string storePath, } } - if (s_storeCache is null) + if (s_storeCache == null) { s_storeCache = new X509NativeStore(storeLocation, storeName); } @@ -2639,7 +2639,7 @@ private void GetStoresOrNames( // false. Then we should return the names whether 'filter' // is null or not. - if (filter is null || returnNames) + if (filter == null || returnNames) { WriteItemObject(thingToReturn, name, true); } @@ -2729,7 +2729,7 @@ private bool IncludeArchivedCerts() private static bool MatchesFilter(X509Certificate2 cert, CertificateFilterInfo filter) { // No filter means, match everything - if (filter is null) + if (filter == null) { return true; } @@ -3110,7 +3110,7 @@ public bool Equals(EnhancedKeyUsageRepresentation keyUsage) match = true; } } - else if (_oid is null && keyUsage._oid is null) + else if (_oid == null && keyUsage._oid == null) { match = true; } diff --git a/src/Microsoft.PowerShell.Security/security/CmsCommands.cs b/src/Microsoft.PowerShell.Security/security/CmsCommands.cs index c755e94a260..4c90c02e941 100644 --- a/src/Microsoft.PowerShell.Security/security/CmsCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/CmsCommands.cs @@ -302,7 +302,7 @@ protected override void EndProcessing() // Extract out the bytes and Base64 decode them int startIndex, endIndex; byte[] contentBytes = CmsUtils.RemoveAsciiArmor(actualContent, CmsUtils.BEGIN_CMS_SIGIL, CmsUtils.END_CMS_SIGIL, out startIndex, out endIndex); - if (contentBytes is null) + if (contentBytes == null) { ErrorRecord error = new ErrorRecord( new ArgumentException(CmsCommands.InputContainedNoEncryptedContent), @@ -510,7 +510,7 @@ private string Decrypt(string actualContent) // Extract out the bytes and Base64 decode them int startIndex, endIndex; byte[] messageBytes = CmsUtils.RemoveAsciiArmor(actualContent, CmsUtils.BEGIN_CMS_SIGIL, CmsUtils.END_CMS_SIGIL, out startIndex, out endIndex); - if ((messageBytes is null) && (!IncludeContext)) + if ((messageBytes == null) && (!IncludeContext)) { ErrorRecord error = new ErrorRecord( new ArgumentException( diff --git a/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs b/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs index 5ab15f08909..74dee890cdf 100644 --- a/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs @@ -164,7 +164,7 @@ protected override void ProcessRecord() if (SecureKey != null) { - Dbg.Diagnostics.Assert(Key is null, "Only one encryption key should be specified"); + Dbg.Diagnostics.Assert(Key == null, "Only one encryption key should be specified"); encryptionResult = SecureStringHelper.Encrypt(SecureString, SecureKey); } else if (Key != null) @@ -348,7 +348,7 @@ protected override void ProcessRecord() if (SecureKey != null) { - Dbg.Diagnostics.Assert(Key is null, "Only one encryption key should be specified"); + Dbg.Diagnostics.Assert(Key == null, "Only one encryption key should be specified"); importedString = SecureStringHelper.Decrypt(encryptedContent, SecureKey, iv); } else if (Key != null) diff --git a/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs b/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs index 1240ca95aea..91a3e8e3a83 100644 --- a/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs @@ -151,7 +151,7 @@ private SignatureCommandsBase() : base() { } /// protected override void ProcessRecord() { - if (Content is null) + if (Content == null) { // // this cannot happen as we have specified the Path @@ -200,7 +200,7 @@ protected override void ProcessRecord() string resolvedFilePath = SecurityUtils.GetFilePathOfExistingFile(this, path); - if (resolvedFilePath is null) + if (resolvedFilePath == null) { WriteError(SecurityUtils.CreateFileNotFoundErrorRecord( SignatureCommands.FileNotFound, @@ -378,7 +378,7 @@ public string TimestampServer set { - if (value is null) + if (value == null) { value = string.Empty; } @@ -442,7 +442,7 @@ protected override Signature PerformAction(string filePath) { SigningOption option = GetSigningOption(IncludeChain); - if (Certificate is null) + if (Certificate == null) { throw PSTraceSource.NewArgumentNullException("certificate"); } diff --git a/src/Microsoft.WSMan.Management/ConfigProvider.cs b/src/Microsoft.WSMan.Management/ConfigProvider.cs index 44819207469..326f53d4d94 100644 --- a/src/Microsoft.WSMan.Management/ConfigProvider.cs +++ b/src/Microsoft.WSMan.Management/ConfigProvider.cs @@ -106,7 +106,7 @@ string ICmdletProviderSupportsHelp.GetHelpMaml(string helpItemName, string path) culture = culture.Parent; } while (culture != culture.Parent); - if (helpFile is null) + if (helpFile == null) { // Can't find help file. Return empty string return string.Empty; @@ -188,7 +188,7 @@ string ICmdletProviderSupportsHelp.GetHelpMaml(string helpItemName, string path) /// protected override PSDriveInfo NewDrive(PSDriveInfo drive) { - if (drive is null) + if (drive == null) { return null; } @@ -425,7 +425,7 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether it has Chi { XmlDocument xmlCertificates = EnumerateResourceValue(sessionobj, WsManURI); Hashtable KeyCache, CertificatesObjCache; - if (xmlCertificates is null) + if (xmlCertificates == null) { return true; } @@ -533,7 +533,7 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether it has Chi strPathCheck = strPathCheck + WSManStringLiterals.containerSecurity + WSManStringLiterals.DefaultPathSeparator; if (path.Contains(strPathCheck + WSManStringLiterals.containerSecurity + "_")) { - if (arrSecurities is null) + if (arrSecurities == null) { return false; } @@ -617,7 +617,7 @@ protected override void GetItem(string path) SessionObjCache.TryGetValue(host, out sessionobj); XmlDocument xmlResource = FindResourceValue(sessionobj, uri, null); - if (xmlResource is null) { return; } + if (xmlResource == null) { return; } // if endswith '\', removes it. if (path.EndsWith(WSManStringLiterals.DefaultPathSeparator.ToString(), StringComparison.OrdinalIgnoreCase)) @@ -654,7 +654,7 @@ protected override void GetItem(string path) strPathChk = strPathChk + WSManStringLiterals.containerPlugin + WSManStringLiterals.DefaultPathSeparator; string filter = uri + "?Name=" + currentpluginname; XmlDocument CurrentPluginXML = GetResourceValue(sessionobj, filter, null); - if (CurrentPluginXML is null) + if (CurrentPluginXML == null) { return; } @@ -682,7 +682,7 @@ protected override void GetItem(string path) strPathChk = strPathChk + currentpluginname + WSManStringLiterals.DefaultPathSeparator; if (path.Contains(strPathChk + WSManStringLiterals.containerResources)) { - if (arrResources is null) + if (arrResources == null) { return; } @@ -740,7 +740,7 @@ protected override void GetItem(string path) strPathChk = strPathChk + sResourceDirName + WSManStringLiterals.DefaultPathSeparator; if (path.Contains(strPathChk + WSManStringLiterals.containerSecurity)) { - if (arrSecurity is null) + if (arrSecurity == null) { return; } @@ -873,7 +873,7 @@ protected override void GetItem(string path) [SuppressMessage("Microsoft.Maintainability", "CA1505:AvoidUnmaintainableCode")] protected override void SetItem(string path, object value) { - if (value is null) + if (value == null) { throw new ArgumentException(helper.GetResourceMsgFromResourcetext("value")); } @@ -908,7 +908,7 @@ protected override void SetItem(string path, object value) // The value will be Null only if the object provided by User is not of accepted type. // As of now, this can only happen in case of RunAsUserName and RunAsPassword - if (value is null) + if (value == null) { return; } @@ -1081,7 +1081,7 @@ protected override void SetItem(string path, object value) { if (path.EndsWith(strPathChk + sResourceDirName, StringComparison.OrdinalIgnoreCase)) { - if (arrResources is null) + if (arrResources == null) { return; } @@ -1127,7 +1127,7 @@ protected override void SetItem(string path, object value) return; } - if (arrSecurity is null) + if (arrSecurity == null) { return; } @@ -1557,7 +1557,7 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether Item is Co return true; } - if (arrResources is null || arrResources.Count == 0) + if (arrResources == null || arrResources.Count == 0) { return false; } @@ -1584,7 +1584,7 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether Item is Co strPathCheck = strPathCheck + WSManStringLiterals.containerSecurity + WSManStringLiterals.DefaultPathSeparator; if (path.Contains(strPathCheck + WSManStringLiterals.containerSecurity + "_")) { - if (arrSecurities is null) + if (arrSecurities == null) { return false; } @@ -2204,7 +2204,7 @@ private void NewItemPluginOrPluginChild(object sessionobj, string path, string h } // Construct the Uri from Resource_XXXX resource dir. PSObject resourceDirProperties = GetItemValue(strPathChk); - if ((resourceDirProperties is null) || (resourceDirProperties.Properties["ResourceUri"] is null)) + if ((resourceDirProperties == null) || (resourceDirProperties.Properties["ResourceUri"] == null)) { string message = helper.FormatResourceMsgFromResourcetext("ResourceURIMissingInResourceDir", "ResourceUri", strPathChk); @@ -2354,7 +2354,7 @@ private void SetItemListenerOrClientCertificate(object sessionObj, string Resour Hashtable Keyscache = null; XmlDocument xmlResource = EnumerateResourceValue(sessionObj, ResourceURI); - if (xmlResource is null) + if (xmlResource == null) { AssertError(helper.GetResourceMsgFromResourcetext("InvalidPath"), false); } @@ -2424,7 +2424,7 @@ private string GetInputStringForCreate(string ResourceURI, Hashtable value, stri { sbvalues.Append(" StringBuilder sbvalues = new StringBuilder(string.Empty); - if (objinputparams is null && securities is null) + if (objinputparams == null && securities == null) { return sbvalues.ToString(); } @@ -5351,7 +5351,7 @@ private string ConstructInitParamsXml(PSObject objinputparams, ArrayList initpar // // StringBuilder sbvalues = new StringBuilder(string.Empty); - if (objinputparams is null && initparams is null) + if (objinputparams == null && initparams == null) { return sbvalues.ToString(); } diff --git a/src/Microsoft.WSMan.Management/CredSSP.cs b/src/Microsoft.WSMan.Management/CredSSP.cs index a2fc021934c..52c4f4e921d 100644 --- a/src/Microsoft.WSMan.Management/CredSSP.cs +++ b/src/Microsoft.WSMan.Management/CredSSP.cs @@ -113,7 +113,7 @@ private void DisableClientSideSettings() { WSManHelper helper = new WSManHelper(this); IWSManSession m_SessionObj = CreateWSManSession(); - if (m_SessionObj is null) + if (m_SessionObj == null) { return; } @@ -127,7 +127,7 @@ private void DisableClientSideSettings() XmlNamespaceManager nsmgr = new XmlNamespaceManager(resultopxml.NameTable); nsmgr.AddNamespace("cfg", helper.CredSSP_XMLNmsp); XmlNode xNode = resultopxml.SelectSingleNode(helper.CredSSP_SNode, nsmgr); - if (!(xNode is null)) + if (!(xNode == null)) { inputXml = @"false"; } @@ -180,7 +180,7 @@ private void DisableServerSideSettings() { WSManHelper helper = new WSManHelper(this); IWSManSession m_SessionObj = CreateWSManSession(); - if (m_SessionObj is null) + if (m_SessionObj == null) { return; } @@ -195,7 +195,7 @@ private void DisableServerSideSettings() XmlNamespaceManager nsmgr = new XmlNamespaceManager(resultopxml.NameTable); nsmgr.AddNamespace("cfg", helper.Service_CredSSP_XMLNmsp); XmlNode xNode = resultopxml.SelectSingleNode(helper.CredSSP_SNode, nsmgr); - if (!(xNode is null)) + if (!(xNode == null)) { inputXml = string.Format(CultureInfo.InvariantCulture, @"false", @@ -459,7 +459,7 @@ protected override void BeginProcessing() } // DelegateComputer must be specified when Role is client - if (Role.Equals(Client, StringComparison.OrdinalIgnoreCase) && (delegatecomputer is null)) + if (Role.Equals(Client, StringComparison.OrdinalIgnoreCase) && (delegatecomputer == null)) { string message = helper.FormatResourceMsgFromResourcetext("CredSSPClientAndDelegateMustBeSpecified", "DelegateComputer", @@ -496,7 +496,7 @@ private void EnableClientSideSettings() } IWSManSession m_SessionObj = CreateWSManSession(); - if (m_SessionObj is null) + if (m_SessionObj == null) { return; } @@ -507,7 +507,7 @@ private void EnableClientSideSettings() string result = m_SessionObj.Get(helper.CredSSP_RUri, 0); XmlNode node = helper.GetXmlNode(result, helper.CredSSP_SNode, helper.CredSSP_XMLNmsp); - if (node is null) + if (node == null) { InvalidOperationException ex = new InvalidOperationException(); ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null); @@ -574,7 +574,7 @@ private void EnableServerSideSettings() } IWSManSession m_SessionObj = CreateWSManSession(); - if (m_SessionObj is null) + if (m_SessionObj == null) { return; } @@ -587,7 +587,7 @@ private void EnableServerSideSettings() helper.CredSSP_SNode, helper.Service_CredSSP_XMLNmsp); - if (node is null) + if (node == null) { InvalidOperationException ex = new InvalidOperationException(); ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null); @@ -825,7 +825,7 @@ protected override void BeginProcessing() m_SessionObj = (IWSManSession)wsmanObject.CreateSession(null, 0, null); string result = m_SessionObj.Get(helper.CredSSP_RUri, 0); XmlNode node = helper.GetXmlNode(result, helper.CredSSP_SNode, helper.CredSSP_XMLNmsp); - if (node is null) + if (node == null) { InvalidOperationException ex = new InvalidOperationException(); ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null); @@ -848,7 +848,7 @@ protected override void BeginProcessing() // Get the server side settings result = m_SessionObj.Get(helper.Service_CredSSP_Uri, 0); node = helper.GetXmlNode(result, helper.CredSSP_SNode, helper.Service_CredSSP_XMLNmsp); - if (node is null) + if (node == null) { InvalidOperationException ex = new InvalidOperationException(); ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null); diff --git a/src/Microsoft.WSMan.Management/CurrentConfigurations.cs b/src/Microsoft.WSMan.Management/CurrentConfigurations.cs index 9f8830b8009..01ba71f68a7 100644 --- a/src/Microsoft.WSMan.Management/CurrentConfigurations.cs +++ b/src/Microsoft.WSMan.Management/CurrentConfigurations.cs @@ -61,7 +61,7 @@ public XmlDocument RootDocument /// Current server session. public CurrentConfigurations(IWSManSession serverSession) { - if (serverSession is null) + if (serverSession == null) { throw new ArgumentNullException(nameof(serverSession)); } @@ -117,7 +117,7 @@ public void PutConfigurationOnServer(string resourceUri) /// Path with namespace to the node from Root element. Must not end with '/'. public void RemoveOneConfiguration(string pathToNodeFromRoot) { - if (pathToNodeFromRoot is null) + if (pathToNodeFromRoot == null) { throw new ArgumentNullException(nameof(pathToNodeFromRoot)); } @@ -150,7 +150,7 @@ public void RemoveOneConfiguration(string pathToNodeFromRoot) /// Value of the configurations. public void UpdateOneConfiguration(string pathToNodeFromRoot, string configurationName, string configurationValue) { - if (pathToNodeFromRoot is null) + if (pathToNodeFromRoot == null) { throw new ArgumentNullException(nameof(pathToNodeFromRoot)); } @@ -160,7 +160,7 @@ public void UpdateOneConfiguration(string pathToNodeFromRoot, string configurati throw new ArgumentNullException(nameof(configurationName)); } - if (configurationValue is null) + if (configurationValue == null) { throw new ArgumentNullException(nameof(configurationValue)); } @@ -195,7 +195,7 @@ public void UpdateOneConfiguration(string pathToNodeFromRoot, string configurati /// Value of the Node, or Null if no node present. public string GetOneConfiguration(string pathFromRoot) { - if (pathFromRoot is null) + if (pathFromRoot == null) { throw new ArgumentNullException(nameof(pathFromRoot)); } diff --git a/src/Microsoft.WSMan.Management/NewWSManSession.cs b/src/Microsoft.WSMan.Management/NewWSManSession.cs index 56d69ade76f..b2d6719e7e9 100644 --- a/src/Microsoft.WSMan.Management/NewWSManSession.cs +++ b/src/Microsoft.WSMan.Management/NewWSManSession.cs @@ -235,7 +235,7 @@ protected override void BeginProcessing() if (proxyauthentication.Equals(ProxyAuthentication.Basic) || proxyauthentication.Equals(ProxyAuthentication.Digest)) { - if (_proxycredential is null) + if (_proxycredential == null) { InvalidOperationException ex = new InvalidOperationException(helper.GetResourceMsgFromResourcetext("NewWSManSessionOptionCred")); ErrorRecord er = new ErrorRecord(ex, "InvalidOperationException", ErrorCategory.InvalidOperation, null); diff --git a/src/Microsoft.WSMan.Management/WSManConnections.cs b/src/Microsoft.WSMan.Management/WSManConnections.cs index 36aa9ab0dea..4aeb283b81f 100644 --- a/src/Microsoft.WSMan.Management/WSManConnections.cs +++ b/src/Microsoft.WSMan.Management/WSManConnections.cs @@ -346,7 +346,7 @@ public string ComputerName protected override void BeginProcessing() { WSManHelper helper = new WSManHelper(this); - if (computername is null) + if (computername == null) { computername = "localhost"; } diff --git a/src/Microsoft.WSMan.Management/WsManHelper.cs b/src/Microsoft.WSMan.Management/WsManHelper.cs index eaadfb706be..f09ba2bb233 100644 --- a/src/Microsoft.WSMan.Management/WsManHelper.cs +++ b/src/Microsoft.WSMan.Management/WsManHelper.cs @@ -178,7 +178,7 @@ private static string FormatResourceMsgFromResourcetextS( string resourceName, object[] args) { - if (resourceManager is null) + if (resourceManager == null) { throw new ArgumentNullException(nameof(resourceManager)); } @@ -391,7 +391,7 @@ internal string ProcessInput(IWSManEx wsman, string filepath, string operation, string resultString = null; // if file path is given - if (!string.IsNullOrEmpty(filepath) && valueset is null) + if (!string.IsNullOrEmpty(filepath) && valueset == null) { if (!File.Exists(filepath)) { @@ -416,7 +416,7 @@ internal string ProcessInput(IWSManEx wsman, string filepath, string operation, foreach (DictionaryEntry entry in valueset) { parameters = parameters + " 0) { - if (loadedPublicKeyToken is null || requestedPublicKeyToken.Length != loadedPublicKeyToken.Length) + if (loadedPublicKeyToken == null || requestedPublicKeyToken.Length != loadedPublicKeyToken.Length) return false; for (int i = 0; i < requestedPublicKeyToken.Length; i++) diff --git a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs index 868c00addd4..4e572586c98 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs @@ -188,7 +188,7 @@ internal static class CommonEnvVariableNames /// internal static void RemoveTemporaryDirectory() { - if (_tempDirectory is null) + if (_tempDirectory == null) { return; } @@ -252,7 +252,7 @@ public static string SelectProductNameForDirectory(Platform.XDG_Type dirpath) string xdgdatahome = System.Environment.GetEnvironmentVariable("XDG_DATA_HOME"); string xdgcachehome = System.Environment.GetEnvironmentVariable("XDG_CACHE_HOME"); string envHome = System.Environment.GetEnvironmentVariable(CommonEnvVariableNames.Home); - if (envHome is null) + if (envHome == null) { s_tempHomeDir ??= GetTemporaryDirectory(); envHome = s_tempHomeDir; @@ -414,7 +414,7 @@ private static string InternalGetFolderPath(System.Environment.SpecialFolder fol string folderPath = null; #if UNIX string envHome = System.Environment.GetEnvironmentVariable(Platform.CommonEnvVariableNames.Home); - if (envHome is null) + if (envHome == null) { envHome = Platform.GetTemporaryDirectory(); } diff --git a/src/System.Management.Automation/DscSupport/CimDSCParser.cs b/src/System.Management.Automation/DscSupport/CimDSCParser.cs index 9a984d6dba7..58fc81715bb 100644 --- a/src/System.Management.Automation/DscSupport/CimDSCParser.cs +++ b/src/System.Management.Automation/DscSupport/CimDSCParser.cs @@ -73,7 +73,7 @@ public static object ConvertCimInstanceToObject(Type targetType, CimInstance ins MemberInfo[] memberInfo = targetType.GetMember(property.Name, BindingFlags.Public | BindingFlags.Instance); // verify property exists in corresponding class type - if (memberInfo is null || memberInfo.Length > 1 || !(memberInfo[0] is PropertyInfo || memberInfo[0] is FieldInfo)) + if (memberInfo == null || memberInfo.Length > 1 || !(memberInfo[0] is PropertyInfo || memberInfo[0] is FieldInfo)) { errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.PropertyNotDeclaredInPSClass, new object[] { property.Name, className }); var invalidOperationException = new InvalidOperationException(errorMessage); @@ -105,7 +105,7 @@ public static object ConvertCimInstanceToObject(Type targetType, CimInstance ins targetValue = ConvertCimInstanceToObject(memberType, cimPropertyInstance, moduleName); } - if (targetValue is null) + if (targetValue == null) { return null; } @@ -133,7 +133,7 @@ public static object ConvertCimInstanceToObject(Type targetType, CimInstance ins for (int i = 0; i < instanceArray.Length; i++) { var obj = ConvertCimInstanceToObject(elementType, instanceArray[i], moduleName); - if (obj is null) + if (obj == null) { return null; } @@ -151,7 +151,7 @@ public static object ConvertCimInstanceToObject(Type targetType, CimInstance ins break; } - if (targetValue is null) + if (targetValue == null) { errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.ConvertCimPropertyToObjectPropertyFailed, new object[] { property.Name, className }); var invalidOperationException = new InvalidOperationException(errorMessage); @@ -191,7 +191,7 @@ private static object ConvertCimInstanceHashtable(string providerName, CimInstan var key = keyValuePair.CimInstanceProperties["Key"]; var value = keyValuePair.CimInstanceProperties["Value"]; - if (key is null || value is null) + if (key == null || value == null) { errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.InvalidHashtable, providerName); var invalidOperationException = new InvalidOperationException(errorMessage); @@ -296,7 +296,7 @@ public override object Transform(EngineIntrinsics engineIntrinsics, object input return inputData; } - if (engineIntrinsics is null) + if (engineIntrinsics == null) { throw PSTraceSource.NewArgumentNullException(nameof(engineIntrinsics)); } @@ -563,7 +563,7 @@ private static Dictionary ClassCache { get { - if (t_classCache is null) + if (t_classCache == null) { t_classCache = new Dictionary(StringComparer.OrdinalIgnoreCase); } @@ -582,7 +582,7 @@ private static Dictionary> ByClassModuleCache { get { - if (t_byClassModuleCache is null) + if (t_byClassModuleCache == null) { t_byClassModuleCache = new Dictionary>(StringComparer.OrdinalIgnoreCase); } @@ -601,7 +601,7 @@ private static Dictionary> ByClassModuleCache { get { - if (t_byFileClassCache is null) + if (t_byFileClassCache == null) { t_byFileClassCache = new Dictionary>(StringComparer.OrdinalIgnoreCase); } @@ -620,7 +620,7 @@ private static HashSet ScriptKeywordFileCache { get { - if (t_scriptKeywordFileCache is null) + if (t_scriptKeywordFileCache == null) { t_scriptKeywordFileCache = new HashSet(StringComparer.OrdinalIgnoreCase); } @@ -782,7 +782,7 @@ public static void Initialize(Collection errors, List moduleP // Load Regular and DSC PS modules bool importInBoxResourcesImplicitly = false; List modulePaths = new List(); - if (modulePathList is null || modulePathList.Count == 0) + if (modulePathList == null || modulePathList.Count == 0) { modulePaths.Add(Path.Combine(configSystemPath, inboxModulePath)); importInBoxResourcesImplicitly = true; @@ -833,7 +833,7 @@ private static void LoadDSCResourceIntoCache(Collection errors, List< } Tuple moduleInfo = GetModuleInfoHelper(moduleDir, importInBoxResourcesImplicitly, isPsProviderModule: false); - if (moduleInfo is null) + if (moduleInfo == null) { continue; } @@ -1324,7 +1324,7 @@ public static Collection GetCachedKeywords() private static void CreateAndRegisterKeywordFromCimClass(string moduleName, Version moduleVersion, Microsoft.Management.Infrastructure.CimClass cimClass, Dictionary functionsToDefine, DSCResourceRunAsCredential runAsBehavior) { var keyword = CreateKeywordFromCimClass(moduleName, moduleVersion, cimClass, functionsToDefine, runAsBehavior); - if (keyword is null) + if (keyword == null) { return; } @@ -1333,7 +1333,7 @@ private static void CreateAndRegisterKeywordFromCimClass(string moduleName, Vers if (!CacheResourcesFromMultipleModuleVersions && DynamicKeyword.ContainsKeyword(keyword.Keyword)) { var oldKeyword = DynamicKeyword.GetKeyword(keyword.Keyword); - if (oldKeyword.ImplementingModule is null || + if (oldKeyword.ImplementingModule == null || !oldKeyword.ImplementingModule.Equals(moduleName, StringComparison.OrdinalIgnoreCase) || oldKeyword.ImplementingModuleVersion != moduleVersion) { var e = PSTraceSource.NewInvalidOperationException(ParserStrings.DuplicateKeywordDefinition, keyword.Keyword); @@ -1746,7 +1746,7 @@ private static ParseError[] ImportResourcePostParse(DynamicKeywordStatementAst k } } - if (errorList.Count == 0 && moduleNameBindingResult is null && resourceNameBindingResult is null) + if (errorList.Count == 0 && moduleNameBindingResult == null && resourceNameBindingResult == null) { errorList.Add(new ParseError(kwAst.Extent, "ImportDscResourceNeedParams", @@ -1754,7 +1754,7 @@ private static ParseError[] ImportResourcePostParse(DynamicKeywordStatementAst k } // Check here if Version is specified but modulename is not specified - if (moduleVersionBindingResult != null && moduleNameBindingResult is null) + if (moduleVersionBindingResult != null && moduleNameBindingResult == null) { // only add this error again to the error list if resources is not null // if resources and modules are both null we have already added this error in collection @@ -1847,7 +1847,7 @@ private static ParseError[] ImportResourcePostParse(DynamicKeywordStatementAst k // If moduleVersion is specified we have only one module Name in valid scenario // So update it's version property in module specification object that will be used to load modules - if (moduleSpecifications != null && moduleSpecifications[0].Version is null && moduleSpecifications[0].MaximumVersion is null && moduleVersion != null) + if (moduleSpecifications != null && moduleSpecifications[0].Version == null && moduleSpecifications[0].MaximumVersion == null && moduleVersion != null) { moduleSpecifications[0].Version = moduleVersion; } @@ -1879,7 +1879,7 @@ private static ParseError[] ImportResourceCheckSemantics(DynamicKeywordStatement { if (keywordAst.Keyword.Keyword.Equals("Node")) { - if (errorList is null) + if (errorList == null) { errorList = new List(); } @@ -1928,7 +1928,7 @@ private static ParseError[] CheckMandatoryPropertiesPresent(DynamicKeywordStatem } } - if (hashtableAst is null) + if (hashtableAst == null) { // nothing to validate return null; @@ -2024,7 +2024,7 @@ public static void LoadResourcesFromModule(IScriptExtent scriptExtent, } else { - string moduleString = moduleToImport.Version is null + string moduleString = moduleToImport.Version == null ? moduleToImport.Name : string.Format(CultureInfo.CurrentCulture, "<{0}, {1}>", moduleToImport.Name, moduleToImport.Version); @@ -2049,7 +2049,7 @@ public static void LoadResourcesFromModule(IScriptExtent scriptExtent, // When ModuleName only specified, we need to import all resources from that module var resourcesToImport = new List(); - if (resourceNames is null || resourceNames.Length == 0) + if (resourceNames == null || resourceNames.Length == 0) { resourcesToImport.Add("*"); } @@ -2181,7 +2181,7 @@ private static void LoadPowerShellClassResourcesFromModule(PSModuleInfo primaryM bool recurse = true, IScriptExtent extent = null) { - if (primaryModuleInfo._declaredDscResourceExports is null || primaryModuleInfo._declaredDscResourceExports.Count == 0) + if (primaryModuleInfo._declaredDscResourceExports == null || primaryModuleInfo._declaredDscResourceExports.Count == 0) { return; } @@ -2197,7 +2197,7 @@ private static void LoadPowerShellClassResourcesFromModule(PSModuleInfo primaryM { AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += reh; var assembly = moduleInfo.ImplementingAssembly; - if (assembly is null && moduleInfo.Path != null) + if (assembly == null && moduleInfo.Path != null) { try { @@ -2315,7 +2315,7 @@ internal static string MapTypeNameToMofType(ITypeName typeName, string memberNam propTypeName = typeName as TypeName; } - if (propTypeName is null || propTypeName._typeDefinitionAst is null) + if (propTypeName == null || propTypeName._typeDefinitionAst == null) { throw new NotSupportedException(string.Format( CultureInfo.InvariantCulture, @@ -2372,7 +2372,7 @@ private static void GenerateMofForAst(TypeDefinitionAst typeAst, StringBuilder s if (tc != null) { b = tc.TypeName.GetReflectionType(); - if (b is null) + if (b == null) { var td = tc.TypeName as TypeName; if (td != null && td._typeDefinitionAst != null) @@ -2450,7 +2450,7 @@ public static bool GetResourceMethodsLinePosition(PSModuleInfo moduleInfo, strin { resourceMethodsLinePosition = null; resourceFilePath = string.Empty; - if (moduleInfo is null || string.IsNullOrEmpty(resourceName)) + if (moduleInfo == null || string.IsNullOrEmpty(resourceName)) { return false; } @@ -2500,13 +2500,13 @@ private static void ProcessMembers(StringBuilder sb, List embeddedInstan { var property = member as PropertyMemberAst; - if (property is null || property.IsStatic || + if (property == null || property.IsStatic || property.Attributes.All(a => a.TypeName.GetReflectionAttributeType() != typeof(DscPropertyAttribute))) { continue; } - var memberType = property.PropertyType is null + var memberType = property.PropertyType == null ? typeof(object) : property.PropertyType.TypeName.GetReflectionType(); @@ -2725,7 +2725,7 @@ private static bool AreQualifiersSame(CimReadOnlyKeyedCollection o { // Find the qualifier in new class var newQual = newQualifiers[qual.Name]; - if (newQual is null) + if (newQual == null) { return false; } @@ -2736,8 +2736,8 @@ private static bool AreQualifiersSame(CimReadOnlyKeyedCollection o return false; } - if ((qual.Value is null && newQual.Value != null) || - (qual.Value != null && newQual.Value is null) || + if ((qual.Value == null && newQual.Value != null) || + (qual.Value != null && newQual.Value == null) || (qual.Value != null && newQual.Value != null && !string.Equals(qual.Value.ToString(), newQual.Value.ToString(), StringComparison.OrdinalIgnoreCase) ) @@ -2761,7 +2761,7 @@ private static bool ArePropertiesSame(CimReadOnlyKeyedCollection embeddedInstanceTy while (embeddedInstanceTypes.Count > 0) { - if (nestedSb is null) + if (nestedSb == null) { nestedSb = new StringBuilder(); } @@ -3079,14 +3079,14 @@ private static void ProcessMembers(Type type, StringBuilder sb, List emb Type memberType; var propertyInfo = member as PropertyInfo; - if (propertyInfo is null) + if (propertyInfo == null) { var fieldInfo = (FieldInfo)member; memberType = fieldInfo.FieldType; } else { - if (propertyInfo.GetSetMethod() is null) + if (propertyInfo.GetSetMethod() == null) { continue; } @@ -3219,12 +3219,12 @@ public static bool ImportCimKeywordsFromModule(PSModuleInfo module, string resou /// public static bool ImportCimKeywordsFromModule(PSModuleInfo module, string resourceName, out string schemaFilePath, Dictionary functionsToDefine, Collection errors) { - if (module is null) + if (module == null) { throw PSTraceSource.NewArgumentNullException(nameof(module)); } - if (resourceName is null) + if (resourceName == null) { throw PSTraceSource.NewArgumentNullException(nameof(resourceName)); } @@ -3331,12 +3331,12 @@ public static bool ImportScriptKeywordsFromModule(PSModuleInfo module, string re /// public static bool ImportScriptKeywordsFromModule(PSModuleInfo module, string resourceName, out string schemaFilePath, Dictionary functionsToDefine) { - if (module is null) + if (module == null) { throw PSTraceSource.NewArgumentNullException(nameof(module)); } - if (resourceName is null) + if (resourceName == null) { throw PSTraceSource.NewArgumentNullException(nameof(resourceName)); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseCommand.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseCommand.cs index a653a666e01..e03b4ae61eb 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseCommand.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseCommand.cs @@ -17,7 +17,7 @@ internal sealed class TerminatingErrorContext { internal TerminatingErrorContext(PSCmdlet command) { - if (command is null) + if (command == null) throw PSTraceSource.NewArgumentNullException(nameof(command)); _command = command; } @@ -72,7 +72,7 @@ internal void AddNamedParameter(string parameterName, object parameterValue) /// Array of objects out of the success pipeline. internal Array Process(object o) { - if (_pp is null) + if (_pp == null) { // if this is the first call, we need to initialize the // pipeline underneath @@ -88,7 +88,7 @@ internal Array Process(object o) /// Array of objects out of the success pipeline. internal Array ShutDown() { - if (_pp is null) + if (_pp == null) { // if Process() never got called, no sub pipeline // ever got created, hence we just return an empty array @@ -122,7 +122,7 @@ private void DelayedInternalInitialize() /// public void Dispose() { - if (_pp is null) + if (_pp == null) return; _pp.Dispose(); @@ -259,7 +259,7 @@ protected virtual void Dispose(bool disposing) /// protected virtual void InternalDispose() { - if (this.implementation is null) + if (this.implementation == null) return; this.implementation.Dispose(); diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommand.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommand.cs index c2169059821..ffccf13f4e1 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommand.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommand.cs @@ -96,11 +96,11 @@ internal override void ProcessRecord() _typeInfoDataBase = this.OuterCmdlet().Context.FormatDBManager.GetTypeInfoDataBase(); PSObject so = this.ReadObject(); - if (so is null || so == AutomationNull.Value) + if (so == null || so == AutomationNull.Value) return; IEnumerable e = PSObjectHelper.GetEnumerable(so); - if (e is null) + if (e == null) { ProcessObject(so); return; @@ -297,7 +297,7 @@ private bool ShouldProcessOutOfBand { get { - if (_shape == FormatShape.Undefined || _parameters is null) + if (_shape == FormatShape.Undefined || _parameters == null) { return true; } @@ -390,7 +390,7 @@ protected void WriteInternalErrorMessage(string message) private void WriteErrorRecords(List errorRecordList) { - if (errorRecordList is null) + if (errorRecordList == null) return; // NOTE: for the time being we directly process error records. diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommandParameters.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommandParameters.cs index 79375b70ef9..cdd60637a7a 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommandParameters.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommandParameters.cs @@ -169,7 +169,7 @@ internal override object Verify(object val, TerminatingErrorContext invocationContext, bool originalParameterWasHashTable) { - if (val is null) + if (val == null) { throw PSTraceSource.NewArgumentNullException(nameof(val)); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs index 2b3716eb7a3..bb8305b2fdc 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs @@ -46,7 +46,7 @@ internal override void ProcessRecord() { PSObject so = this.ReadObject(); - if (so is null || so == AutomationNull.Value) + if (so == null || so == AutomationNull.Value) return; // try to process the object @@ -129,7 +129,7 @@ private bool ProcessObject(PSObject so) } // instantiate the cache if not done yet - if (_cache is null) + if (_cache == null) { _cache = new FormattedObjectsCache(this.LineOutput.RequiresBuffering); } @@ -184,7 +184,7 @@ private FormatShape ActiveFormattingShape FormatShape shape = FormatShape.Table; // default FormatOutputContext foc = this.FormatContext; - if (foc is null || foc.Data.shapeInfo is null) + if (foc == null || foc.Data.shapeInfo == null) return shape; if (foc.Data.shapeInfo is TableHeaderInfo) @@ -368,7 +368,7 @@ private void ValidateCurrentFormattingState(FormattingState expectedFormattingSt /// Array of objects returned by the preprocessing step. private Array ApplyFormatting(object o) { - if (_command is null) + if (_command == null) { _command = new CommandWrapper(); _command.Initialize(this.OuterCmdlet().Context, "format-default", typeof(FormatDefaultCommand)); @@ -506,12 +506,12 @@ private void ProcessGroupEnd(GroupEndData ge, FormatMessagesContextManager.Outpu private void ProcessPayload(FormatEntryData fed, FormatMessagesContextManager.OutputContext c) { // we assume FormatEntryData as a standard wrapper - if (fed is null) + if (fed == null) { PSTraceSource.NewArgumentNullException(nameof(fed)); } - if (fed.formatEntryInfo is null) + if (fed.formatEntryInfo == null) { PSTraceSource.NewArgumentNullException("fed.formatEntryInfo"); } @@ -521,7 +521,7 @@ private void ProcessPayload(FormatEntryData fed, FormatMessagesContextManager.Ou { _lo.WriteStream = fed.writeStream; - if (c is null) + if (c == null) { ProcessOutOfBandPayload(fed); } @@ -607,7 +607,7 @@ private ShapeInfo ShapeInfoOnFormatContext { FormatOutputContext foc = this.FormatContext; - if (foc is null) + if (foc == null) return null; return foc.Data.shapeInfo; @@ -1390,7 +1390,7 @@ internal override void Initialize() internal override void ProcessPayload(FormatEntryData fed) { ComplexViewEntry cve = fed.formatEntryInfo as ComplexViewEntry; - if (cve is null || cve.formatValueList is null) + if (cve == null || cve.formatValueList == null) return; _writer.WriteObject(cve.formatValueList); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs b/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs index 10891fb400c..74031dc515c 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs @@ -416,7 +416,7 @@ private static StringCollection GenerateLinesWithoutWordWrap(DisplayCells displa for (int k = 0; k < lines.Length; k++) { - if (lines[k] is null || displayCells.Length(lines[k]) <= firstLineLen) + if (lines[k] == null || displayCells.Length(lines[k]) <= firstLineLen) { // we do not need to split further, just add retVal.Add(lines[k]); @@ -532,7 +532,7 @@ private static StringCollection GenerateLinesWithWordWrap(DisplayCells displayCe for (int k = 0; k < lines.Length; k++) { - if (lines[k] is null || displayCells.Length(lines[k]) <= firstLineLen) + if (lines[k] == null || displayCells.Length(lines[k]) <= firstLineLen) { // we do not need to split further, just add retVal.Add(lines[k]); diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/FormatTable.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/FormatTable.cs index 00c8089a825..6b647bd0912 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/FormatTable.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/FormatTable.cs @@ -85,7 +85,7 @@ internal FormatTableLoadException(ConcurrentBag loadErrors) : protected FormatTableLoadException(SerializationInfo info, StreamingContext context) : base(info, context) { - if (info is null) + if (info == null) { throw new PSArgumentNullException(nameof(info)); } @@ -112,7 +112,7 @@ protected FormatTableLoadException(SerializationInfo info, StreamingContext cont [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) { throw new PSArgumentNullException(nameof(info)); } @@ -206,7 +206,7 @@ public FormatTable(IEnumerable formatFiles) : this(formatFiles, null, nu /// public void AppendFormatData(IEnumerable formatData) { - if (formatData is null) + if (formatData == null) throw PSTraceSource.NewArgumentNullException(nameof(formatData)); _formatDBMgr.AddFormatData(formatData, false); } @@ -225,7 +225,7 @@ public void AppendFormatData(IEnumerable formatData) /// public void PrependFormatData(IEnumerable formatData) { - if (formatData is null) + if (formatData == null) throw PSTraceSource.NewArgumentNullException(nameof(formatData)); _formatDBMgr.AddFormatData(formatData, true); } @@ -251,7 +251,7 @@ public void PrependFormatData(IEnumerable formatData) /// internal FormatTable(IEnumerable formatFiles, AuthorizationManager authorizationManager, PSHost host) { - if (formatFiles is null) + if (formatFiles == null) { throw PSTraceSource.NewArgumentNullException(nameof(formatFiles)); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData.cs index 348aa30bba5..64af2244fb8 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData.cs @@ -79,7 +79,7 @@ internal T Value /* set { - if (_value is null) + if (_value == null) { this._value = value; } @@ -636,7 +636,7 @@ public ExtendedTypeDefinition(string typeName, IEnumerable { if (string.IsNullOrEmpty(typeName)) throw PSTraceSource.NewArgumentNullException(nameof(typeName)); - if (viewDefinitions is null) + if (viewDefinitions == null) throw PSTraceSource.NewArgumentNullException(nameof(viewDefinitions)); TypeNames.Add(typeName); @@ -692,7 +692,7 @@ public FormatViewDefinition(string name, PSControl control) { if (string.IsNullOrEmpty(name)) throw PSTraceSource.NewArgumentNullException(nameof(name)); - if (control is null) + if (control == null) throw PSTraceSource.NewArgumentNullException(nameof(control)); Name = name; @@ -725,7 +725,7 @@ public abstract class PSControl internal virtual bool SafeForExport() { - return GroupBy is null || GroupBy.IsSafeForExport(); + return GroupBy == null || GroupBy.IsSafeForExport(); } internal virtual bool CompatibleWithOldPowerShell() @@ -734,7 +734,7 @@ internal virtual bool CompatibleWithOldPowerShell() // PowerShell, but that's still wrong. // OutOfBand is also ignored by old PowerShell, but it's of less importance. - return GroupBy is null; + return GroupBy == null; } } @@ -761,8 +761,8 @@ public sealed class PSControlGroupBy internal bool IsSafeForExport() { - return (Expression is null || Expression.SafeForExport()) && - (CustomControl is null || CustomControl.SafeForExport()); + return (Expression == null || Expression.SafeForExport()) && + (CustomControl == null || CustomControl.SafeForExport()); } internal static PSControlGroupBy Get(GroupBy groupBy) @@ -799,7 +799,7 @@ internal DisplayEntry() { } public DisplayEntry(string value, DisplayEntryValueType type) { if (string.IsNullOrEmpty(value)) - if (value is null || type == DisplayEntryValueType.Property) + if (value == null || type == DisplayEntryValueType.Property) throw PSTraceSource.NewArgumentNullException(nameof(value)); Value = value; @@ -818,7 +818,7 @@ internal DisplayEntry(ExpressionToken expression) ValueType = expression.isScriptBlock ? DisplayEntryValueType.ScriptBlock : DisplayEntryValueType.Property; if (string.IsNullOrEmpty(Value)) - if (Value is null || ValueType == DisplayEntryValueType.Property) + if (Value == null || ValueType == DisplayEntryValueType.Property) throw PSTraceSource.NewArgumentNullException("value"); } @@ -886,7 +886,7 @@ internal static EntrySelectedBy Get(List references) { if (tr.conditionToken != null) { - if (result.SelectionCondition is null) result.SelectionCondition = new List(); + if (result.SelectionCondition == null) result.SelectionCondition = new List(); result.SelectionCondition.Add(new DisplayEntry(tr.conditionToken)); continue; @@ -895,7 +895,7 @@ internal static EntrySelectedBy Get(List references) if (tr is TypeGroupReference) continue; - if (result.TypeNames is null) result.TypeNames = new List(); + if (result.TypeNames == null) result.TypeNames = new List(); result.TypeNames.Add(tr.name); } @@ -906,7 +906,7 @@ internal static EntrySelectedBy Get(List references) internal bool SafeForExport() { - if (SelectionCondition is null) + if (SelectionCondition == null) return true; foreach (var cond in SelectionCondition) @@ -921,7 +921,7 @@ internal bool SafeForExport() internal bool CompatibleWithOldPowerShell() { // Old versions of PowerShell know nothing about selection conditions. - return SelectionCondition is null || SelectionCondition.Count == 0; + return SelectionCondition == null || SelectionCondition.Count == 0; } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Complex.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Complex.cs index 959c2062d22..d3290c18752 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Complex.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Complex.cs @@ -160,7 +160,7 @@ internal bool SafeForExport() return false; } - return SelectedBy is null || SelectedBy.SafeForExport(); + return SelectedBy == null || SelectedBy.SafeForExport(); } } @@ -264,9 +264,9 @@ internal CustomItemExpression() { } internal override bool SafeForExport() { - return (ItemSelectionCondition is null || ItemSelectionCondition.SafeForExport()) && - (Expression is null || Expression.SafeForExport()) && - (CustomControl is null || CustomControl.SafeForExport()); + return (ItemSelectionCondition == null || ItemSelectionCondition.SafeForExport()) && + (Expression == null || Expression.SafeForExport()) && + (CustomControl == null || CustomControl.SafeForExport()); } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_List.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_List.cs index b70afe7d2f8..6025acfff44 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_List.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_List.cs @@ -172,7 +172,7 @@ internal ListControl(ListControlBody listcontrolbody, ViewDefinition viewDefinit public ListControl(IEnumerable entries) : this() { - if (entries is null) + if (entries == null) throw PSTraceSource.NewArgumentNullException(nameof(entries)); foreach (ListControlEntry entry in entries) { @@ -208,7 +208,7 @@ public List SelectedBy { get { - if (EntrySelectedBy is null) + if (EntrySelectedBy == null) EntrySelectedBy = new EntrySelectedBy { TypeNames = new List() }; return EntrySelectedBy.TypeNames; } @@ -241,7 +241,7 @@ internal ListControlEntry(ListControlEntryDefinition entrydefn) public ListControlEntry(IEnumerable listItems) : this() { - if (listItems is null) + if (listItems == null) throw PSTraceSource.NewArgumentNullException(nameof(listItems)); foreach (ListControlEntryItem item in listItems) { @@ -252,9 +252,9 @@ public ListControlEntry(IEnumerable listItems) /// Public constructor for ListControlEntry public ListControlEntry(IEnumerable listItems, IEnumerable selectedBy) { - if (listItems is null) + if (listItems == null) throw PSTraceSource.NewArgumentNullException(nameof(listItems)); - if (selectedBy is null) + if (selectedBy == null) throw PSTraceSource.NewArgumentNullException(nameof(selectedBy)); EntrySelectedBy = new EntrySelectedBy { TypeNames = new List(selectedBy) }; @@ -272,7 +272,7 @@ internal bool SafeForExport() return false; } - return EntrySelectedBy is null || EntrySelectedBy.SafeForExport(); + return EntrySelectedBy == null || EntrySelectedBy.SafeForExport(); } internal bool CompatibleWithOldPowerShell() @@ -283,7 +283,7 @@ internal bool CompatibleWithOldPowerShell() return false; } - return EntrySelectedBy is null || EntrySelectedBy.CompatibleWithOldPowerShell(); + return EntrySelectedBy == null || EntrySelectedBy.CompatibleWithOldPowerShell(); } } @@ -350,13 +350,13 @@ public ListControlEntryItem(string label, DisplayEntry entry) internal bool SafeForExport() { return DisplayEntry.SafeForExport() && - (ItemSelectionCondition is null || ItemSelectionCondition.SafeForExport()); + (ItemSelectionCondition == null || ItemSelectionCondition.SafeForExport()); } internal bool CompatibleWithOldPowerShell() { // Old versions of PowerShell know nothing about ItemSelectionCondition. - return ItemSelectionCondition is null; + return ItemSelectionCondition == null; } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Table.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Table.cs index fd38fee0be9..b9d1e897068 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Table.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Table.cs @@ -290,7 +290,7 @@ internal TableControl(TableControlBody tcb, ViewDefinition viewDefinition) : thi /// public TableControl(TableControlRow tableControlRow) : this() { - if (tableControlRow is null) + if (tableControlRow == null) throw PSTraceSource.NewArgumentNullException("tableControlRows"); this.Rows.Add(tableControlRow); @@ -303,9 +303,9 @@ public TableControl(TableControlRow tableControlRow) : this() /// public TableControl(TableControlRow tableControlRow, IEnumerable tableControlColumnHeaders) : this() { - if (tableControlRow is null) + if (tableControlRow == null) throw PSTraceSource.NewArgumentNullException("tableControlRows"); - if (tableControlColumnHeaders is null) + if (tableControlColumnHeaders == null) throw PSTraceSource.NewArgumentNullException(nameof(tableControlColumnHeaders)); this.Rows.Add(tableControlRow); @@ -466,7 +466,7 @@ internal TableControlRow(TableRowDefinition rowdefinition) : this() /// Public constructor for TableControlRow. public TableControlRow(IEnumerable columns) : this() { - if (columns is null) + if (columns == null) throw PSTraceSource.NewArgumentNullException(nameof(columns)); foreach (TableControlColumn column in columns) { @@ -488,7 +488,7 @@ internal bool SafeForExport() internal bool CompatibleWithOldPowerShell() { // Old versions of PowerShell don't support multiple row definitions. - return SelectedBy is null; + return SelectedBy == null; } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Wide.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Wide.cs index 3b59985cf5c..05e3e79923b 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Wide.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Wide.cs @@ -144,7 +144,7 @@ internal WideControl(WideControlBody widecontrolbody, ViewDefinition viewDefinit /// Public constructor for WideControl public WideControl(IEnumerable wideEntries) : this() { - if (wideEntries is null) + if (wideEntries == null) throw PSTraceSource.NewArgumentNullException(nameof(wideEntries)); foreach (WideControlEntryItem entryItem in wideEntries) @@ -156,7 +156,7 @@ public WideControl(IEnumerable wideEntries) : this() /// Public constructor for WideControl public WideControl(IEnumerable wideEntries, uint columns) : this() { - if (wideEntries is null) + if (wideEntries == null) throw PSTraceSource.NewArgumentNullException(nameof(wideEntries)); foreach (WideControlEntryItem entryItem in wideEntries) @@ -187,7 +187,7 @@ public List SelectedBy { get { - if (EntrySelectedBy is null) + if (EntrySelectedBy == null) EntrySelectedBy = new EntrySelectedBy { TypeNames = new List() }; return EntrySelectedBy.TypeNames; } @@ -223,7 +223,7 @@ internal WideControlEntryItem(WideControlEntryDefinition definition) : this() /// public WideControlEntryItem(DisplayEntry entry) : this() { - if (entry is null) + if (entry == null) throw PSTraceSource.NewArgumentNullException(nameof(entry)); this.DisplayEntry = entry; } @@ -233,9 +233,9 @@ public WideControlEntryItem(DisplayEntry entry) : this() /// public WideControlEntryItem(DisplayEntry entry, IEnumerable selectedBy) : this() { - if (entry is null) + if (entry == null) throw PSTraceSource.NewArgumentNullException(nameof(entry)); - if (selectedBy is null) + if (selectedBy == null) throw PSTraceSource.NewArgumentNullException(nameof(selectedBy)); this.DisplayEntry = entry; @@ -244,14 +244,14 @@ public WideControlEntryItem(DisplayEntry entry, IEnumerable selectedBy) internal bool SafeForExport() { - return DisplayEntry.SafeForExport() && (EntrySelectedBy is null || EntrySelectedBy.SafeForExport()); + return DisplayEntry.SafeForExport() && (EntrySelectedBy == null || EntrySelectedBy.SafeForExport()); } internal bool CompatibleWithOldPowerShell() { // Old versions of PowerShell don't know anything about FormatString or conditions in EntrySelectedBy. - return FormatString is null && - (EntrySelectedBy is null || EntrySelectedBy.CompatibleWithOldPowerShell()); + return FormatString == null && + (EntrySelectedBy == null || EntrySelectedBy.CompatibleWithOldPowerShell()); } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs index 5e316c0a2df..52e1043cb2c 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs @@ -57,7 +57,7 @@ private string GetStringHelper(StringResourceReference resourceReference, out Lo // we do not have an assembly, we try to load it bool foundInGac; loadResult.a = LoadAssemblyFromResourceReference(resourceReference, out foundInGac); - if (loadResult.a is null) + if (loadResult.a == null) { loadResult.status = AssemblyBindingStatus.NotFound; } @@ -72,7 +72,7 @@ private string GetStringHelper(StringResourceReference resourceReference, out Lo bindingStatus = loadResult.status; - if (loadResult.a is null) + if (loadResult.a == null) { // we failed the assembly loading result = LoadingResult.AssemblyNotFound; @@ -87,7 +87,7 @@ private string GetStringHelper(StringResourceReference resourceReference, out Lo try { string val = ResourceManagerCache.GetResourceString(loadResult.a, resourceReference.baseName, resourceReference.resourceId); - if (val is null) + if (val == null) { result = LoadingResult.StringNotFound; return null; diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs index 38f297c6717..985561670f8 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs @@ -346,7 +346,7 @@ internal bool LoadFromFile( // data base to an empty instance lock (databaseLock) { - if (Database is null) + if (Database == null) { TypeInfoDataBase tempDataBase = new TypeInfoDataBase(); AddPreLoadIntrinsics(tempDataBase); @@ -488,7 +488,7 @@ private static bool ProcessBuiltin( List logEntries, ref bool success) { - if (s_builtinGenerators is null) + if (s_builtinGenerators == null) { var builtInGenerators = new Dictionary>(StringComparer.OrdinalIgnoreCase); diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs index 59b17ec30eb..ec0c40736fb 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs @@ -125,7 +125,7 @@ internal object BestMatch { get { - if (_bestMatchItem is null) + if (_bestMatchItem == null) return null; return _bestMatchItem.Item; } @@ -221,7 +221,7 @@ private int MatchTypeIndex(string typeName, PSObject currentObject, PSPropertyEx private bool MatchCondition(PSObject currentObject, PSPropertyExpression ex) { - if (ex is null) + if (ex == null) return true; PSPropertyExpressionResult expressionResult; @@ -392,7 +392,7 @@ internal static ViewDefinition GetOutOfBandView(PSPropertyExpressionFactory expr // we were unable to find a best match so far..try // to get rid of Deserialization prefix and see if a // match can be found. - if (result is null) + if (result == null) { Collection typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames); if (typesWithoutPrefix != null) @@ -409,7 +409,7 @@ private static ViewDefinition GetView(PSPropertyExpressionFactory expressionFact TypeMatch match = new TypeMatch(expressionFactory, db, typeNames); foreach (ViewDefinition vd in db.viewDefinitionsSection.viewDefinitionList) { - if (vd is null || mainControlType != vd.mainControl.GetType()) + if (vd == null || mainControlType != vd.mainControl.GetType()) { ActiveTracer.WriteLine( "NOT MATCH {0} NAME: {1}", @@ -425,7 +425,7 @@ private static ViewDefinition GetView(PSPropertyExpressionFactory expressionFact continue; } - if (vd.appliesTo is null) + if (vd.appliesTo == null) { ActiveTracer.WriteLine( "NOT MATCH {0} NAME: {1} No applicable types", @@ -467,7 +467,7 @@ private static ViewDefinition GetView(PSPropertyExpressionFactory expressionFact // we were unable to find a best match so far..try // to get rid of Deserialization prefix and see if a // match can be found. - if (result is null) + if (result == null) { Collection typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames); if (typesWithoutPrefix != null) @@ -522,7 +522,7 @@ private static ViewDefinition GetDefaultView(PSPropertyExpressionFactory express foreach (ViewDefinition vd in db.viewDefinitionsSection.viewDefinitionList) { - if (vd is null) + if (vd == null) continue; if (IsOutOfBandView(vd)) @@ -533,7 +533,7 @@ private static ViewDefinition GetDefaultView(PSPropertyExpressionFactory express continue; } - if (vd.appliesTo is null) + if (vd.appliesTo == null) { ActiveTracer.WriteLine( "NOT MATCH {0} NAME: {1} No applicable types", @@ -562,7 +562,7 @@ private static ViewDefinition GetDefaultView(PSPropertyExpressionFactory express // we were unable to find a best match so far..try // to get rid of Deserialization prefix and see if a // match can be found. - if (result is null) + if (result == null) { Collection typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames); if (typesWithoutPrefix != null) @@ -604,13 +604,13 @@ internal static AppliesTo GetAllApplicableTypes(TypeInfoDataBase db, AppliesTo a // check if we have a type group reference TypeGroupReference tgr = r as TypeGroupReference; - if (tgr is null) + if (tgr == null) continue; // find the type group definition the reference points to TypeGroupDefinition tgd = FindGroupDefinition(db, tgr.name); - if (tgd is null) + if (tgd == null) continue; // we found the group, go over it diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs index 018456d7d0f..79bcbd61dca 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs @@ -192,16 +192,16 @@ internal bool LoadXmlFile( PSHost host, bool preValidated) { - if (info is null) + if (info == null) throw PSTraceSource.NewArgumentNullException(nameof(info)); - if (info.filePath is null) + if (info.filePath == null) throw PSTraceSource.NewArgumentNullException("info.filePath"); - if (db is null) + if (db == null) throw PSTraceSource.NewArgumentNullException(nameof(db)); - if (expressionFactory is null) + if (expressionFactory == null) throw PSTraceSource.NewArgumentNullException(nameof(expressionFactory)); if (SecuritySupport.IsProductBinary(info.filePath)) @@ -228,7 +228,7 @@ internal bool LoadXmlFile( SetLoadingInfoIsFullyTrusted(isFullyTrusted); } - if (newDocument is null) + if (newDocument == null) { return false; } @@ -287,13 +287,13 @@ internal bool LoadFormattingData( bool isBuiltInFormatData, bool isForHelp) { - if (typeDefinition is null) + if (typeDefinition == null) throw PSTraceSource.NewArgumentNullException(nameof(typeDefinition)); - if (typeDefinition.TypeName is null) + if (typeDefinition.TypeName == null) throw PSTraceSource.NewArgumentNullException("typeDefinition.TypeName"); - if (db is null) + if (db == null) throw PSTraceSource.NewArgumentNullException(nameof(db)); - if (expressionFactory is null) + if (expressionFactory == null) throw PSTraceSource.NewArgumentNullException(nameof(expressionFactory)); this.expressionFactory = expressionFactory; @@ -336,10 +336,10 @@ internal bool LoadFormattingData( /// Instance of the databaseto load into. private void LoadData(XmlDocument doc, TypeInfoDataBase db) { - if (doc is null) + if (doc == null) throw PSTraceSource.NewArgumentNullException(nameof(doc)); - if (db is null) + if (db == null) throw PSTraceSource.NewArgumentNullException(nameof(db)); // create a new instance of the database to be loaded @@ -424,10 +424,10 @@ private void LoadData(XmlDocument doc, TypeInfoDataBase db) /// True if the formatter is used for formatting help objects. private void LoadData(ExtendedTypeDefinition typeDefinition, TypeInfoDataBase db, bool isForHelpOutput) { - if (typeDefinition is null) + if (typeDefinition == null) throw PSTraceSource.NewArgumentNullException("viewDefinition"); - if (db is null) + if (db == null) throw PSTraceSource.NewArgumentNullException(nameof(db)); int viewIndex = 0; @@ -495,7 +495,7 @@ private ViewDefinition LoadViewFromObjectModel(List typeNames, FormatVie } // Check if the PSControl is successfully loaded - if (view.mainControl is null) + if (view.mainControl == null) { return null; } @@ -552,7 +552,7 @@ private ControlBase LoadTableControlFromObjectModel(TableControl table, int view LoadRowEntriesSectionFromObjectModel(tableBody, table.Rows, viewIndex, typeName); // When error occurs while loading rowEntry, the tableBody.defaultDefinition would be null - if (tableBody.defaultDefinition is null) + if (tableBody.defaultDefinition == null) { return null; } @@ -629,7 +629,7 @@ private void LoadRowEntriesSectionFromObjectModel(TableControlBody tableBody, Li { LoadColumnEntriesFromObjectModel(trd, row.Columns, viewIndex, typeName); // trd.rowItemDefinitionList is null, it means there was a failure - if (trd.rowItemDefinitionList is null) + if (trd.rowItemDefinitionList == null) { tableBody.defaultDefinition = null; return; @@ -648,7 +648,7 @@ private void LoadRowEntriesSectionFromObjectModel(TableControlBody tableBody, Li } // rowEntries must not be empty - if (tableBody.defaultDefinition is null) + if (tableBody.defaultDefinition == null) { this.ReportErrorForLoadingFromObjectModel( StringUtil.Format(FormatAndOutXmlLoadingStrings.NoDefaultShapeEntryInFormattingData, typeName, viewIndex, XmlTags.TableRowEntryNode), typeName); @@ -675,7 +675,7 @@ private void LoadColumnEntriesFromObjectModel(TableRowDefinition trd, List LoadEnumerableExpansionDirectiveList( if (MatchNodeName(n, XmlTags.EnumerableExpansionNode)) { EnumerableExpansionDirective eed = LoadEnumerableExpansionDirective(n, k++); - if (eed is null) + if (eed == null) { // Error at XPath {0} in file {1}: {2} failed to load. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.LoadTagFailed, ComputeCurrentXPath(), FilePath, XmlTags.EnumerableExpansionNode)); @@ -1298,7 +1298,7 @@ private EnumerableExpansionDirective LoadEnumerableExpansionDirective(XmlNode di expandNodeFound = true; string s = GetMandatoryInnerText(n); - if (s is null) + if (s == null) { return null; // fatal } @@ -1589,7 +1589,7 @@ private TypeOrGroupReference LoadSelectionConditionNode(XmlNode selectionConditi return null; // fatal error } - if (retVal is null) + if (retVal == null) { // missing mandatory node this.ReportMissingNodes(new string[] { XmlTags.SelectionSetNameNode, XmlTags.TypeNameNode }); @@ -1600,7 +1600,7 @@ private TypeOrGroupReference LoadSelectionConditionNode(XmlNode selectionConditi { // mandatory node retVal.conditionToken = expressionMatch.GenerateExpressionToken(); - if (retVal.conditionToken is null) + if (retVal.conditionToken == null) { return null; // fatal error } @@ -1670,7 +1670,7 @@ private GroupBy LoadGroupBySection(XmlNode groupByNode) labelFound = true; labelTextToken = LoadLabel(n); - if (labelTextToken is null) + if (labelTextToken == null) { return null; // fatal error } @@ -1711,7 +1711,7 @@ private GroupBy LoadGroupBySection(XmlNode groupByNode) { // we add only if we encountered one, since it's not mandatory ExpressionToken expression = expressionMatch.GenerateExpressionToken(); - if (expression is null) + if (expression == null) { return null; // fatal error } @@ -1754,7 +1754,7 @@ private TextToken LoadTextToken(XmlNode n) // inner text is mandatory tt.text = this.GetMandatoryInnerText(n); - if (tt.text is null) + if (tt.text == null) return null; return tt; @@ -1765,7 +1765,7 @@ private bool LoadStringResourceReference(XmlNode n, out StringResourceReference resource = null; XmlElement e = n as XmlElement; - if (e is null) + if (e == null) { // Error at XPath {0} in file {1}: Node should be an XmlElement. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.NonXmlElementNode, ComputeCurrentXPath(), FilePath)); @@ -1793,19 +1793,19 @@ private StringResourceReference LoadResourceAttributes(XmlAttributeCollection at if (MatchAttributeName(a, XmlTags.AssemblyNameAttribute)) { resource.assemblyName = GetMandatoryAttributeValue(a); - if (resource.assemblyName is null) + if (resource.assemblyName == null) return null; } else if (MatchAttributeName(a, XmlTags.BaseNameAttribute)) { resource.baseName = GetMandatoryAttributeValue(a); - if (resource.baseName is null) + if (resource.baseName == null) return null; } else if (MatchAttributeName(a, XmlTags.ResourceIdAttribute)) { resource.resourceId = GetMandatoryAttributeValue(a); - if (resource.resourceId is null) + if (resource.resourceId == null) return null; } else @@ -1816,19 +1816,19 @@ private StringResourceReference LoadResourceAttributes(XmlAttributeCollection at } // make sure we got all the attributes, since allof them are mandatory - if (resource.assemblyName is null) + if (resource.assemblyName == null) { ReportMissingAttribute(XmlTags.AssemblyNameAttribute); return null; } - if (resource.baseName is null) + if (resource.baseName == null) { ReportMissingAttribute(XmlTags.BaseNameAttribute); return null; } - if (resource.resourceId is null) + if (resource.resourceId == null) { ReportMissingAttribute(XmlTags.ResourceIdAttribute); return null; @@ -1971,7 +1971,7 @@ internal bool ProcessNode(XmlNode n) _token = new ExpressionToken(); _token.expressionValue = _loader.GetMandatoryInnerText(n); - if (_token.expressionValue is null) + if (_token.expressionValue == null) { // Error at XPath {0} in file {1}: Missing property. _loader.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.NoProperty, _loader.ComputeCurrentXPath(), _loader.FilePath)); @@ -1995,7 +1995,7 @@ internal bool ProcessNode(XmlNode n) _token = new ExpressionToken(); _token.isScriptBlock = true; _token.expressionValue = _loader.GetMandatoryInnerText(n); - if (_token.expressionValue is null) + if (_token.expressionValue == null) { // Error at XPath {0} in file {1}: Missing script block text. _loader.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.NoScriptBlockText, _loader.ComputeCurrentXPath(), _loader.FilePath)); @@ -2024,7 +2024,7 @@ internal ExpressionToken GenerateExpressionToken() return null; } - if (_token is null) + if (_token == null) { // we do not have a token: we never got one // the user should have specified either a property or a script block @@ -2053,7 +2053,7 @@ internal ViewEntryNodeMatch(TypeInfoDataBaseLoader loader) internal bool ProcessExpressionDirectives(XmlNode containerNode, List unprocessedNodes) { - if (containerNode is null) + if (containerNode == null) throw PSTraceSource.NewArgumentNullException(nameof(containerNode)); string formatString = null; @@ -2088,7 +2088,7 @@ internal bool ProcessExpressionDirectives(XmlNode containerNode, List u formatStringNodeFound = true; formatString = _loader.GetMandatoryInnerText(n); - if (formatString is null) + if (formatString == null) { // Error at XPath {0} in file {1}: Missing a format string. _loader.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.NoFormatString, _loader.ComputeCurrentXPath(), _loader.FilePath)); @@ -2105,7 +2105,7 @@ internal bool ProcessExpressionDirectives(XmlNode containerNode, List u textNodeFound = true; textToken = _loader.LoadText(n); - if (textToken is null) + if (textToken == null) { // Error at XPath {0} in file {1}: Invalid {2}. _loader.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.InvalidNode, _loader.ComputeCurrentXPath(), _loader.FilePath, XmlTags.TextNode)); @@ -2131,7 +2131,7 @@ internal bool ProcessExpressionDirectives(XmlNode containerNode, List u } ExpressionToken expression = expressionMatch.GenerateExpressionToken(); - if (expression is null) + if (expression == null) { return false; // fatal error } @@ -2206,7 +2206,7 @@ internal bool ProcessNode(XmlNode n) else if (_loader.MatchNodeName(n, XmlTags.ComplexControlNameNode)) { string name = _loader.GetMandatoryInnerText(n); - if (name is null) + if (name == null) { return false; } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Complex.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Complex.cs index 6b070b85854..3c9cecaed1b 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Complex.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Complex.cs @@ -36,7 +36,7 @@ private ComplexControlBody LoadComplexControl(XmlNode controlNode) // now read the columns section LoadComplexControlEntries(n, complexBody); - if (complexBody.defaultEntry is null) + if (complexBody.defaultEntry == null) { return null; // fatal error } @@ -68,7 +68,7 @@ private void LoadComplexControlEntries(XmlNode complexControlEntriesNode, Comple if (MatchNodeName(n, XmlTags.ComplexEntryNode)) { ComplexControlEntryDefinition cced = LoadComplexControlEntryDefinition(n, entryIndex++); - if (cced is null) + if (cced == null) { // Error at XPath {0} in file {1}: {2} failed to load. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.LoadTagFailed, ComputeCurrentXPath(), FilePath, XmlTags.ComplexEntryNode)); @@ -76,9 +76,9 @@ private void LoadComplexControlEntries(XmlNode complexControlEntriesNode, Comple return; // fatal error } // determine if we have a default entry and if it's already set - if (cced.appliesTo is null) + if (cced.appliesTo == null) { - if (complexBody.defaultEntry is null) + if (complexBody.defaultEntry == null) { complexBody.defaultEntry = cced; } @@ -101,7 +101,7 @@ private void LoadComplexControlEntries(XmlNode complexControlEntriesNode, Comple } } - if (complexBody.defaultEntry is null) + if (complexBody.defaultEntry == null) { // Error at XPath {0} in file {1}: There must be at least one default {2}. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.NoDefaultShapeEntry, ComputeCurrentXPath(), FilePath, XmlTags.ComplexEntryNode)); @@ -150,7 +150,7 @@ private ComplexControlEntryDefinition LoadComplexControlEntryDefinition(XmlNode } } - if (cced.itemDefinition.formatTokenList is null) + if (cced.itemDefinition.formatTokenList == null) { // MissingNode=Error at XPath {0} in file {1}: Missing Node {2}. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.MissingNode, ComputeCurrentXPath(), FilePath, XmlTags.ComplexItemNode)); @@ -178,7 +178,7 @@ private List LoadComplexControlTokenListDefinitions(XmlNode bodyNod { CompoundPropertyToken cpt = LoadCompoundProperty(n, compoundPropertyIndex++); - if (cpt is null) + if (cpt == null) { // Error at XPath {0} in file {1}: {2} failed to load. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.LoadTagFailed, ComputeCurrentXPath(), FilePath, XmlTags.ExpressionBindingNode)); @@ -191,7 +191,7 @@ private List LoadComplexControlTokenListDefinitions(XmlNode bodyNod { NewLineToken nlt = LoadNewLine(n, newLineIndex++); - if (nlt is null) + if (nlt == null) { // Error at XPath {0} in file {1}: {2} failed to load. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.LoadTagFailed, ComputeCurrentXPath(), FilePath, XmlTags.NewLineNode)); @@ -204,7 +204,7 @@ private List LoadComplexControlTokenListDefinitions(XmlNode bodyNod { TextToken tt = LoadText(n, textIndex++); - if (tt is null) + if (tt == null) { // Error at XPath {0} in file {1}: {2} failed to load. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.LoadTagFailed, ComputeCurrentXPath(), FilePath, XmlTags.TextNode)); @@ -217,7 +217,7 @@ private List LoadComplexControlTokenListDefinitions(XmlNode bodyNod { FrameToken frame = LoadFrameDefinition(n, frameIndex++); - if (frame is null) + if (frame == null) { // Error at XPath {0} in file {1}: {2} failed to load. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.LoadTagFailed, ComputeCurrentXPath(), FilePath, XmlTags.FrameNode)); @@ -289,7 +289,7 @@ private bool LoadPropertyBaseHelper(XmlNode propertyBaseNode, PropertyTokenBase itemSelectionConditionNodeFound = true; condition = LoadItemSelectionCondition(n); - if (condition is null) + if (condition == null) { return false; } @@ -305,7 +305,7 @@ private bool LoadPropertyBaseHelper(XmlNode propertyBaseNode, PropertyTokenBase { // we add only if we encountered one, since it's not mandatory ExpressionToken expression = expressionMatch.GenerateExpressionToken(); - if (expression is null) + if (expression == null) { return false; // fatal error } @@ -388,7 +388,7 @@ private CompoundPropertyToken LoadCompoundProperty(XmlNode compoundPropertyNode, fieldControlFound = true; fieldControlBody = new FieldControlBody(); fieldControlBody.fieldFormattingDirective.formatString = GetMandatoryInnerText(n); - if (fieldControlBody.fieldFormattingDirective.formatString is null) + if (fieldControlBody.fieldFormattingDirective.formatString == null) { return null; // fatal error } @@ -414,7 +414,7 @@ private CompoundPropertyToken LoadCompoundProperty(XmlNode compoundPropertyNode, cpt.control = controlMatch.Control; } /* - if (cpt.control is null) + if (cpt.control == null) { this.ReportMissingNodes ( new string[] { XmlTags.FieldControlNode, XmlTags.ComplexControlNode, XmlTags.ComplexControlNameNode }); @@ -469,7 +469,7 @@ private int LoadIntegerValue(XmlNode node, out bool success) string val = this.GetMandatoryInnerText(node); - if (val is null) + if (val == null) { // Error at XPath {0} in file {1}: Missing inner text value. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.MissingInnerText, ComputeCurrentXPath(), FilePath)); @@ -606,7 +606,7 @@ private FrameToken LoadFrameDefinition(XmlNode frameNode, int index) return null; // fatal error } - if (frame.itemDefinition.formatTokenList is null) + if (frame.itemDefinition.formatTokenList == null) { // MissingNode=Error at XPath {0} in file {1}: Missing Node {2}. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.MissingNode, ComputeCurrentXPath(), FilePath, XmlTags.ComplexItemNode)); diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_List.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_List.cs index 736b9d3a0db..323c94454b2 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_List.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_List.cs @@ -35,7 +35,7 @@ private ListControlBody LoadListControl(XmlNode controlNode) // now read the columns section LoadListControlEntries(n, listBody); - if (listBody.defaultEntryDefinition is null) + if (listBody.defaultEntryDefinition == null) { return null; // fatal error } @@ -67,7 +67,7 @@ private void LoadListControlEntries(XmlNode listViewEntriesNode, ListControlBody if (MatchNodeName(n, XmlTags.ListEntryNode)) { ListControlEntryDefinition lved = LoadListControlEntryDefinition(n, entryIndex++); - if (lved is null) + if (lved == null) { // Error at XPath {0} in file {1}: {2} failed to load. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.LoadTagFailed, ComputeCurrentXPath(), FilePath, XmlTags.ListEntryNode)); @@ -75,9 +75,9 @@ private void LoadListControlEntries(XmlNode listViewEntriesNode, ListControlBody return; // fatal error } // determine if we have a default entry and if it's already set - if (lved.appliesTo is null) + if (lved.appliesTo == null) { - if (listBody.defaultEntryDefinition is null) + if (listBody.defaultEntryDefinition == null) { listBody.defaultEntryDefinition = lved; } @@ -100,7 +100,7 @@ private void LoadListControlEntries(XmlNode listViewEntriesNode, ListControlBody } } - if (listBody.optionalEntryList is null) + if (listBody.optionalEntryList == null) { // Error at XPath {0} in file {1}: There must be at least one default {2}. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.NoDefaultShapeEntry, ComputeCurrentXPath(), FilePath, XmlTags.ListEntryNode)); @@ -149,7 +149,7 @@ private ListControlEntryDefinition LoadListControlEntryDefinition(XmlNode listVi } } - if (lved.itemDefinitionList is null) + if (lved.itemDefinitionList == null) { // Error at XPath {0} in file {1}: Missing definition list. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.NoDefinitionList, ComputeCurrentXPath(), FilePath)); @@ -172,7 +172,7 @@ private void LoadListControlItemDefinitions(ListControlEntryDefinition lved, Xml { index++; ListControlItemDefinition lvid = LoadListControlItemDefinition(n); - if (lvid is null) + if (lvid == null) { // Error at XPath {0} in file {1}: Invalid property entry. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.InvalidPropertyEntry, ComputeCurrentXPath(), FilePath)); @@ -229,7 +229,7 @@ private ListControlItemDefinition LoadListControlItemDefinition(XmlNode property itemSelectionConditionNodeFound = true; condition = LoadItemSelectionCondition(n); - if (condition is null) + if (condition == null) { return null; // fatal error } @@ -244,7 +244,7 @@ private ListControlItemDefinition LoadListControlItemDefinition(XmlNode property labelNodeFound = true; labelToken = LoadLabel(n); - if (labelToken is null) + if (labelToken == null) { return null; // fatal error } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Table.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Table.cs index 86e7c50cb5a..acc60a3e3e5 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Table.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Table.cs @@ -69,7 +69,7 @@ private ControlBase LoadTableControl(XmlNode controlNode) // now read the columns header section LoadHeadersSection(tableBody, n); - if (tableBody.header.columnHeaderDefinitionList is null) + if (tableBody.header.columnHeaderDefinitionList == null) { // if we have an empty list, it means there was a failure return null; // fatal error @@ -87,7 +87,7 @@ private ControlBase LoadTableControl(XmlNode controlNode) // now read the columns section LoadRowEntriesSection(tableBody, n); - if (tableBody.defaultDefinition is null) + if (tableBody.defaultDefinition == null) { return null; // fatal error } @@ -198,7 +198,7 @@ private TableColumnHeaderDefinition LoadColumnHeaderDefinition(XmlNode columnHea labelNodeFound = true; chd.label = LoadLabel(n); - if (chd.label is null) + if (chd.label == null) { return null; // fatal error } @@ -252,7 +252,7 @@ private bool ReadPositiveIntegerValue(XmlNode n, out int val) { val = -1; string text = GetMandatoryInnerText(n); - if (text is null) + if (text == null) return false; bool isInteger = int.TryParse(text, out val); if (!isInteger || val <= 0) @@ -269,7 +269,7 @@ private bool LoadAlignmentValue(XmlNode n, out int alignmentValue) { alignmentValue = TextAlignment.Undefined; string alignmentString = GetMandatoryInnerText(n); - if (alignmentString is null) + if (alignmentString == null) { return false; // fatal error } @@ -306,7 +306,7 @@ private void LoadRowEntriesSection(TableControlBody tableBody, XmlNode rowEntrie if (MatchNodeName(n, XmlTags.TableRowEntryNode)) { TableRowDefinition trd = LoadRowEntryDefinition(n, rowEntryIndex++); - if (trd is null) + if (trd == null) { // Error at XPath {0} in file {1}: {2} failed to load. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.LoadTagFailed, ComputeCurrentXPath(), FilePath, XmlTags.TableRowEntryNode)); @@ -315,9 +315,9 @@ private void LoadRowEntriesSection(TableControlBody tableBody, XmlNode rowEntrie } // determine if we have a default entry and if it's already set - if (trd.appliesTo is null) + if (trd.appliesTo == null) { - if (tableBody.defaultDefinition is null) + if (tableBody.defaultDefinition == null) { tableBody.defaultDefinition = trd; } @@ -340,7 +340,7 @@ private void LoadRowEntriesSection(TableControlBody tableBody, XmlNode rowEntrie } } - if (tableBody.defaultDefinition is null) + if (tableBody.defaultDefinition == null) { // Error at XPath {0} in file {1}: There must be at least one default {2}. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.NoDefaultShapeEntry, ComputeCurrentXPath(), FilePath, XmlTags.TableRowEntryNode)); @@ -381,7 +381,7 @@ private TableRowDefinition LoadRowEntryDefinition(XmlNode rowEntryNode, int inde } LoadColumnEntries(n, trd); - if (trd.rowItemDefinitionList is null) + if (trd.rowItemDefinitionList == null) { return null; // fatal error } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Views.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Views.cs index 2ea757a44df..8b960e32297 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Views.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Views.cs @@ -126,7 +126,7 @@ private ViewDefinition LoadView(XmlNode viewNode, int index) } } - if (view.mainControl is null) + if (view.mainControl == null) { this.ReportMissingNodes(controlNodeTags); return null; // fatal @@ -199,10 +199,10 @@ private bool LoadMainControlDependentData(List unprocessedNodes, ViewDe private bool LoadCommonViewData(XmlNode viewNode, ViewDefinition view, List unprocessedNodes) { - if (viewNode is null) + if (viewNode == null) throw PSTraceSource.NewArgumentNullException(nameof(viewNode)); - if (view is null) + if (view == null) throw PSTraceSource.NewArgumentNullException(nameof(view)); // set loading information @@ -226,7 +226,7 @@ private bool LoadCommonViewData(XmlNode viewNode, ViewDefinition view, ListTrue if there was an update. internal bool UpdateGroupingKeyValue(PSObject so) { - if (_groupingKeyExpression is null) + if (_groupingKeyExpression == null) return false; List results = _groupingKeyExpression.GetValues(so); // if we have more that one match, we have to select the first one - if (results.Count > 0 && results[0].Exception is null) + if (results.Count > 0 && results[0].Exception == null) { // no exception got thrown, so we can update object newValue = results[0].Result; @@ -66,7 +66,7 @@ internal bool UpdateGroupingKeyValue(PSObject so) bool update = !(IsEqual(_currentGroupingKeyPropertyValue, oldValue) || IsEqual(oldValue, _currentGroupingKeyPropertyValue)); - if (update && _label is null) + if (update && _label == null) { _groupingKeyDisplayName = results[0].ResolvedExpression.ToString(); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs index e39fd46466a..cf6a4d2eb88 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs @@ -115,12 +115,12 @@ private void InitializeGroupBy() if (this.dataBaseInfo.view != null) { GroupBy gb = this.dataBaseInfo.view.groupBy; - if (gb is null) + if (gb == null) { return; } - if (gb.startGroup is null || gb.startGroup.expression is null) + if (gb.startGroup == null || gb.startGroup.expression == null) { return; } @@ -176,7 +176,7 @@ internal virtual FormatStartData GenerateStartData(PSObject so) internal GroupStartData GenerateGroupStartData(PSObject firstObjectInGroup, int enumerationLimit) { GroupStartData startGroup = new GroupStartData(); - if (_groupingManager is null) + if (_groupingManager == null) return startGroup; object currentGroupingValue = _groupingManager.CurrentGroupingKeyPropertyValue; @@ -202,7 +202,7 @@ internal GroupStartData GenerateGroupStartData(PSObject firstObjectInGroup, int startGroup.groupingEntry = new GroupingEntry(); - if (control is null) + if (control == null) { // we do not have a control, we auto generate a // snippet of complex display using a label @@ -278,7 +278,7 @@ internal GroupStartData GenerateGroupStartData(PSObject firstObjectInGroup, int /// True if the value of the key changed. internal bool UpdateGroupingKeyValue(PSObject so) { - if (_groupingManager is null) + if (_groupingManager == null) return false; return _groupingManager.UpdateGroupingKeyValue(so); } @@ -290,7 +290,7 @@ internal GroupEndData GenerateGroupEndData() internal bool IsObjectApplicable(Collection typeNames) { - if (dataBaseInfo.view is null) + if (dataBaseInfo.view == null) return true; if (typeNames.Count == 0) @@ -402,7 +402,7 @@ protected string GetExpressionDisplayValue(PSObject so, int enumerationLimit, PS protected bool EvaluateDisplayCondition(PSObject so, ExpressionToken conditionToken) { - if (conditionToken is null) + if (conditionToken == null) return true; PSPropertyExpression ex = this.expressionFactory.CreateFromExpressionToken(conditionToken, this.dataBaseInfo.view.loadingInfo); diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs index b2ca8b6b3c3..c9cd80bbee8 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs @@ -91,7 +91,7 @@ internal ComplexControlGenerator(TypeInfoDataBase dataBase, internal void GenerateFormatEntries(int maxTreeDepth, ControlBase control, PSObject so, List formatValueList) { - if (control is null) + if (control == null) { throw PSTraceSource.NewArgumentNullException(nameof(control)); } @@ -188,7 +188,7 @@ private ComplexControlEntryDefinition GetActiveComplexControlEntryDefinition(Com private void ExecuteFormatTokenList(TraversalInfo level, PSObject so, List formatTokenList, List formatValueList) { - if (so is null) + if (so == null) { throw PSTraceSource.NewArgumentNullException(nameof(so)); } @@ -259,7 +259,7 @@ private void ExecuteFormatTokenList(TraversalInfo level, // if no expression was specified, just use the // object itself - if (cpt.expression is null || string.IsNullOrEmpty(cpt.expression.expressionValue)) + if (cpt.expression == null || string.IsNullOrEmpty(cpt.expression.expressionValue)) { val = so; } @@ -279,11 +279,11 @@ private void ExecuteFormatTokenList(TraversalInfo level, // if the token is has a formatting string, it's a leaf node, // do the formatting and we will be done - if (cpt.control is null || cpt.control is FieldControlBody) + if (cpt.control == null || cpt.control is FieldControlBody) { // Since it is a leaf node we just consider it an empty string and go // on with formatting - if (val is null) + if (val == null) { val = string.Empty; } @@ -305,7 +305,7 @@ private void ExecuteFormatTokenList(TraversalInfo level, { foreach (object x in e) { - if (x is null) + if (x == null) { // nothing to process continue; @@ -334,7 +334,7 @@ private void ExecuteFormatTokenList(TraversalInfo level, else { // An empty result that is not a leaf node should not be expanded - if (val is null) + if (val == null) { continue; } @@ -344,7 +344,7 @@ private void ExecuteFormatTokenList(TraversalInfo level, { foreach (object x in e) { - if (x is null) + if (x == null) { // nothing to process continue; @@ -368,7 +368,7 @@ private void ExecuteFormatTokenList(TraversalInfo level, private bool EvaluateDisplayCondition(PSObject so, ExpressionToken conditionToken) { - if (conditionToken is null) + if (conditionToken == null) return true; PSPropertyExpression ex = _expressionFactory.CreateFromExpressionToken(conditionToken, _loadingInfo); @@ -592,7 +592,7 @@ private void ProcessActiveAssociationList(PSObject so, formatValueList.Add(new FormatNewLine()); DisplayEnumeration(e, level.NextLevel, AddIndentationLevel(formatValueList)); } - else if (val is null || TreatAsLeafNode(val, level)) + else if (val == null || TreatAsLeafNode(val, level)) { DisplayLeaf(val, formatValueList); } @@ -687,7 +687,7 @@ private void DisplayLeaf(object val, List formatValueList) /// private static bool TreatAsLeafNode(object val, TraversalInfo level) { - if (level.Level >= level.MaxDepth || val is null) + if (level.Level >= level.MaxDepth || val == null) return true; return TreatAsScalarType(PSObject.GetTypeNames(val)); diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_List.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_List.cs index 2c547d7470f..2ded68cd510 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_List.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_List.cs @@ -182,7 +182,7 @@ private ListControlEntryDefinition GetActiveListControlEntryDefinition(ListContr private ListViewEntry GenerateListViewEntryFromProperties(PSObject so, int enumerationLimit) { // compute active properties every time - if (this.activeAssociationList is null) + if (this.activeAssociationList == null) { SetUpActiveProperties(so); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs index 231e8d927de..ab4912c8838 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs @@ -180,7 +180,7 @@ private TableHeaderInfo GenerateTableHeaderInfoFromDataBaseInfo(PSObject so) ci.alignment = rowItem.alignment; } - if (ci.label is null) + if (ci.label == null) { FormatToken token = null; if (rowItem.formatTokenList.Count > 0) @@ -233,7 +233,7 @@ private TableHeaderInfo GenerateTableHeaderInfoFromProperties(PSObject so) ci.propertyName = (string)key; } - if (ci.propertyName is null) + if (ci.propertyName == null) { ci.propertyName = this.activeAssociationList[k].ResolvedExpression.ToString(); } @@ -320,7 +320,7 @@ private static int ComputeDefaultAlignment(PSObject so, PSPropertyExpression ex) return TextAlignment.Left; object val = rList[0].Result; - if (val is null) + if (val == null) return TextAlignment.Left; PSObject soVal = PSObject.AsPSObject(val); @@ -391,12 +391,12 @@ private List GetActiveTableRowDefinition(TableControlBod } } - if (matchingRowDefinition is null) + if (matchingRowDefinition == null) { matchingRowDefinition = match.BestMatch as TableRowDefinition; } - if (matchingRowDefinition is null) + if (matchingRowDefinition == null) { Collection typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames); if (typesWithoutPrefix != null) @@ -412,14 +412,14 @@ private List GetActiveTableRowDefinition(TableControlBod } } - if (matchingRowDefinition is null) + if (matchingRowDefinition == null) { matchingRowDefinition = match.BestMatch as TableRowDefinition; } } } - if (matchingRowDefinition is null) + if (matchingRowDefinition == null) { // no matching override, use default return tableBody.defaultDefinition.rowItemDefinitionList; diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Wide.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Wide.cs index 2d1aa16d1ac..9d378eaf9cc 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Wide.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Wide.cs @@ -131,7 +131,7 @@ private WideControlEntryDefinition GetActiveWideControlEntryDefinition(WideContr private WideViewEntry GenerateWideViewEntryFromProperties(PSObject so, int enumerationLimit) { // compute active properties every time - if (this.activeAssociationList is null) + if (this.activeAssociationList == null) { SetUpActiveProperty(so); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs index baa7ede8edf..aca38f8994b 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs @@ -403,7 +403,7 @@ private static ViewGenerator SelectViewGeneratorFromProperties(FormatShape shape FormattingCommandLineParameters parameters) { // use some heuristics to determine the shape if none is specified - if (shape == FormatShape.Undefined && parameters is null) + if (shape == FormatShape.Undefined && parameters == null) { // check first if we have a known shape for a type var typeNames = so.InternalTypeNames; diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs b/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs index a0c37005e2c..21630c1a9c1 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs @@ -57,7 +57,7 @@ fid is GroupEndData || string classId = GetProperty(so, FormatInfoData.classidProperty) as string; - if (classId is null) + if (classId == null) { // it's not one of the objects derived from FormatInfoData return false; @@ -115,7 +115,7 @@ fid is GroupEndData || string classId = GetProperty(so, FormatInfoData.classidProperty) as string; - if (classId is null) + if (classId == null) { // it's not one of the objects derived from FormatInfoData, // just return it as is @@ -172,7 +172,7 @@ private static string[] ReadStringArrayHelper (object rawObject, string property // throw if the property is not there IEnumerable e = (IEnumerable)ERSHelper.GetExtendedProperty (rawObject, propertyName, false); - if (e is null) + if (e == null) return null; // copy to string collection, since, a priori, we do not know the length @@ -197,7 +197,7 @@ private static string[] ReadStringArrayHelper (object rawObject, string property internal static object GetProperty(PSObject so, string name) { PSMemberInfo member = so.Properties[name]; - if (member is null) + if (member == null) { return null; } @@ -210,7 +210,7 @@ internal static object GetProperty(PSObject so, string name) internal FormatInfoData DeserializeMemberObject(PSObject so, string property) { object memberRaw = GetProperty(so, property); - if (memberRaw is null) + if (memberRaw == null) return null; if (so == memberRaw) { @@ -294,13 +294,13 @@ internal int DeserializeIntMemberVariable(PSObject so, string property) internal bool DeserializeBoolMemberVariable(PSObject so, string property, bool cannotBeNull = true) { var val = DeserializeMemberVariable(so, property, typeof(bool), cannotBeNull); - return (val is null) ? false : (bool)val; + return (val == null) ? false : (bool)val; } internal WriteStreamType DeserializeWriteStreamTypeMemberVariable(PSObject so) { object wsTypeValue = GetProperty(so, "writeStream"); - if (wsTypeValue is null) + if (wsTypeValue == null) { return WriteStreamType.None; } @@ -390,14 +390,14 @@ static FormatInfoDataClassFactory() // returns null on error internal static FormatInfoData CreateInstance(PSObject so, FormatObjectDeserializer deserializer) { - if (so is null) + if (so == null) { throw PSTraceSource.NewArgumentNullException(nameof(so)); } // look for the property that defines the type of object string classId = FormatObjectDeserializer.GetProperty(so, FormatInfoData.classidProperty) as string; - if (classId is null) + if (classId == null) { string msg = StringUtil.Format(FormatAndOut_format_xxx.FOD_InvalidClassidProperty); @@ -502,7 +502,7 @@ private static void ReadListHelper(IEnumerable en, List lst, FormatObjectDese internal static void ReadList(PSObject so, string property, List lst, FormatObjectDeserializer deserializer) { - if (lst is null) + if (lst == null) { throw PSTraceSource.NewArgumentNullException(nameof(lst)); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/ILineOutput.cs b/src/System.Management.Automation/FormatAndOutput/common/ILineOutput.cs index 51e79ffe0bc..09432253e33 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/ILineOutput.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/ILineOutput.cs @@ -281,9 +281,9 @@ internal class WriteLineHelper /// Helper object for manipulating strings. internal WriteLineHelper(bool lineWrap, WriteCallback wlc, WriteCallback wc, DisplayCells displayCells) { - if (wlc is null) + if (wlc == null) throw PSTraceSource.NewArgumentNullException(nameof(wlc)); - if (displayCells is null) + if (displayCells == null) throw PSTraceSource.NewArgumentNullException(nameof(displayCells)); _displayCells = displayCells; @@ -473,7 +473,7 @@ internal class StreamingTextWriter : TextWriter internal StreamingTextWriter(WriteLineCallback writeCall, CultureInfo culture) : base(culture) { - if (writeCall is null) + if (writeCall == null) throw PSTraceSource.NewArgumentNullException(nameof(writeCall)); _writeCall = writeCall; diff --git a/src/System.Management.Automation/FormatAndOutput/common/ListWriter.cs b/src/System.Management.Automation/FormatAndOutput/common/ListWriter.cs index b14cfa78e0f..91a7b8698a6 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/ListWriter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/ListWriter.cs @@ -37,7 +37,7 @@ internal class ListWriter internal void Initialize(string[] propertyNames, int screenColumnWidth, DisplayCells dc) { _columnWidth = screenColumnWidth; - if (propertyNames is null || propertyNames.Length == 0) + if (propertyNames == null || propertyNames.Length == 0) { // there is nothing to show _disabled = true; @@ -115,7 +115,7 @@ internal void WriteProperties(string[] values, LineOutput lo) return; string[] valuesToPrint = null; - if (values is null) + if (values == null) { // we have nothing, but we have to create an empty array valuesToPrint = new string[_propertyLabels.Length]; @@ -164,7 +164,7 @@ internal void WriteProperties(string[] values, LineOutput lo) /// LineOutput interface to write to. private void WriteProperty(int k, string propertyValue, LineOutput lo) { - if (propertyValue is null) + if (propertyValue == null) propertyValue = string.Empty; // make sure we honor embedded newlines @@ -181,7 +181,7 @@ private void WriteProperty(int k, string propertyValue, LineOutput lo) prependString = _propertyLabels[k]; else { - if (padding is null) + if (padding == null) padding = StringUtil.Padding(_propertyLabelsDisplayLength); prependString = padding; @@ -200,7 +200,7 @@ private void WriteProperty(int k, string propertyValue, LineOutput lo) /// LineOuput to write to. private void WriteSingleLineHelper(string prependString, string line, LineOutput lo) { - if (line is null) + if (line == null) line = string.Empty; // compute the width of the field for the value string (in screen cells) diff --git a/src/System.Management.Automation/FormatAndOutput/common/OutputManager.cs b/src/System.Management.Automation/FormatAndOutput/common/OutputManager.cs index cc5be812cb8..b07731c3e04 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/OutputManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/OutputManager.cs @@ -51,14 +51,14 @@ internal override void ProcessRecord() { PSObject so = this.ReadObject(); - if (so is null || so == AutomationNull.Value) + if (so == null || so == AutomationNull.Value) { return; } // on demand initialization when the first pipeline // object is initialized - if (_mgr is null) + if (_mgr == null) { _mgr = new SubPipelineManager(); _mgr.Initialize(_lo, this.OuterCmdlet().Context); @@ -69,7 +69,7 @@ internal override void ProcessRecord() // unpack the object and process each member separately IEnumerable e = PSObjectHelper.GetEnumerable (so); - if (e is null) + if (e == null) { this.mgr.Process (so); } @@ -175,7 +175,7 @@ internal bool AppliesToType(string typeName) /// public void Dispose() { - if (this.command is null) + if (this.command == null) return; this.command.Dispose(); diff --git a/src/System.Management.Automation/FormatAndOutput/common/OutputQueue.cs b/src/System.Management.Automation/FormatAndOutput/common/OutputQueue.cs index d70889c3d4e..1545f456e12 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/OutputQueue.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/OutputQueue.cs @@ -122,7 +122,7 @@ private void UpdateObjectCount(PacketInfoData o) // and it's not out of band FormatEntryData fed = o as FormatEntryData; - if (fed is null || fed.outOfBand) + if (fed == null || fed.outOfBand) return; _currentObjectCount++; @@ -130,7 +130,7 @@ private void UpdateObjectCount(PacketInfoData o) private void Notify() { - if (_notificationCallBack is null) + if (_notificationCallBack == null) return; // filter out the out of band data, since they do not participate in the @@ -256,7 +256,7 @@ internal void EnableGroupCaching(ProcessCachedGroupNotification callBack, TimeSp internal List Add(PacketInfoData o) { // if neither there, pass thru - if (_frontEndQueue is null && _groupQueue is null) + if (_frontEndQueue == null && _groupQueue == null) { List retVal = new List(); retVal.Add(o); @@ -281,7 +281,7 @@ internal List Add(PacketInfoData o) internal List Drain() { // if neither there,we did not cache at all - if (_frontEndQueue is null && _groupQueue is null) + if (_frontEndQueue == null && _groupQueue == null) { return null; } @@ -290,7 +290,7 @@ internal List Drain() if (_frontEndQueue != null) { - if (_groupQueue is null) + if (_groupQueue == null) { // drain the front queue and return the data while (_frontEndQueue.Count > 0) @@ -315,7 +315,7 @@ internal List Drain() { PacketInfoData obj = _groupQueue.Dequeue(); - if (obj is null) + if (obj == null) break; retVal.Add(obj); diff --git a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshObjectUtil.cs b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshObjectUtil.cs index 8c1b2cce39f..c890599cb1e 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshObjectUtil.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshObjectUtil.cs @@ -93,7 +93,7 @@ internal static PSPropertyExpressionResult GetDisplayName(PSObject target, PSPro { // get the expression to evaluate PSPropertyExpression ex = GetDisplayNameExpression(target, expressionFactory); - if (ex is null) + if (ex == null) return null; // evaluate the expression @@ -131,7 +131,7 @@ internal static IEnumerable GetEnumerable(object obj) private static string GetSmartToStringDisplayName(object x, PSPropertyExpressionFactory expressionFactory) { PSPropertyExpressionResult r = PSObjectHelper.GetDisplayName(PSObjectHelper.AsPSObject(x), expressionFactory); - if ((r != null) && (r.Exception is null)) + if ((r != null) && (r.Exception == null)) { return PSObjectHelper.AsPSObject(r.Result).ToString(); } @@ -154,7 +154,7 @@ private static string GetObjectName(object x, PSPropertyExpressionFactory expres { objName = x.ToString(); } - else if (x is null) + else if (x == null) { // use PowerShell's $null variable to indicate that the value is null... objName = "$null"; @@ -171,7 +171,7 @@ private static string GetObjectName(object x, PSPropertyExpressionFactory expres else { PSPropertyExpressionResult r = PSObjectHelper.GetDisplayName(PSObjectHelper.AsPSObject(x), expressionFactory); - if ((r != null) && (r.Exception is null)) + if ((r != null) && (r.Exception == null)) { objName = PSObjectHelper.AsPSObject(r.Result).ToString(); } @@ -204,7 +204,7 @@ private static string GetObjectName(object x, PSPropertyExpressionFactory expres /// String representation. internal static string SmartToString(PSObject so, PSPropertyExpressionFactory expressionFactory, int enumerationLimit, StringFormatError formatErrorObject) { - if (so is null) + if (so == null) return string.Empty; try @@ -308,7 +308,7 @@ internal static string SmartToString(PSObject so, PSPropertyExpressionFactory ex internal static PSObject AsPSObject(object obj) { - return (obj is null) ? s_emptyPSObject : PSObject.AsPSObject(obj); + return (obj == null) ? s_emptyPSObject : PSObject.AsPSObject(obj); } /// @@ -368,13 +368,13 @@ private static PSMemberSet MaskDeserializedAndGetStandardMembers(PSObject so) Diagnostics.Assert(so != null, "Shell object to process cannot be null"); var typeNames = so.InternalTypeNames; Collection typeNamesWithoutDeserializedPrefix = Deserializer.MaskDeserializationPrefix(typeNames); - if (typeNamesWithoutDeserializedPrefix is null) + if (typeNamesWithoutDeserializedPrefix == null) { return null; } TypeTable typeTable = so.GetTypeTable(); - if (typeTable is null) + if (typeTable == null) { return null; } diff --git a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameter.cs b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameter.cs index f5b7a898a5f..d04008a1f9a 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameter.cs @@ -149,7 +149,7 @@ internal HashtableEntryDefinition MatchEntry(string keyName, TerminatingErrorCon if (this.hashEntries[k].IsKeyMatch(keyName)) { // we have a match - if (matchingEntry is null) + if (matchingEntry == null) { // this is the first match, we save the entry // and we keep going for ambiguity check @@ -253,7 +253,7 @@ internal ParameterProcessor(CommandParameterDefinition p) /// internal List ProcessParameters(object[] p, TerminatingErrorContext invocationContext) { - if (p is null || p.Length == 0) + if (p == null || p.Length == 0) return null; List retVal = new List(); @@ -311,13 +311,13 @@ private Hashtable VerifyHashTable(IDictionary hash, TerminatingErrorContext invo foreach (DictionaryEntry e in hash) { - if (e.Key is null) + if (e.Key == null) { ProcessNullHashTableKey(invocationContext); } string currentStringKey = e.Key as string; - if (currentStringKey is null) + if (currentStringKey == null) { ProcessNonStringHashTableKey(invocationContext, e.Key); } @@ -333,7 +333,7 @@ private Hashtable VerifyHashTable(IDictionary hash, TerminatingErrorContext invo // now the key is verified, need to check the type bool matchType = false; - if (def.AllowedTypes is null || def.AllowedTypes.Length == 0) + if (def.AllowedTypes == null || def.AllowedTypes.Length == 0) { // we match on any type, it will be up to the entry to further check matchType = true; @@ -342,7 +342,7 @@ private Hashtable VerifyHashTable(IDictionary hash, TerminatingErrorContext invo { for (int t = 0; t < def.AllowedTypes.Length; t++) { - if (e.Value is null) + if (e.Value == null) { ProcessMissingKeyValue(invocationContext, currentStringKey); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameterAssociation.cs b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameterAssociation.cs index f2fe89111b4..22b4c47ee40 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameterAssociation.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameterAssociation.cs @@ -22,7 +22,7 @@ internal sealed class MshResolvedExpressionParameterAssociation internal MshResolvedExpressionParameterAssociation(MshParameter parameter, PSPropertyExpression expression) { - if (expression is null) + if (expression == null) throw PSTraceSource.NewArgumentNullException(nameof(expression)); OriginatingParameter = parameter; diff --git a/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs b/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs index 36363ed6381..febac2224f1 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs @@ -86,7 +86,7 @@ public PSPropertyExpression(string s, bool isResolved) /// public PSPropertyExpression(ScriptBlock scriptBlock) { - if (scriptBlock is null) + if (scriptBlock == null) { throw PSTraceSource.NewArgumentNullException(nameof(scriptBlock)); } @@ -184,7 +184,7 @@ public List ResolveNames(PSObject target, bool expand) // we have no globbing: try an exact match, because this is quicker. PSMemberInfo x = wrappedTarget.Members[_stringValue]; - if (x is null) + if (x == null) { if (wasHashtable) { @@ -326,7 +326,7 @@ private PSPropertyExpressionResult GetValue(PSObject target, bool eatExceptions) } else { - if (_getValueDynamicSite is null) + if (_getValueDynamicSite == null) { _getValueDynamicSite = CallSite>.Create( diff --git a/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs b/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs index 7866c02e512..b6cde18fb65 100644 --- a/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs +++ b/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs @@ -251,9 +251,9 @@ internal override DisplayCells DisplayCells /// Error context to throw exceptions. internal ConsoleLineOutput(PSHostUserInterface hostConsole, bool paging, TerminatingErrorContext errorContext) { - if (hostConsole is null) + if (hostConsole == null) throw PSTraceSource.NewArgumentNullException(nameof(hostConsole)); - if (errorContext is null) + if (errorContext == null) throw PSTraceSource.NewArgumentNullException(nameof(errorContext)); _console = hostConsole; @@ -388,7 +388,7 @@ private void LineWrittenEvent() return; // if there is no prompting, we are done - if (_prompt is null) + if (_prompt == null) return; // increment the count of lines written to the screen diff --git a/src/System.Management.Automation/FormatAndOutput/out-textInterface/OutTextInterface.cs b/src/System.Management.Automation/FormatAndOutput/out-textInterface/OutTextInterface.cs index 72177fc151c..5a6f2bd0683 100644 --- a/src/System.Management.Automation/FormatAndOutput/out-textInterface/OutTextInterface.cs +++ b/src/System.Management.Automation/FormatAndOutput/out-textInterface/OutTextInterface.cs @@ -43,13 +43,13 @@ public OutLineOutputCommand() /// protected override void BeginProcessing() { - if (_lineOutput is null) + if (_lineOutput == null) { ProcessNullLineOutput(); } LineOutput lo = _lineOutput as LineOutput; - if (lo is null) + if (lo == null) { ProcessWrongTypeLineOutput(_lineOutput); } diff --git a/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs b/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs index 2062092b79d..81a4c33062f 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs @@ -21,8 +21,8 @@ public sealed class MethodInvocationInfo /// Return value of the method (ok to pass null if the method doesn't return anything). public MethodInvocationInfo(string name, IEnumerable parameters, MethodParameter returnValue) { - if (name is null) throw new ArgumentNullException(nameof(name)); - if (parameters is null) throw new ArgumentNullException(nameof(parameters)); + if (name == null) throw new ArgumentNullException(nameof(name)); + if (parameters == null) throw new ArgumentNullException(nameof(parameters)); // returnValue can be null MethodName = name; diff --git a/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs b/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs index d33c8223e94..289ad0c3a76 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs @@ -17,7 +17,7 @@ public abstract class CmdletAdapter { internal void Initialize(PSCmdlet cmdlet, string className, string classVersion, IDictionary privateData) { - if (cmdlet is null) + if (cmdlet == null) { throw new ArgumentNullException(nameof(cmdlet)); } @@ -27,12 +27,12 @@ internal void Initialize(PSCmdlet cmdlet, string className, string classVersion, throw new ArgumentNullException(nameof(className)); } - if (classVersion is null) // possible and ok to have classVersion==string.Empty + if (classVersion == null) // possible and ok to have classVersion==string.Empty { throw new ArgumentNullException(nameof(classVersion)); } - if (privateData is null) + if (privateData == null) { throw new ArgumentNullException(nameof(privateData)); } diff --git a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs index 0609e62a853..3757319c9ab 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs @@ -415,7 +415,7 @@ private List GetMethodParameterSets(InstanceCmdletMetadata instanceCmdle private GetCmdletParameters GetGetCmdletParameters(InstanceCmdletMetadata instanceCmdlet) { - if (instanceCmdlet is null) + if (instanceCmdlet == null) { if ((_cmdletizationMetadata.Class.InstanceCmdlets.GetCmdlet != null) && (_cmdletizationMetadata.Class.InstanceCmdlets.GetCmdlet.GetCmdletParameters != null)) @@ -629,7 +629,7 @@ private ParameterMetadata GetParameter( { Type parameterType = parameterMetadata.ParameterType; Type elementType; - if (parameterType is null) + if (parameterType == null) { elementType = typeof(string); } @@ -991,7 +991,7 @@ private static MethodParameterBindings GetMethodParameterKind(InstanceMethodPara if (methodParameter.CmdletOutputMetadata != null) { - if (methodParameter.CmdletOutputMetadata.ErrorCode is null) + if (methodParameter.CmdletOutputMetadata.ErrorCode == null) { bindings |= MethodParameterBindings.Out; } @@ -1016,7 +1016,7 @@ private static MethodParameterBindings GetMethodParameterKind(StaticMethodParame if (methodParameter.CmdletOutputMetadata != null) { - if (methodParameter.CmdletOutputMetadata.ErrorCode is null) + if (methodParameter.CmdletOutputMetadata.ErrorCode == null) { bindings |= MethodParameterBindings.Out; } @@ -1036,7 +1036,7 @@ private static MethodParameterBindings GetMethodParameterKind(CommonMethodMetada MethodParameterBindings bindings = 0; if (returnValue.CmdletOutputMetadata != null) { - if (returnValue.CmdletOutputMetadata.ErrorCode is null) + if (returnValue.CmdletOutputMetadata.ErrorCode == null) { bindings |= MethodParameterBindings.Out; } @@ -1481,7 +1481,7 @@ private ParameterMetadata GenerateQueryClause( WildcardablePropertyQuery wildcardablePropertyQuery = query as WildcardablePropertyQuery; if ((wildcardablePropertyQuery != null) && (!cmdletParameterMetadata.SwitchParameter)) { - if (cmdletParameterMetadata.ParameterType is null) + if (cmdletParameterMetadata.ParameterType == null) { cmdletParameterMetadata.ParameterType = typeof(object); } @@ -1491,8 +1491,8 @@ private ParameterMetadata GenerateQueryClause( GenerateIfBoundParameter(commonParameterSets, methodParameterSets, cmdletParameterMetadata, output); - string localVariableName = wildcardablePropertyQuery is null ? "__cmdletization_value" : "__cmdletization_values"; - if (wildcardablePropertyQuery is null) + string localVariableName = wildcardablePropertyQuery == null ? "__cmdletization_value" : "__cmdletization_values"; + if (wildcardablePropertyQuery == null) { output.WriteLine( " [object]${0} = ${{{1}}}", @@ -1512,7 +1512,7 @@ private ParameterMetadata GenerateQueryClause( queryBuilderMethodName, CodeGeneration.EscapeSingleQuotedStringContent(property.PropertyName), localVariableName); - if (wildcardablePropertyQuery is null) + if (wildcardablePropertyQuery == null) { output.WriteLine( ", '{0}')", @@ -1536,7 +1536,7 @@ private ParameterMetadata GenerateQueryClause( private static BehaviorOnNoMatch GetBehaviorWhenNoMatchesFound(CmdletParameterMetadataForGetCmdletFilteringParameter cmdletParameterMetadata) { - if ((cmdletParameterMetadata is null) || (!cmdletParameterMetadata.ErrorOnNoMatchSpecified)) + if ((cmdletParameterMetadata == null) || (!cmdletParameterMetadata.ErrorOnNoMatchSpecified)) { return BehaviorOnNoMatch.Default; } @@ -1929,7 +1929,7 @@ private static void AddPassThruParameter(IDictionary { foreach (InstanceMethodParameterMetadata parameter in instanceCmdletMetadata.Method.Parameters) { - if ((parameter.CmdletOutputMetadata != null) && (parameter.CmdletOutputMetadata.ErrorCode is null)) + if ((parameter.CmdletOutputMetadata != null) && (parameter.CmdletOutputMetadata.ErrorCode == null)) { outParametersArePresent = true; break; @@ -1940,7 +1940,7 @@ private static void AddPassThruParameter(IDictionary if (instanceCmdletMetadata.Method.ReturnValue != null) { if ((instanceCmdletMetadata.Method.ReturnValue.CmdletOutputMetadata != null) && - (instanceCmdletMetadata.Method.ReturnValue.CmdletOutputMetadata.ErrorCode is null)) + (instanceCmdletMetadata.Method.ReturnValue.CmdletOutputMetadata.ErrorCode == null)) { outParametersArePresent = true; } diff --git a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs index bd77d5bd082..9c53032284e 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs @@ -161,7 +161,7 @@ internal int ReaderCount // return checkDeserializeAdvances ? countingReader.AdvanceCount : 0; // and checkDeserializeAdvances is set in the static constructor: // XmlSerializerSection configSection = ConfigurationManager.GetSection(ConfigurationStrings.XmlSerializerSectionPath) as XmlSerializerSection; - // checkDeserializeAdvances = (configSection is null) ? false : configSection.CheckDeserializeAdvances; + // checkDeserializeAdvances = (configSection == null) ? false : configSection.CheckDeserializeAdvances; // When XmlSerializationReader is used in powershell, there is no configuration file defined for it, so 'checkDeserializeAdvances' will actually // always be 'false'. Therefore, here we directly return 0 for 'ReaderCount'. return 0; @@ -185,7 +185,7 @@ protected XmlDocument Document { get { - if (_d is null) + if (_d == null) { _d = new XmlDocument(_r.NameTable); } @@ -299,7 +299,7 @@ protected Exception CreateUnknownConstantException(string value, Type enumType) protected Array ShrinkArray(Array a, int length, Type elementType, bool isNullable) { - if (a is null) + if (a == null) { if (isNullable) return null; return Array.CreateInstance(elementType, 0); @@ -313,7 +313,7 @@ protected Array ShrinkArray(Array a, int length, Type elementType, bool isNullab protected Array EnsureArrayIndex(Array a, int index, Type elementType) { - if (a is null) return Array.CreateInstance(elementType, 32); + if (a == null) return Array.CreateInstance(elementType, 32); if (index < a.Length) return a; Array b = Array.CreateInstance(elementType, a.Length * 2); Array.Copy(a, b, index); @@ -322,7 +322,7 @@ protected Array EnsureArrayIndex(Array a, int index, Type elementType) protected string CollapseWhitespace(string value) { - if (value is null) + if (value == null) return null; return value.Trim(); } @@ -367,7 +367,7 @@ protected void UnknownNode(object o, string qnames) private void UnknownNode(XmlNode unknownNode, object o, string qnames) { - if (unknownNode is null) + if (unknownNode == null) return; // No XmlDeserializationEvents in CoreCLR. The events like 'onUnknownNode', 'onUnknownAttribute' and @@ -394,7 +394,7 @@ protected string ReadString(string value, bool trim) string str = _r.ReadContentAsString(); if (str != null && trim) str = str.Trim(); - if (value is null || value.Length == 0) + if (value == null || value.Length == 0) return str; return value + str; } @@ -406,7 +406,7 @@ protected XmlQualifiedName ToXmlQualifiedName(string value) internal XmlQualifiedName ToXmlQualifiedName(string value, bool decodeName) { - int colon = value is null ? -1 : value.LastIndexOf(':'); + int colon = value == null ? -1 : value.LastIndexOf(':'); string prefix = colon < 0 ? null : value.Substring(0, colon); string localName = value.Substring(colon + 1); @@ -416,14 +416,14 @@ internal XmlQualifiedName ToXmlQualifiedName(string value, bool decodeName) localName = XmlConvert.DecodeName(localName); } - if (prefix is null || prefix.Length == 0) + if (prefix == null || prefix.Length == 0) { return new XmlQualifiedName(_r.NameTable.Add(value), _r.LookupNamespace(string.Empty)); } else { string ns = _r.LookupNamespace(prefix); - if (ns is null) + if (ns == null) { // Namespace prefix '{0}' is not defined. throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "XmlUndefinedAlias. Prefix: {0}", prefix)); @@ -442,13 +442,13 @@ internal XmlQualifiedName ToXmlQualifiedName(string value, bool decodeName) protected XmlQualifiedName GetXsiType() { string type = _r.GetAttribute(_typeID, _instanceNsID); - if (type is null) + if (type == null) { type = _r.GetAttribute(_typeID, _instanceNs2000ID); - if (type is null) + if (type == null) { type = _r.GetAttribute(_typeID, _instanceNs1999ID); - if (type is null) + if (type == null) return null; } } @@ -459,16 +459,16 @@ protected XmlQualifiedName GetXsiType() protected bool GetNullAttr() { string isNull = _r.GetAttribute(_nilID, _instanceNsID); - if (isNull is null) + if (isNull == null) isNull = _r.GetAttribute(_nullID, _instanceNsID); - if (isNull is null) + if (isNull == null) { isNull = _r.GetAttribute(_nullID, _instanceNs2000ID); - if (isNull is null) + if (isNull == null) isNull = _r.GetAttribute(_nullID, _instanceNs1999ID); } - if (isNull is null || !XmlConvert.ToBoolean(isNull)) return false; + if (isNull == null || !XmlConvert.ToBoolean(isNull)) return false; return true; } @@ -1426,7 +1426,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id40_EnumMetadataEnumValue && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id40_EnumMetadataEnumValue && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -1492,7 +1492,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id39_EnumMetadataEnum && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id39_EnumMetadataEnum && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -1575,7 +1575,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -1641,7 +1641,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id38_ClassMetadataData && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id38_ClassMetadataData && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -1723,7 +1723,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id36_WildcardablePropertyQuery && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id36_WildcardablePropertyQuery && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -1793,7 +1793,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id13_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id13_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -2005,7 +2005,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id17_ObsoleteAttributeMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id17_ObsoleteAttributeMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -2066,7 +2066,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -2132,7 +2132,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -2198,7 +2198,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -2270,7 +2270,7 @@ public object Read87_EnumMetadataEnumValue() else return null; } - if (xsiType is null) + if (xsiType == null) { return ReadTypedPrimitive(new System.Xml.XmlQualifiedName("anyType", "http://www.w3.org/2001/XMLSchema")); } @@ -2836,7 +2836,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -2919,7 +2919,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -2989,7 +2989,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id24_StaticCmdletMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id24_StaticCmdletMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -3061,7 +3061,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id27_StaticMethodMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id27_StaticMethodMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -3181,7 +3181,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id29_StaticMethodParameterMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id29_StaticMethodParameterMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -3265,7 +3265,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id30_CmdletOutputMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id30_CmdletOutputMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -3334,7 +3334,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id19_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id19_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -3527,7 +3527,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id8_TypeMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id8_TypeMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -3593,7 +3593,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -3662,7 +3662,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -3777,7 +3777,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id31_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id31_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -3861,7 +3861,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id18_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id18_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -4048,7 +4048,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id20_QueryOption && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id20_QueryOption && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -4122,7 +4122,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id12_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id12_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id13_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) @@ -4330,7 +4330,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id9_Association && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id9_Association && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -4409,7 +4409,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -4478,7 +4478,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id7_PropertyMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id7_PropertyMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -4575,7 +4575,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id35_PropertyQuery && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id35_PropertyQuery && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id36_WildcardablePropertyQuery && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) @@ -4641,7 +4641,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id11_CmdletParameterMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id11_CmdletParameterMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id12_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) @@ -4830,7 +4830,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id6_GetCmdletParameters && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id6_GetCmdletParameters && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -5032,7 +5032,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id25_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id25_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -5135,7 +5135,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id22_CommonCmdletMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id22_CommonCmdletMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id25_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) @@ -5235,7 +5235,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id21_GetCmdletMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id21_GetCmdletMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -5304,7 +5304,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id33_InstanceMethodMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id33_InstanceMethodMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -5419,7 +5419,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id26_CommonMethodMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id26_CommonMethodMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id33_InstanceMethodMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) @@ -5492,7 +5492,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id28_CommonMethodParameterMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id28_CommonMethodParameterMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id29_StaticMethodParameterMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) @@ -5570,7 +5570,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id34_InstanceCmdletMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id34_InstanceCmdletMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -5644,7 +5644,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id3_ClassMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id3_ClassMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -5831,7 +5831,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -5908,7 +5908,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id5_ClassMetadataInstanceCmdlets && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id5_ClassMetadataInstanceCmdlets && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -5985,7 +5985,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id10_AssociationAssociatedInstance && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id10_AssociationAssociatedInstance && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -6054,7 +6054,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id14_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id14_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -6120,7 +6120,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id15_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id15_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -6186,7 +6186,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id16_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id16_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -6252,7 +6252,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id32_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id32_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -6321,7 +6321,7 @@ public object Read87_EnumMetadataEnumValue() if (isNullable) isNull = ReadNull(); if (checkType) { - if (xsiType is null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) + if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) { } else @@ -6678,7 +6678,7 @@ internal sealed class PowerShellMetadataSerializer { internal object Deserialize(XmlReader reader) { - if (reader is null) + if (reader == null) { throw new ArgumentNullException("reader"); } diff --git a/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs b/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs index 98a0034ba35..3a7e29a4c14 100644 --- a/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs +++ b/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs @@ -64,7 +64,7 @@ public override System.Collections.ObjectModel.Collection Get { // baseObject should never be null CimInstance cimInstance = baseObject as CimInstance; - if (cimInstance is null) + if (cimInstance == null) { string msg = string.Format(CultureInfo.InvariantCulture, CimInstanceTypeAdapterResources.BaseObjectNotCimInstance, @@ -103,14 +103,14 @@ public override System.Collections.ObjectModel.Collection Get /// public override PSAdaptedProperty GetProperty(object baseObject, string propertyName) { - if (propertyName is null) + if (propertyName == null) { throw new PSArgumentNullException(nameof(propertyName)); } // baseObject should never be null CimInstance cimInstance = baseObject as CimInstance; - if (cimInstance is null) + if (cimInstance == null) { string msg = string.Format(CultureInfo.InvariantCulture, CimInstanceTypeAdapterResources.BaseObjectNotCimInstance, @@ -138,14 +138,14 @@ public override PSAdaptedProperty GetProperty(object baseObject, string property /// public override PSAdaptedProperty GetFirstPropertyOrDefault(object baseObject, MemberNamePredicate predicate) { - if (predicate is null) + if (predicate == null) { throw new PSArgumentNullException(nameof(predicate)); } // baseObject should never be null CimInstance cimInstance = baseObject as CimInstance; - if (cimInstance is null) + if (cimInstance == null) { string msg = string.Format( CultureInfo.InvariantCulture, @@ -197,7 +197,7 @@ internal static string CimTypeToTypeNameDisplayString(CimType cimType) /// public override string GetPropertyTypeName(PSAdaptedProperty adaptedProperty) { - if (adaptedProperty is null) + if (adaptedProperty == null) { throw new ArgumentNullException(nameof(adaptedProperty)); } @@ -222,7 +222,7 @@ public override string GetPropertyTypeName(PSAdaptedProperty adaptedProperty) /// public override object GetPropertyValue(PSAdaptedProperty adaptedProperty) { - if (adaptedProperty is null) + if (adaptedProperty == null) { throw new ArgumentNullException(nameof(adaptedProperty)); } @@ -286,7 +286,7 @@ private List GetInheritanceChain(CimInstance cimInstance) public override Collection GetTypeNameHierarchy(object baseObject) { var cimInstance = baseObject as CimInstance; - if (cimInstance is null) + if (cimInstance == null) { throw new ArgumentNullException(nameof(baseObject)); } @@ -295,7 +295,7 @@ public override Collection GetTypeNameHierarchy(object baseObject) var typeNamesWithoutNamespace = new List(); IList inheritanceChain = GetInheritanceChain(cimInstance); - if ((inheritanceChain is null) || (inheritanceChain.Count == 0)) + if ((inheritanceChain == null) || (inheritanceChain.Count == 0)) { AddTypeNameHierarchy( typeNamesWithNamespace, @@ -357,13 +357,13 @@ public override bool IsSettable(PSAdaptedProperty adaptedProperty) return writeQualifierValue; */ - if (adaptedProperty is null) + if (adaptedProperty == null) { return false; } CimProperty cimProperty = adaptedProperty.Tag as CimProperty; - if (cimProperty is null) + if (cimProperty == null) { return false; } @@ -379,7 +379,7 @@ public override bool IsSettable(PSAdaptedProperty adaptedProperty) /// public override void SetPropertyValue(PSAdaptedProperty adaptedProperty, object value) { - if (adaptedProperty is null) + if (adaptedProperty == null) { throw new ArgumentNullException(nameof(adaptedProperty)); } diff --git a/src/System.Management.Automation/engine/AliasInfo.cs b/src/System.Management.Automation/engine/AliasInfo.cs index 6e352b02cf7..bd209c6afe8 100644 --- a/src/System.Management.Automation/engine/AliasInfo.cs +++ b/src/System.Management.Automation/engine/AliasInfo.cs @@ -168,7 +168,7 @@ public CommandInfo ResolvedCommand } } - if (result is null) + if (result == null) { // Since we couldn't resolve the command that the alias // points to, remember the definition so that we can diff --git a/src/System.Management.Automation/engine/ApplicationInfo.cs b/src/System.Management.Automation/engine/ApplicationInfo.cs index d72e0980a1f..9e785aee935 100644 --- a/src/System.Management.Automation/engine/ApplicationInfo.cs +++ b/src/System.Management.Automation/engine/ApplicationInfo.cs @@ -42,7 +42,7 @@ internal ApplicationInfo(string name, string path, ExecutionContext context) : b throw PSTraceSource.NewArgumentException(nameof(path)); } - if (context is null) + if (context == null) { throw PSTraceSource.NewArgumentNullException(nameof(context)); } @@ -91,7 +91,7 @@ public override Version Version { get { - if (_version is null) + if (_version == null) { FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(Path); _version = new Version(versionInfo.ProductMajorPart, versionInfo.ProductMinorPart, versionInfo.ProductBuildPart, versionInfo.ProductPrivatePart); @@ -123,7 +123,7 @@ public override ReadOnlyCollection OutputType { get { - if (_outputType is null) + if (_outputType == null) { List l = new List(); l.Add(new PSTypeName(typeof(string))); diff --git a/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs b/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs index c0ed9926de6..e9b6be3caff 100644 --- a/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs +++ b/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs @@ -31,7 +31,7 @@ internal Type TargetType { get { - return _convertTypes is null + return _convertTypes == null ? null : _convertTypes.LastOrDefault(); } @@ -44,7 +44,7 @@ public override object Transform(EngineIntrinsics engineIntrinsics, object input internal object Transform(EngineIntrinsics engineIntrinsics, object inputData, bool bindingParameters, bool bindingScriptCmdlet) { - if (_convertTypes is null) + if (_convertTypes == null) return inputData; object result = inputData; @@ -69,7 +69,7 @@ internal object Transform(EngineIntrinsics engineIntrinsics, object inputData, b PSReference reference = temp as PSReference; - if (reference is null) + if (reference == null) { throw new PSInvalidCastException("InvalidCastExceptionReferenceTypeExpected", null, ExtendedTypeSystem.ReferenceTypeExpected); diff --git a/src/System.Management.Automation/engine/Attributes.cs b/src/System.Management.Automation/engine/Attributes.cs index 05b7c353483..593dd89d30d 100644 --- a/src/System.Management.Automation/engine/Attributes.cs +++ b/src/System.Management.Automation/engine/Attributes.cs @@ -207,7 +207,7 @@ protected sealed override void Validate(object arguments, EngineIntrinsics engin var enumerator = _getEnumeratorSite.Target.Invoke(_getEnumeratorSite, arguments); - if (enumerator is null) + if (enumerator == null) { ValidateElement(arguments); return; @@ -551,7 +551,7 @@ public sealed class AliasAttribute : ParsingBaseAttribute /// For invalid arguments. public AliasAttribute(params string[] aliasNames) { - if (aliasNames is null) + if (aliasNames == null) { throw PSTraceSource.NewArgumentNullException(nameof(aliasNames)); } @@ -840,7 +840,7 @@ public sealed class ValidateLengthAttribute : ValidateEnumeratedArgumentsAttribu protected override void ValidateElement(object element) { string objectString = element as string; - if (objectString is null) + if (objectString == null) { throw new ValidationMetadataException( "ValidateLengthNotString", @@ -972,7 +972,7 @@ public sealed class ValidateRangeAttribute : ValidateEnumeratedArgumentsAttribut /// protected override void ValidateElement(object element) { - if (element is null) + if (element == null) { throw new ValidationMetadataException( "ArgumentIsEmpty", @@ -1009,12 +1009,12 @@ protected override void ValidateElement(object element) /// public ValidateRangeAttribute(object minRange, object maxRange) : base() { - if (minRange is null) + if (minRange == null) { throw PSTraceSource.NewArgumentNullException(nameof(minRange)); } - if (maxRange is null) + if (maxRange == null) { throw PSTraceSource.NewArgumentNullException(nameof(maxRange)); } @@ -1050,7 +1050,7 @@ public ValidateRangeAttribute(object minRange, object maxRange) : base() // minRange and maxRange have the same type, so we just need to check one of them _minComparable = minRange as IComparable; - if (_minComparable is null) + if (_minComparable == null) { throw new ValidationMetadataException( "MinRangeNotIComparable", @@ -1086,7 +1086,7 @@ public ValidateRangeAttribute(ValidateRangeKind kind) : base() private void ValidateRange(object element, ValidateRangeKind rangeKind) { Type commonType = GetCommonType(typeof(int), element.GetType()); - if (commonType is null) + if (commonType == null) { throw new ValidationMetadataException( "ValidationRangeElementType", @@ -1288,7 +1288,7 @@ public sealed class ValidatePatternAttribute : ValidateEnumeratedArgumentsAttrib /// protected override void ValidateElement(object element) { - if (element is null) + if (element == null) { throw new ValidationMetadataException( "ArgumentIsEmpty", @@ -1357,7 +1357,7 @@ public sealed class ValidateScriptAttribute : ValidateEnumeratedArgumentsAttribu /// If is invalid. protected override void ValidateElement(object element) { - if (element is null) + if (element == null) { throw new ValidationMetadataException( "ArgumentIsEmpty", @@ -1393,7 +1393,7 @@ protected override void ValidateElement(object element) /// For invalid arguments. public ValidateScriptAttribute(ScriptBlock scriptBlock) { - if (scriptBlock is null) + if (scriptBlock == null) { throw PSTraceSource.NewArgumentException(nameof(scriptBlock)); } @@ -1433,7 +1433,7 @@ public sealed class ValidateCountAttribute : ValidateArgumentsAttribute protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) { int len = 0; - if (arguments is null || arguments == AutomationNull.Value) + if (arguments == null || arguments == AutomationNull.Value) { // treat a nul list the same as an empty list // with a count of zero. @@ -1565,7 +1565,7 @@ public string[] GetValidValues() var validValuesNoCache = GenerateValidValues(); - if (validValuesNoCache is null) + if (validValuesNoCache == null) { throw new ValidationMetadataException( "ValidateSetGeneratedValidValuesListIsNull", @@ -1623,14 +1623,14 @@ public IList ValidValues { get { - if (validValuesGenerator is null) + if (validValuesGenerator == null) { return _validValues; } var validValuesLocal = validValuesGenerator.GetValidValues(); - if (validValuesLocal is null) + if (validValuesLocal == null) { throw new ValidationMetadataException( "ValidateSetGeneratedValidValuesListIsNull", @@ -1652,7 +1652,7 @@ public IList ValidValues /// protected override void ValidateElement(object element) { - if (element is null) + if (element == null) { throw new ValidationMetadataException( "ArgumentIsEmpty", @@ -1690,7 +1690,7 @@ protected override void ValidateElement(object element) /// For invalid arguments. public ValidateSetAttribute(params string[] validValues) { - if (validValues is null) + if (validValues == null) { throw PSTraceSource.NewArgumentNullException(nameof(validValues)); } @@ -1834,7 +1834,7 @@ public class ValidateDriveAttribute : ValidateArgumentsAttribute /// List of approved root drives for path. public ValidateDriveAttribute(params string[] validRootDrives) { - if (validRootDrives is null) + if (validRootDrives == null) { throw PSTraceSource.NewArgumentException(nameof(validRootDrives)); } @@ -1849,7 +1849,7 @@ public ValidateDriveAttribute(params string[] validRootDrives) /// Engine intrinsics. protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) { - if (arguments is null) + if (arguments == null) { throw new ValidationMetadataException( "PathArgumentIsEmpty", @@ -1858,7 +1858,7 @@ protected override void Validate(object arguments, EngineIntrinsics engineIntrin } var path = arguments as string; - if (path is null) + if (path == null) { throw new ValidationMetadataException( "PathArgumentIsNotValid", diff --git a/src/System.Management.Automation/engine/COM/ComAdapter.cs b/src/System.Management.Automation/engine/COM/ComAdapter.cs index f4a1d2b3a23..75e95b6082a 100644 --- a/src/System.Management.Automation/engine/COM/ComAdapter.cs +++ b/src/System.Management.Automation/engine/COM/ComAdapter.cs @@ -169,7 +169,7 @@ protected override PSMemberInfoInternalCollection GetMembers(object obj) { foreach (ComMethod method in _comTypeInfo.Methods.Values) { - if (collection[method.Name] is null) + if (collection[method.Name] == null) { PSMethod mshmethod = new PSMethod(method.Name, this, obj, method); collection.Add(mshmethod as T); diff --git a/src/System.Management.Automation/engine/COM/ComInvoker.cs b/src/System.Management.Automation/engine/COM/ComInvoker.cs index be648cf159b..3834be3de8e 100644 --- a/src/System.Management.Automation/engine/COM/ComInvoker.cs +++ b/src/System.Management.Automation/engine/COM/ComInvoker.cs @@ -138,7 +138,7 @@ internal static bool[] GetByRefArray(ParameterInformation[] parameters, int argu internal static object Invoke(IDispatch target, int dispId, object[] args, bool[] byRef, COM.INVOKEKIND invokeKind) { Diagnostics.Assert(target != null, "Caller makes sure an IDispatch object passed in."); - Diagnostics.Assert(args is null || byRef is null || args.Length == byRef.Length, + Diagnostics.Assert(args == null || byRef == null || args.Length == byRef.Length, "If 'args' and 'byRef' are not null, then they should be one-on-one mapping."); int argCount = args != null ? args.Length : 0; @@ -249,7 +249,7 @@ internal static object Invoke(IDispatch target, int dispId, object[] args, bool[ } } - var outerException = exceptionMsg is null + var outerException = exceptionMsg == null ? new TargetInvocationException(innerException) : new TargetInvocationException(exceptionMsg, innerException); throw outerException; diff --git a/src/System.Management.Automation/engine/COM/ComMethod.cs b/src/System.Management.Automation/engine/COM/ComMethod.cs index 06b1302e158..32552c6bd14 100644 --- a/src/System.Management.Automation/engine/COM/ComMethod.cs +++ b/src/System.Management.Automation/engine/COM/ComMethod.cs @@ -107,9 +107,9 @@ internal object InvokeMethod(PSMethod method, object[] arguments) { // First check if this is a severe exception. var innerCom = te.InnerException as COMException; - if (innerCom is null || innerCom.HResult != ComUtil.DISP_E_MEMBERNOTFOUND) + if (innerCom == null || innerCom.HResult != ComUtil.DISP_E_MEMBERNOTFOUND) { - string message = te.InnerException is null ? te.Message : te.InnerException.Message; + string message = te.InnerException == null ? te.Message : te.InnerException.Message; throw new MethodInvocationException( "ComMethodTargetInvocation", te, diff --git a/src/System.Management.Automation/engine/COM/ComProperty.cs b/src/System.Management.Automation/engine/COM/ComProperty.cs index 763cf3a4b3e..2de108a872e 100644 --- a/src/System.Management.Automation/engine/COM/ComProperty.cs +++ b/src/System.Management.Automation/engine/COM/ComProperty.cs @@ -51,7 +51,7 @@ internal Type Type { _cachedType = null; - if (_cachedType is null) + if (_cachedType == null) { IntPtr pFuncDesc = IntPtr.Zero; @@ -153,7 +153,7 @@ internal object GetValue(object target) catch (TargetInvocationException te) { var innerCom = te.InnerException as COMException; - if (innerCom is null || innerCom.HResult != ComUtil.DISP_E_MEMBERNOTFOUND) + if (innerCom == null || innerCom.HResult != ComUtil.DISP_E_MEMBERNOTFOUND) { throw; } @@ -197,7 +197,7 @@ internal object GetValue(object target, object[] arguments) catch (TargetInvocationException te) { var innerCom = te.InnerException as COMException; - if (innerCom is null || innerCom.HResult != ComUtil.DISP_E_MEMBERNOTFOUND) + if (innerCom == null || innerCom.HResult != ComUtil.DISP_E_MEMBERNOTFOUND) { throw; } @@ -231,7 +231,7 @@ internal void SetValue(object target, object setValue) catch (TargetInvocationException te) { var innerCom = te.InnerException as COMException; - if (innerCom is null || innerCom.HResult != ComUtil.DISP_E_MEMBERNOTFOUND) + if (innerCom == null || innerCom.HResult != ComUtil.DISP_E_MEMBERNOTFOUND) { throw; } @@ -280,7 +280,7 @@ internal void SetValue(object target, object setValue, object[] arguments) catch (TargetInvocationException te) { var innerCom = te.InnerException as COMException; - if (innerCom is null || innerCom.HResult != ComUtil.DISP_E_MEMBERNOTFOUND) + if (innerCom == null || innerCom.HResult != ComUtil.DISP_E_MEMBERNOTFOUND) { throw; } diff --git a/src/System.Management.Automation/engine/ChildrenCmdletProviderInterfaces.cs b/src/System.Management.Automation/engine/ChildrenCmdletProviderInterfaces.cs index cf51d549e9b..85cff4c8efb 100644 --- a/src/System.Management.Automation/engine/ChildrenCmdletProviderInterfaces.cs +++ b/src/System.Management.Automation/engine/ChildrenCmdletProviderInterfaces.cs @@ -33,7 +33,7 @@ private ChildItemCmdletProviderIntrinsics() /// internal ChildItemCmdletProviderIntrinsics(Cmdlet cmdlet) { - if (cmdlet is null) + if (cmdlet == null) { throw PSTraceSource.NewArgumentNullException(nameof(cmdlet)); } @@ -53,7 +53,7 @@ internal ChildItemCmdletProviderIntrinsics(Cmdlet cmdlet) /// internal ChildItemCmdletProviderIntrinsics(SessionStateInternal sessionState) { - if (sessionState is null) + if (sessionState == null) { throw PSTraceSource.NewArgumentNullException(nameof(sessionState)); } diff --git a/src/System.Management.Automation/engine/CmdletFamilyProviderInterfaces.cs b/src/System.Management.Automation/engine/CmdletFamilyProviderInterfaces.cs index ad3e48609ac..27537b21601 100644 --- a/src/System.Management.Automation/engine/CmdletFamilyProviderInterfaces.cs +++ b/src/System.Management.Automation/engine/CmdletFamilyProviderInterfaces.cs @@ -36,7 +36,7 @@ private ProviderIntrinsics() /// internal ProviderIntrinsics(Cmdlet cmdlet) { - if (cmdlet is null) + if (cmdlet == null) { throw PSTraceSource.NewArgumentNullException(nameof(cmdlet)); } @@ -57,7 +57,7 @@ internal ProviderIntrinsics(Cmdlet cmdlet) /// internal ProviderIntrinsics(SessionStateInternal sessionState) { - if (sessionState is null) + if (sessionState == null) { throw PSTraceSource.NewArgumentNullException(nameof(sessionState)); } diff --git a/src/System.Management.Automation/engine/CmdletInfo.cs b/src/System.Management.Automation/engine/CmdletInfo.cs index 3f0b0a66cec..2861fa3a8b6 100644 --- a/src/System.Management.Automation/engine/CmdletInfo.cs +++ b/src/System.Management.Automation/engine/CmdletInfo.cs @@ -108,7 +108,7 @@ public CmdletInfo(string name, Type implementingType) throw PSTraceSource.NewArgumentNullException(nameof(name)); } - if (implementingType is null) + if (implementingType == null) { throw PSTraceSource.NewArgumentNullException(nameof(name)); } @@ -250,7 +250,7 @@ public override Version Version { get { - if (_version is null) + if (_version == null) { if (Module != null) { @@ -339,7 +339,7 @@ public override ReadOnlyCollection OutputType { get { - if (_outputType is null) + if (_outputType == null) { _outputType = new List(); @@ -380,7 +380,7 @@ public override ReadOnlyCollection OutputType } } - if (provider is null) + if (provider == null) { // No path argument, so just use the current path to choose the provider. provider = Context.SessionState.Path.CurrentLocation.Provider; @@ -496,8 +496,8 @@ internal static string GetFullName(PSObject psObject) // Handle the case in one or both of the properties might not be defined. PSPropertyInfo nameProperty = psObject.Properties["Name"]; PSPropertyInfo psSnapInProperty = psObject.Properties["PSSnapIn"]; - string nameString = nameProperty is null ? string.Empty : (string)nameProperty.Value; - string psSnapInString = psSnapInProperty is null ? string.Empty : (string)psSnapInProperty.Value; + string nameString = nameProperty == null ? string.Empty : (string)nameProperty.Value; + string psSnapInString = psSnapInProperty == null ? string.Empty : (string)psSnapInProperty.Value; return GetFullName(psSnapInString, nameString); } } diff --git a/src/System.Management.Automation/engine/CmdletParameterBinderController.cs b/src/System.Management.Automation/engine/CmdletParameterBinderController.cs index 435564d5997..069201589af 100644 --- a/src/System.Management.Automation/engine/CmdletParameterBinderController.cs +++ b/src/System.Management.Automation/engine/CmdletParameterBinderController.cs @@ -52,12 +52,12 @@ internal CmdletParameterBinderController( cmdlet.Context, parameterBinder) { - if (cmdlet is null) + if (cmdlet == null) { throw PSTraceSource.NewArgumentNullException(nameof(cmdlet)); } - if (commandMetadata is null) + if (commandMetadata == null) { throw PSTraceSource.NewArgumentNullException(nameof(commandMetadata)); } @@ -276,7 +276,7 @@ internal void BindCommandLineParametersNoValidation(Collection results = scriptBlockArg.Invoke(arg); - if (results is null || results.Count == 0) + if (results == null || results.Count == 0) { continue; } @@ -514,7 +514,7 @@ private Dictionary GetQualifiedParameter uint currentParameterSetFlag, Dictionary availableParameterValuePairs) { - if (availableParameterValuePairs is null) + if (availableParameterValuePairs == null) { return null; } @@ -574,7 +574,7 @@ private List GetAliasOfCurrentCmdlet() /// private bool MatchAnyAlias(string aliasName) { - if (_aliasList is null) + if (_aliasList == null) { return false; } @@ -600,7 +600,7 @@ private bool MatchAnyAlias(string aliasName) /// Return the available parameter value pairs. Otherwise return null. private Dictionary GetDefaultParameterValuePairs(bool needToGetAlias) { - if (DefaultParameterValues is null) + if (DefaultParameterValues == null) { _useDefaultParameterBinding = false; return null; @@ -633,7 +633,7 @@ private Dictionary GetDefaultParameterVa foreach (DictionaryEntry entry in DefaultParameterValues) { string key = entry.Key as string; - if (key is null) + if (key == null) { continue; } @@ -1548,7 +1548,7 @@ private bool BindParameter( BoundObsoleteParameterNames.Add(parameter.Parameter.Name); - if (ObsoleteParameterWarningList is null) + if (ObsoleteParameterWarningList == null) ObsoleteParameterWarningList = new List(); ObsoleteParameterWarningList.Add(warningRecord); @@ -1577,7 +1577,7 @@ private void HandleRemainingArguments() { ParameterSetSpecificMetadata parameterSetData = parameter.Parameter.GetParameterSetData(_currentParameterSetFlag); - if (parameterSetData is null) + if (parameterSetData == null) { continue; } @@ -1711,7 +1711,7 @@ private void HandleCommandLineDynamicParameters(out ParameterBindingException ou if (dynamicParameterCmdlet != null) { - if (_dynamicParameterBinder is null) + if (_dynamicParameterBinder == null) { s_tracer.WriteLine("Getting the bindable object from the Cmdlet"); @@ -1799,7 +1799,7 @@ private void HandleCommandLineDynamicParameters(out ParameterBindingException ou } } - if (_dynamicParameterBinder is null) + if (_dynamicParameterBinder == null) { s_tracer.WriteLine("No dynamic parameter object was returned from the Cmdlet"); return; @@ -2934,7 +2934,7 @@ internal bool HandleUnboundMandatoryParameters( { // If the host interface wasn't specified or we were instructed not to prmopt, then throw // an exception instead - if ((Context.EngineHostInterface is null) || (!promptForMandatory)) + if ((Context.EngineHostInterface == null) || (!promptForMandatory)) { Diagnostics.Assert( Context.EngineHostInterface != null, @@ -3057,7 +3057,7 @@ private Dictionary PromptForMissingMandatoryParameters( throw bindingException; } - if ((parameters is null) || (parameters.Count == 0)) + if ((parameters == null) || (parameters.Count == 0)) { ParameterBinderBase.bindingTracer.WriteLine( "ERROR: still missing mandatory parameters after PROMPTING"); @@ -3360,7 +3360,7 @@ private bool BindPipelineParametersPrivate(PSObject inputToOperateOn) ConsolidatedString dontuseInternalTypeNames; ParameterBinderBase.bindingTracer.WriteLine( "PIPELINE object TYPE = [{0}]", - inputToOperateOn is null || inputToOperateOn == AutomationNull.Value + inputToOperateOn == null || inputToOperateOn == AutomationNull.Value ? "null" : ((dontuseInternalTypeNames = inputToOperateOn.InternalTypeNames).Count > 0 && dontuseInternalTypeNames[0] != null) ? dontuseInternalTypeNames[0] @@ -3610,7 +3610,7 @@ private bool BindValueFromPipeline( invalidCast = e.InnerException as PSInvalidCastException; } - if (invalidCast is null) + if (invalidCast == null) { parameterBindingException = e; } @@ -3661,7 +3661,7 @@ private bool BindValueFromPipelineByPropertyName( PSMemberInfo member = inputToOperateOn.Properties[parameter.Parameter.Name]; - if (member is null) + if (member == null) { // Since a member matching the name of the parameter wasn't found, // check the aliases. @@ -3824,7 +3824,7 @@ private bool InvokeAndBindDelayBindScriptBlock(PSObject inputToOperateOn, out bo throw bindingException; } - if (output is null || output.Count == 0) + if (output == null || output.Count == 0) { ParameterBindingException bindingException = new ParameterBindingException( @@ -4043,7 +4043,7 @@ internal ReflectionParameterBinder ShouldProcessParametersBinder { get { - if (_shouldProcessParameterBinder is null) + if (_shouldProcessParameterBinder == null) { // Construct a new instance of the should process parameters object ShouldProcessParameters shouldProcessParameters = new ShouldProcessParameters(_commandRuntime); @@ -4070,7 +4070,7 @@ internal ReflectionParameterBinder PagingParametersBinder { get { - if (_pagingParameterBinder is null) + if (_pagingParameterBinder == null) { // Construct a new instance of the should process parameters object PagingParameters pagingParameters = new PagingParameters(_commandRuntime); @@ -4097,7 +4097,7 @@ internal ReflectionParameterBinder TransactionParametersBinder { get { - if (_transactionParameterBinder is null) + if (_transactionParameterBinder == null) { // Construct a new instance of the transactions parameters object TransactionParameters transactionParameters = new TransactionParameters(_commandRuntime); @@ -4124,7 +4124,7 @@ internal ReflectionParameterBinder CommonParametersBinder { get { - if (_commonParametersBinder is null) + if (_commonParametersBinder == null) { // Construct a new instance of the user feedback parameters object CommonParameters commonParameters = new CommonParameters(_commandRuntime); @@ -4273,7 +4273,7 @@ private void BackupDefaultParameter(MergedCompiledCommandParameter parameter) /// private void RestoreDefaultParameterValues(IEnumerable parameters) { - if (parameters is null) + if (parameters == null) { throw PSTraceSource.NewArgumentNullException(nameof(parameters)); } @@ -4283,7 +4283,7 @@ private void RestoreDefaultParameterValues(IEnumerable public override bool ContainsKey(object key) { - if (key is null) + if (key == null) { throw PSTraceSource.NewArgumentNullException(nameof(key)); } var strKey = key as string; - if (strKey is null) { return false; } + if (strKey == null) { return false; } string keyAfterTrim = strKey.Trim(); return base.ContainsKey(keyAfterTrim); @@ -4506,13 +4506,13 @@ public override void Add(object key, object value) /// private void AddImpl(object key, object value, bool isSelfIndexing) { - if (key is null) + if (key == null) { throw PSTraceSource.NewArgumentNullException(nameof(key)); } var strKey = key as string; - if (strKey is null) + if (strKey == null) { throw PSTraceSource.NewArgumentException(nameof(key), ParameterBinderStrings.StringValueKeyExpected, key, key.GetType().FullName); } @@ -4555,10 +4555,10 @@ public override object this[object key] { get { - if (key is null) { throw PSTraceSource.NewArgumentNullException(nameof(key)); } + if (key == null) { throw PSTraceSource.NewArgumentNullException(nameof(key)); } var strKey = key as string; - if (strKey is null) { return null; } + if (strKey == null) { return null; } string keyAfterTrim = strKey.Trim(); return base[keyAfterTrim]; @@ -4576,13 +4576,13 @@ public override object this[object key] /// Key. public override void Remove(object key) { - if (key is null) + if (key == null) { throw PSTraceSource.NewArgumentNullException(nameof(key)); } var strKey = key as string; - if (strKey is null) { return; } + if (strKey == null) { return; } string keyAfterTrim = strKey.Trim(); if (base.ContainsKey(keyAfterTrim)) diff --git a/src/System.Management.Automation/engine/CodeMethods.cs b/src/System.Management.Automation/engine/CodeMethods.cs index 24acf11bdc0..7fd88909f9a 100644 --- a/src/System.Management.Automation/engine/CodeMethods.cs +++ b/src/System.Management.Automation/engine/CodeMethods.cs @@ -24,16 +24,16 @@ public static partial class ToStringCodeMethods /// Instance of PSObject wrapping a PropertyValueCollection. public static string PropertyValueCollection(PSObject instance) { - if (instance is null) + if (instance == null) return string.Empty; var values = (PropertyValueCollection)instance.BaseObject; - if (values is null) + if (values == null) return string.Empty; if (values.Count == 1) { - if (values[0] is null) + if (values[0] == null) { return string.Empty; } @@ -65,7 +65,7 @@ public static class AdapterCodeMethods [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "integer")] public static Int64 ConvertLargeIntegerToInt64(PSObject deInstance, PSObject largeIntegerInstance) { - if (largeIntegerInstance is null) + if (largeIntegerInstance == null) { throw PSTraceSource.NewArgumentException(nameof(largeIntegerInstance)); } @@ -109,7 +109,7 @@ public static Int64 ConvertLargeIntegerToInt64(PSObject deInstance, PSObject lar [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "dn", Justification = "DN represents valid prefix w.r.t Active Directory.")] public static string ConvertDNWithBinaryToString(PSObject deInstance, PSObject dnWithBinaryInstance) { - if (dnWithBinaryInstance is null) + if (dnWithBinaryInstance == null) { throw PSTraceSource.NewArgumentException(nameof(dnWithBinaryInstance)); } diff --git a/src/System.Management.Automation/engine/CommandBase.cs b/src/System.Management.Automation/engine/CommandBase.cs index fa952a38a23..720a93ab85d 100644 --- a/src/System.Management.Automation/engine/CommandBase.cs +++ b/src/System.Management.Automation/engine/CommandBase.cs @@ -159,7 +159,7 @@ internal ExecutionContext Context set { - if (value is null) + if (value == null) { throw PSTraceSource.NewArgumentNullException("Context"); } @@ -482,7 +482,7 @@ public PathInfo CurrentProviderLocation(string providerId) { using (PSTransactionManager.GetEngineProtectionScope()) { - if (providerId is null) + if (providerId == null) { throw PSTraceSource.NewArgumentNullException(nameof(providerId)); } diff --git a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs index 6689cf81fec..e00e0d737fc 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs @@ -93,7 +93,7 @@ public static Tuple MapStringInputToParsedInput(s /// public static CommandCompletion CompleteInput(string input, int cursorIndex, Hashtable options) { - if (input is null) + if (input == null) { return s_emptyCommandCompletion; } @@ -111,17 +111,17 @@ public static CommandCompletion CompleteInput(string input, int cursorIndex, Has /// public static CommandCompletion CompleteInput(Ast ast, Token[] tokens, IScriptPosition positionOfCursor, Hashtable options) { - if (ast is null) + if (ast == null) { throw PSTraceSource.NewArgumentNullException(nameof(ast)); } - if (tokens is null) + if (tokens == null) { throw PSTraceSource.NewArgumentNullException(nameof(tokens)); } - if (positionOfCursor is null) + if (positionOfCursor == null) { throw PSTraceSource.NewArgumentNullException(nameof(positionOfCursor)); } @@ -141,7 +141,7 @@ public static CommandCompletion CompleteInput(Ast ast, Token[] tokens, IScriptPo [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "powershell")] public static CommandCompletion CompleteInput(string input, int cursorIndex, Hashtable options, PowerShell powershell) { - if (input is null) + if (input == null) { return s_emptyCommandCompletion; } @@ -151,7 +151,7 @@ public static CommandCompletion CompleteInput(string input, int cursorIndex, Has throw PSTraceSource.NewArgumentException(nameof(cursorIndex)); } - if (powershell is null) + if (powershell == null) { throw PSTraceSource.NewArgumentNullException(nameof(powershell)); } @@ -215,22 +215,22 @@ public static CommandCompletion CompleteInput(string input, int cursorIndex, Has [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "powershell")] public static CommandCompletion CompleteInput(Ast ast, Token[] tokens, IScriptPosition cursorPosition, Hashtable options, PowerShell powershell) { - if (ast is null) + if (ast == null) { throw PSTraceSource.NewArgumentNullException(nameof(ast)); } - if (tokens is null) + if (tokens == null) { throw PSTraceSource.NewArgumentNullException(nameof(tokens)); } - if (cursorPosition is null) + if (cursorPosition == null) { throw PSTraceSource.NewArgumentNullException(nameof(cursorPosition)); } - if (powershell is null) + if (powershell == null) { throw PSTraceSource.NewArgumentNullException(nameof(powershell)); } @@ -328,7 +328,7 @@ public CompletionResult GetNextResult(bool forward) /// A collection of completions with the replacement start and length. internal static CommandCompletion CompleteInputInDebugger(string input, int cursorIndex, Hashtable options, Debugger debugger) { - if (input is null) + if (input == null) { return s_emptyCommandCompletion; } @@ -338,7 +338,7 @@ internal static CommandCompletion CompleteInputInDebugger(string input, int curs throw PSTraceSource.NewArgumentException(nameof(cursorIndex)); } - if (debugger is null) + if (debugger == null) { throw PSTraceSource.NewArgumentNullException(nameof(debugger)); } @@ -362,22 +362,22 @@ internal static CommandCompletion CompleteInputInDebugger(string input, int curs /// Command completion. internal static CommandCompletion CompleteInputInDebugger(Ast ast, Token[] tokens, IScriptPosition cursorPosition, Hashtable options, Debugger debugger) { - if (ast is null) + if (ast == null) { throw PSTraceSource.NewArgumentNullException(nameof(ast)); } - if (tokens is null) + if (tokens == null) { throw PSTraceSource.NewArgumentNullException(nameof(tokens)); } - if (cursorPosition is null) + if (cursorPosition == null) { throw PSTraceSource.NewArgumentNullException(nameof(cursorPosition)); } - if (debugger is null) + if (debugger == null) { throw PSTraceSource.NewArgumentNullException(nameof(debugger)); } @@ -431,7 +431,7 @@ private static void CheckScriptCallOnRemoteRunspace(RemoteRunspace remoteRunspac if (remoteRunspaceInternal != null) { var transportManager = remoteRunspaceInternal.DataStructureHandler.TransportManager; - if (transportManager != null && transportManager.TypeTable is null) + if (transportManager != null && transportManager.TypeTable == null) { // The remote runspace was created without a TypeTable instance. // The tab completion results cannot be deserialized if the TypeTable is not available @@ -450,7 +450,7 @@ private static CommandCompletion CallScriptWithStringParameterSet(string input, .AddArgument(cursorIndex) .AddArgument(options); var results = powershell.Invoke(); - if (results is null) + if (results == null) { return s_emptyCommandCompletion; } @@ -487,7 +487,7 @@ private static CommandCompletion CallScriptWithAstParameterSet(Ast ast, Token[] .AddArgument(cursorPosition) .AddArgument(options); var results = powershell.Invoke(); - if (results is null) + if (results == null) { return s_emptyCommandCompletion; } @@ -543,7 +543,7 @@ private static CommandCompletion CompleteInputImpl(Ast ast, Token[] tokens, IScr replacementIndex += inputAndCursor.Item3; } - if (results is null || results.Count == 0) + if (results == null || results.Count == 0) { /* BROKEN code commented out, fix sometime // If we were invoked from TabExpansion2, we want to "remove" TabExpansion2 and anything it calls @@ -661,7 +661,7 @@ private static List InvokeLegacyTabExpansion(PowerShell powers foreach (var oldResult in oldResults) { var completionResult = PSObject.Base(oldResult) as CompletionResult; - if (completionResult is null) + if (completionResult == null) { var oldResultStr = oldResult.ToString(); @@ -681,7 +681,7 @@ private static List InvokeLegacyTabExpansion(PowerShell powers } } - if (remoteToWin7 && (results is null || results.Count == 0)) + if (remoteToWin7 && (results == null || results.Count == 0)) { string quoteStr = quote == '\0' ? string.Empty : quote.ToString(); results = PSv2CompletionCompleter.PSv2GenerateMatchSetOfFiles(helper, lastword, replacementIndex == 0, quoteStr); @@ -814,7 +814,7 @@ private static void AddCommandResult(CommandAndName commandAndName, bool useFull string quotedFileName = AddQuoteIfNecessary(name, quote, completingAtStartOfLine); var commandType = SafeGetProperty(commandAndName.Command, "CommandType"); - if (commandType is null) + if (commandType == null) { return; } @@ -973,13 +973,13 @@ private static string AddQuoteIfNecessary(string completionText, string quote, b private static IEnumerable CombineMatchSets(List s1, List s2) { - if (s1 is null || s1.Count < 1) + if (s1 == null || s1.Count < 1) { // only s2 contains results; which may be null or empty return s2; } - if (s2 is null || s2.Count < 1) + if (s2 == null || s2.Count < 1) { // only s1 contains results return s1; @@ -1021,19 +1021,19 @@ private static IEnumerable CombineMatchSets(List(PSObject psObject, string propertyName) { - if (psObject is null) + if (psObject == null) { return default(T); } PSPropertyInfo property = psObject.Properties[propertyName]; - if (property is null) + if (property == null) { return default(T); } object propertyValue = property.Value; - if (propertyValue is null) + if (propertyValue == null) { return default(T); } @@ -1106,7 +1106,7 @@ private static List PSv2FindMatches(PowerShellExecutio } Collection paths = helper.ExecuteCurrentPowerShell(out exceptionThrown); - if (paths is null || paths.Count == 0) + if (paths == null || paths.Count == 0) { return null; } @@ -1120,7 +1120,7 @@ private static List PSv2FindMatches(PowerShellExecutio PSObject item = pathsArray[1] as PSObject; object convertedPath = pathsArray[1]; - if (objectPath is null || item is null || convertedPath is null) + if (objectPath == null || item == null || convertedPath == null) { continue; } diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs index 1d6b3a3666d..bbc85aa4003 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs @@ -35,7 +35,7 @@ internal class CompletionContext internal bool GetOption(string option, bool @default) { - if (Options is null || !Options.ContainsKey(option)) + if (Options == null || !Options.ContainsKey(option)) { return @default; } @@ -111,7 +111,7 @@ private CompletionContext InitializeCompletionContext(TypeInferenceContext typeI IScriptPosition positionForAstSearch = _cursorPosition; var adjustLineAndColumn = false; var tokenAtCursor = InterstingTokenAtCursorOrDefault(_tokens, _cursorPosition); - if (tokenAtCursor is null) + if (tokenAtCursor == null) { tokenBeforeCursor = InterstingTokenBeforeCursorOrDefault(_tokens, _cursorPosition); if (tokenBeforeCursor != null) @@ -131,9 +131,9 @@ private CompletionContext InitializeCompletionContext(TypeInferenceContext typeI var asts = AstSearcher.FindAll(_ast, ast => IsCursorWithinOrJustAfterExtent(positionForAstSearch, ast.Extent), searchNestedScriptBlocks: true).ToList(); - Diagnostics.Assert(tokenAtCursor is null || tokenBeforeCursor is null, "Only one of these tokens can be non-null"); + Diagnostics.Assert(tokenAtCursor == null || tokenBeforeCursor == null, "Only one of these tokens can be non-null"); - if (typeInferenceContext.CurrentTypeDefinitionAst is null) + if (typeInferenceContext.CurrentTypeDefinitionAst == null) { typeInferenceContext.CurrentTypeDefinitionAst = Ast.GetAncestorTypeDefinitionAst(asts.Last()); } @@ -193,13 +193,13 @@ private static bool CompleteAgainstSwitchFile(Ast lastAst, Token tokenBeforeCurs { // Handle "switch -file m" or "switch -file *.ps1" var pipeline = lastAst.Parent.Parent as PipelineAst; - if (pipeline is null) + if (pipeline == null) { return false; } errorStatement = pipeline.Parent as ErrorStatementAst; - if (errorStatement is null || errorStatement.Kind is null || errorStatement.Flags is null) + if (errorStatement == null || errorStatement.Kind == null || errorStatement.Flags == null) { return false; } @@ -730,7 +730,7 @@ internal List GetResultHelper(CompletionContext completionCont // DependsOn='' // | result = GetResultForHashtable(completionContext); - if (result is null || result.Count == 0) + if (result == null || result.Count == 0) { DynamicKeywordStatementAst keywordAst; ConfigurationDefinitionAst configAst = GetAncestorConfigurationAstAndKeywordAst(cursor, lastAst, out keywordAst); @@ -741,7 +741,7 @@ internal List GetResultHelper(CompletionContext completionCont } } } - else if (completionContext.TokenAtCursor is null) + else if (completionContext.TokenAtCursor == null) { if (tokenBeforeCursor != null) { @@ -828,7 +828,7 @@ internal List GetResultHelper(CompletionContext completionCont } } - if (result is null || result.Count == 0) + if (result == null || result.Count == 0) { var typeAst = completionContext.RelatedAsts.OfType().FirstOrDefault(); TypeName typeNameToComplete = null; @@ -856,12 +856,12 @@ internal List GetResultHelper(CompletionContext completionCont } } - if (result is null || result.Count == 0) + if (result == null || result.Count == 0) { result = GetResultForHashtable(completionContext); } - if (result is null || result.Count == 0) + if (result == null || result.Count == 0) { // Handle special file completion scenarios: .\+file.txt -> + string input = completionContext.RelatedAsts[0].Extent.Text; @@ -895,7 +895,7 @@ private List GetResultForHashtable(CompletionContext completio else if (cursor.Offset == hashTableAst.Extent.EndOffset) { // Exclude the scenario that cursor at the end of hashtable, i.e. after '}' - if (completionContext.TokenAtCursor is null || + if (completionContext.TokenAtCursor == null || completionContext.TokenAtCursor.Kind != TokenKind.RCurly) { tempHashtableAst = hashTableAst; @@ -1116,7 +1116,7 @@ private static bool TryGetTypeConstraintOnVariable( PSVariable variable = completionContext.ExecutionContext.EngineSessionState.GetVariable(variableName); - if (variable is null || variable.Attributes.Count == 0) + if (variable == null || variable.Attributes.Count == 0) { return false; } @@ -1176,7 +1176,7 @@ bool TryGetResultForSet(Type typeConstraint, ValidateSetAttribute setConstraint, ValidateSetAttribute setConstraint = null; VariableExpressionAst variableAst = GetVariableFromExpressionAst(assignmentAst.Left, ref typeConstraint, ref setConstraint); - if (variableAst is null) + if (variableAst == null) { return false; } @@ -1386,7 +1386,7 @@ private List GetResultForEnumPropertyValueOfDSCResource( { IEnumerable orderedValues = property.ValueMap.Keys.OrderBy(x => x).Where(v => !existingValues.Contains(v, StringComparer.OrdinalIgnoreCase)); var matchedResults = orderedValues.Where(v => wildcardPattern.IsMatch(v)); - if (matchedResults is null || !matchedResults.Any()) + if (matchedResults == null || !matchedResults.Any()) { // Fallback to all allowed values matchedResults = orderedValues; @@ -1437,7 +1437,7 @@ private List GetResultForEnumPropertyValueOfDSCResource( } var matchedResults = allResources.Where(r => wildcardPattern.IsMatch(r)); - if (matchedResults is null || !matchedResults.Any()) + if (matchedResults == null || !matchedResults.Any()) { // Fallback to all allowed values matchedResults = allResources; @@ -1477,7 +1477,7 @@ private List GetResultForString(CompletionContext completionCo List result = null; var expandableString = lastAst as ExpandableStringExpressionAst; var constantString = lastAst as StringConstantExpressionAst; - if (constantString is null && expandableString is null) { return null; } + if (constantString == null && expandableString == null) { return null; } string strValue = constantString != null ? constantString.Value : expandableString.Value; StringConstantType strType = constantString != null ? constantString.StringConstantType : expandableString.StringConstantType; @@ -1652,7 +1652,7 @@ private List GetResultForIdentifierInConfiguration( // Filter by name var matchedResults = keywords.Where(k => wildcardPattern.IsMatch(k.Keyword)); - if (matchedResults is null || !matchedResults.Any()) + if (matchedResults == null || !matchedResults.Any()) { // Fallback to all legal keywords in the configuration statement matchedResults = keywords; @@ -1665,7 +1665,7 @@ private List GetResultForIdentifierInConfiguration( foreach (var keyword in matchedResults) { string usageString = Microsoft.PowerShell.DesiredStateConfiguration.Internal.DscClassCache.GetDSCResourceUsageString(keyword); - if (results is null) + if (results == null) { results = new List(); } @@ -1793,7 +1793,7 @@ private List GetResultForIdentifier(CompletionContext completi executionContext: completionContext.ExecutionContext) : null; - if (fullPath is null) { return result; } + if (fullPath == null) { return result; } // Continue trying the filename/commandname completion for scenarios like this: $aa\d completionContext.WordToComplete = fullPath; @@ -2093,7 +2093,7 @@ private static List CompleteFileNameAsCommand(CompletionContex var result = new List(); var clearLiteralPathsKey = false; - if (completionContext.Options is null) + if (completionContext.Options == null) { completionContext.Options = new Hashtable { { "LiteralPaths", true } }; } diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index 61fdb8f5489..b6c7d88a111 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -65,7 +65,7 @@ public static IEnumerable CompleteCommand(string commandName) public static IEnumerable CompleteCommand(string commandName, string moduleName, CommandTypes commandTypes = CommandTypes.All) { var runspace = Runspace.DefaultRunspace; - if (runspace is null) + if (runspace == null) { // No runspace, just return no results. return CommandCompletion.EmptyCompletionResult; @@ -167,7 +167,7 @@ List ExecuteGetCommandCommand(bool useModulePrefix) Exception exceptionThrown; var commandInfos = context.Helper.ExecuteCurrentPowerShell(out exceptionThrown); - if (commandInfos is null || commandInfos.Count == 0) + if (commandInfos == null || commandInfos.Count == 0) { powershell.Commands.Clear(); powershell @@ -268,7 +268,7 @@ internal static CompletionResult GetCommandNameCompletionResult(string name, obj internal static List MakeCommandsUnique(IEnumerable commandInfoPsObjs, bool includeModulePrefix, bool addAmpersandIfNecessary, string quote) { List results = new List(); - if (commandInfoPsObjs is null || !commandInfoPsObjs.Any()) + if (commandInfoPsObjs == null || !commandInfoPsObjs.Any()) { return results; } @@ -303,7 +303,7 @@ internal static List MakeCommandsUnique(IEnumerable else { name = baseObj as string; - if (name is null) { continue; } + if (name == null) { continue; } } object value; @@ -332,7 +332,7 @@ internal static List MakeCommandsUnique(IEnumerable var commandList = keyValuePair.Value as List; if (commandList != null) { - if (endResults is null) + if (endResults == null) { endResults = new List(); } @@ -494,7 +494,7 @@ internal static List CompleteCommandParameter(CompletionContex DynamicKeywordStatementAst keywordAst = null; for (int i = context.RelatedAsts.Count - 1; i >= 0; i--) { - if (keywordAst is null) + if (keywordAst == null) keywordAst = context.RelatedAsts[i] as DynamicKeywordStatementAst; parameterAst = (context.RelatedAsts[i] as CommandParameterAst); if (parameterAst != null) break; @@ -543,7 +543,7 @@ internal static List CompleteCommandParameter(CompletionContex { // No CommandParameterAst is found. It could be a StringConstantExpressionAst "-" var dashAst = (context.RelatedAsts[context.RelatedAsts.Count - 1] as StringConstantExpressionAst); - if (dashAst is null) + if (dashAst == null) return result; if (!dashAst.Value.Trim().Equals("-", StringComparison.OrdinalIgnoreCase)) return result; @@ -557,7 +557,7 @@ internal static List CompleteCommandParameter(CompletionContex .DoPseudoParameterBinding(commandAst, null, parameterAst, PseudoParameterBinder.BindingType.ParameterCompletion); // The command cannot be found or it's not a cmdlet, not a script cmdlet, not a function. // Try completing as if it the parameter is a command argument for native command completion. - if (pseudoBinding is null) + if (pseudoBinding == null) { return CompleteCommandArgument(context); } @@ -1005,7 +1005,7 @@ internal static List CompleteCommandArgument(CompletionContext } } - if (commandAst is null) + if (commandAst == null) { // We don't know if this could be expanded into anything interesting return result; @@ -1017,7 +1017,7 @@ internal static List CompleteCommandArgument(CompletionContext do { // The command cannot be found, or it's NOT a cmdlet, NOT a script cmdlet and NOT a function - if (pseudoBinding is null) + if (pseudoBinding == null) break; bool parsedArgumentsProvidesMatch = false; @@ -1110,7 +1110,7 @@ internal static List CompleteCommandArgument(CompletionContext } else { - if (prevElem is CommandParameterAst && ((CommandParameterAst)prevElem).Argument is null) + if (prevElem is CommandParameterAst && ((CommandParameterAst)prevElem).Argument == null) { var paramName = ((CommandParameterAst)prevElem).ParameterName; var pattern = WildcardPattern.Get(paramName + "*", WildcardOptions.IgnoreCase); @@ -1156,7 +1156,7 @@ internal static List CompleteCommandArgument(CompletionContext // Handle some special cases such as: // & "get-comm --> & "Get-Command" // & "sa --> & ".\sa[v].txt" - if (expressionAst is null && !hasBeenProcessed && + if (expressionAst == null && !hasBeenProcessed && commandAst.CommandElements.Count == 1 && commandAst.InvocationOperator != TokenKind.Unknown && context.WordToComplete != string.Empty) @@ -1313,7 +1313,7 @@ internal static List CompleteCommandArgument(CompletionContext } var clearLiteralPathKey = false; - if (pseudoBinding is null) + if (pseudoBinding == null) { // the command could be a native command such as notepad.exe, we use literal path in this case clearLiteralPathKey = TurnOnLiteralPathOption(context); @@ -1443,7 +1443,7 @@ private static List GetArgumentCompletionResultsWithSuccessful Diagnostics.Assert(bindingInfo.InfoType.Equals(PseudoBindingInfoType.PseudoBindingSucceed), "Caller needs to make sure the pseudo binding was successful"); List result = new List(); - if (argLocation.IsPositional && argLocation.Argument is null) + if (argLocation.IsPositional && argLocation.Argument == null) { AstPair lastPositionalArg; AstParameterArgumentPair targetPositionalArg = @@ -1608,7 +1608,7 @@ private static void CompletePositionalArgument( } else { - if (positionalParam is null) + if (positionalParam == null) positionalParam = param; } } @@ -1813,7 +1813,7 @@ private static IEnumerable NativeCommandArgumentCompletion_InferType CompletionContext context, string parameterName) { - if (boundArguments is null) + if (boundArguments == null) { yield break; } @@ -1860,13 +1860,13 @@ private static IEnumerable NativeCommandArgumentCompletion_InferType break; } - if (argumentAst is null) + if (argumentAst == null) { yield break; } ExpressionAst argumentExpressionAst = argumentAst as ExpressionAst; - if (argumentExpressionAst is null) + if (argumentExpressionAst == null) { CommandExpressionAst argumentCommandExpressionAst = argumentAst as CommandExpressionAst; if (argumentCommandExpressionAst != null) @@ -1884,7 +1884,7 @@ private static IEnumerable NativeCommandArgumentCompletion_InferType new object[] { argumentValue }; foreach (var element in enumerable) { - if (element is null) + if (element == null) { continue; } @@ -1917,7 +1917,7 @@ internal static IList NativeCommandArgumentCompletion_ExtractSecondaryAr { List result = new List(); - if (boundArguments is null) + if (boundArguments == null) { return result; } @@ -2164,7 +2164,7 @@ private static void NativeCommandArgumentCompletion( } case "Get-Module": { - bool loadedModulesOnly = boundArguments is null || !boundArguments.ContainsKey("ListAvailable"); + bool loadedModulesOnly = boundArguments == null || !boundArguments.ContainsKey("ListAvailable"); bool skipEditionCheck = !loadedModulesOnly && boundArguments.ContainsKey("SkipEditionCheck"); NativeCompletionModuleCommands(context, parameterName, result, loadedModulesOnly, skipEditionCheck: skipEditionCheck); break; @@ -2458,7 +2458,7 @@ private static bool InvokeScriptArgumentCompleter( { } - if (customResults is null || customResults.Count == 0) + if (customResults == null || customResults.Count == 0) { return false; } @@ -2798,13 +2798,13 @@ private static void NativeCompletionCimNamespace( } CimProperty namespaceNameProperty = namespaceInstance.CimInstanceProperties["Name"]; - if (namespaceNameProperty is null) + if (namespaceNameProperty == null) { continue; } string childNamespace = namespaceNameProperty.Value as string; - if (childNamespace is null) + if (childNamespace == null) { continue; } @@ -2837,7 +2837,7 @@ private static void NativeCompletionGetCommand(CompletionContext context, string result.AddRange(commandResults); // Consider files only if the -Module parameter is not present - if (moduleName is null) + if (moduleName == null) { // ps1 files and directories. We only complete the files with .ps1 extension for Get-Command, because the -Syntax // may only works on files with .ps1 extension @@ -2988,7 +2988,7 @@ private static void NativeCompletionJobCommands(CompletionContext context, strin Exception exceptionThrown; var psObjects = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); - if (psObjects is null) + if (psObjects == null) return; if (paramName.Equals("Id", StringComparison.OrdinalIgnoreCase)) @@ -3080,7 +3080,7 @@ private static void NativeCompletionScheduledJobCommands(CompletionContext conte Exception exceptionThrown; var psObjects = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); - if (psObjects is null) + if (psObjects == null) return; if (paramName.Equals("Id", StringComparison.OrdinalIgnoreCase)) @@ -3212,7 +3212,7 @@ private static void NativeCompletionProcessCommands(CompletionContext context, s Exception exceptionThrown; var psObjects = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); - if (psObjects is null) + if (psObjects == null) return; if (paramName.Equals("Id", StringComparison.OrdinalIgnoreCase)) @@ -3294,7 +3294,7 @@ private static void NativeCompletionProviderCommands(CompletionContext context, var powerShellExecutionHelper = context.Helper; powerShellExecutionHelper.AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-PSProvider").AddParameter("PSProvider", providerName); var psObjects = powerShellExecutionHelper.ExecuteCurrentPowerShell(out _); - if (psObjects is null) + if (psObjects == null) return; foreach (dynamic providerInfo in psObjects) @@ -3471,7 +3471,7 @@ private static void NativeCompletionVariableCommands(CompletionContext context, var powerShellExecutionHelper = context.Helper; var powershell = powerShellExecutionHelper.AddCommandWithPreferenceSetting("Microsoft.PowerShell.Utility\\Get-Variable").AddParameter("Name", variableName); var psObjects = powerShellExecutionHelper.ExecuteCurrentPowerShell(out _); - if (psObjects is null) + if (psObjects == null) return; foreach (dynamic variable in psObjects) @@ -3593,7 +3593,7 @@ private static void NativeCompletionTraceSourceCommands(CompletionContext contex var powershell = powerShellExecutionHelper.AddCommandWithPreferenceSetting("Microsoft.PowerShell.Utility\\Get-TraceSource").AddParameter("Name", traceSourceName); Exception exceptionThrown; var psObjects = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); - if (psObjects is null) + if (psObjects == null) return; foreach (dynamic trace in psObjects) @@ -3794,7 +3794,7 @@ private static void NativeCompletionMemberName(CompletionContext context, List CompleteFilename(string fileName) { var runspace = Runspace.DefaultRunspace; - if (runspace is null) + if (runspace == null) { // No runspace, just return no results. return CommandCompletion.EmptyCompletionResult; @@ -4362,8 +4362,8 @@ internal static IEnumerable CompleteFilename(CompletionContext } } - if (path is null) continue; - if (isFileSystem && providerPath is null) continue; + if (path == null) continue; + if (isFileSystem && providerPath == null) continue; string completionText; if (relativePaths) @@ -4552,11 +4552,11 @@ internal static List GetFileShares(string machine, bool ignoreHidden) private static bool CheckFileExtension(string path, HashSet extension) { - if (extension is null || extension.Count == 0) + if (extension == null || extension.Count == 0) return true; var ext = System.IO.Path.GetExtension(path); - return ext is null || extension.Contains(ext); + return ext == null || extension.Contains(ext); } #endregion Filenames @@ -4570,7 +4570,7 @@ private static bool CheckFileExtension(string path, HashSet extension) public static IEnumerable CompleteVariable(string variableName) { var runspace = Runspace.DefaultRunspace; - if (runspace is null) + if (runspace == null) { // No runspace, just return no results. return CommandCompletion.EmptyCompletionResult; @@ -4974,7 +4974,7 @@ internal static List CompleteComment(CompletionContext context { var psobj = psobjs[index]; var historyInfo = PSObject.Base(psobj) as HistoryInfo; - if (historyInfo is null) continue; + if (historyInfo == null) continue; var commandLine = historyInfo.CommandLine; if (!string.IsNullOrEmpty(commandLine) && pattern.IsMatch(commandLine)) @@ -5050,7 +5050,7 @@ internal static List CompleteMember(CompletionContext context, memberName = memberNameAst.Value + "*"; } } - else if (!(lastAst is ErrorExpressionAst) && targetExpr is null) + else if (!(lastAst is ErrorExpressionAst) && targetExpr == null) { // I don't think we can complete anything interesting return results; @@ -5088,7 +5088,7 @@ internal static List CompleteMember(CompletionContext context, // a MemberExpressionAst '$xml.$xml', whose parent is still a MemberExpressionAst '$xml.$xml.Save'. // But here we DO NOT want to re-assign 'targetExpr' to be '$xml.$xml'. 'targetExpr' in this case // should be '$xml'. - if (targetExpr is null) + if (targetExpr == null) { var memberExprAst = (MemberExpressionAst)lastAst.Parent; targetExpr = memberExprAst.Expression; @@ -5107,7 +5107,7 @@ internal static List CompleteMember(CompletionContext context, } } - if (targetExpr is null) + if (targetExpr == null) { // Not sure what we have, but we're not looking for members. return results; @@ -5341,7 +5341,7 @@ private static void AddInferredMember(object member, WildcardPattern memberNameP getToolTip = memberAst.GetTooltip; } - if (memberName is null || !memberNamePattern.IsMatch(memberName)) + if (memberName == null || !memberNamePattern.IsMatch(memberName)) { return; } @@ -5474,7 +5474,7 @@ internal string ShortTypeName { get { - if (_shortTypeName is null) + if (_shortTypeName == null) { int lastDotIndex = FullTypeName.LastIndexOf('.'); int lastPlusIndex = FullTypeName.LastIndexOf('+'); @@ -5496,7 +5496,7 @@ internal string Namespace { get { - if (_namespace is null) + if (_namespace == null) { int lastDotIndex = FullTypeName.LastIndexOf('.'); _namespace = FullTypeName.Substring(0, lastDotIndex); @@ -5942,7 +5942,7 @@ internal static List CompleteNamespace(CompletionContext conte var results = new List(); var wordToComplete = context.WordToComplete; var dots = wordToComplete.Count(c => c == '.'); - if (dots >= localTypeCache.Length || localTypeCache[dots] is null) + if (dots >= localTypeCache.Length || localTypeCache[dots] == null) { return results; } @@ -5969,7 +5969,7 @@ internal static List CompleteNamespace(CompletionContext conte public static IEnumerable CompleteType(string typeName) { // When completing types, we don't care about the runspace, types are visible across the appdomain - var powershell = (Runspace.DefaultRunspace is null) + var powershell = (Runspace.DefaultRunspace == null) ? PowerShell.Create() : PowerShell.Create(RunspaceMode.CurrentRunspace); @@ -5986,7 +5986,7 @@ internal static List CompleteType(CompletionContext context, s var completionTextSet = new HashSet(StringComparer.OrdinalIgnoreCase); var wordToComplete = context.WordToComplete; var dots = wordToComplete.Count(c => c == '.'); - if (dots >= localTypeCache.Length || localTypeCache[dots] is null) + if (dots >= localTypeCache.Length || localTypeCache[dots] == null) { return results; } @@ -6037,7 +6037,7 @@ internal static List CompleteType(CompletionContext context, s private static string GetNamespaceToRemove(CompletionContext context, TypeCompletionBase completion) { - if (completion is NamespaceCompletion || context.RelatedAsts is null || context.RelatedAsts.Count == 0) + if (completion is NamespaceCompletion || context.RelatedAsts == null || context.RelatedAsts.Count == 0) { return null; } @@ -6113,7 +6113,7 @@ internal static List CompleteHelpTopics(CompletionContext cont { foreach (string file in files) { - if (file is null) + if (file == null) { continue; } @@ -6121,7 +6121,7 @@ internal static List CompleteHelpTopics(CompletionContext cont try { var fileName = Path.GetFileName(file); - if (fileName is null || !topicPattern.IsMatch(fileName)) + if (fileName == null || !topicPattern.IsMatch(fileName)) continue; // All topic files are ending with ".help.txt" @@ -6254,7 +6254,7 @@ internal static List CompleteHashtableKeyForDynamicKeyword( // Filter by name var wildcardPattern = WildcardPattern.Get(memberPattern, WildcardOptions.IgnoreCase); var matchedResults = tempProperties.Where(p => wildcardPattern.IsMatch(p.Key)); - if (matchedResults is null || !matchedResults.Any()) + if (matchedResults == null || !matchedResults.Any()) { // Fallback to all non-exist properties in the hashtable statement matchedResults = tempProperties; @@ -6350,7 +6350,7 @@ internal static List CompleteHashtableKey(CompletionContext co if (commandAst != null) { var binding = new PseudoParameterBinder().DoPseudoParameterBinding(commandAst, null, null, bindingType: PseudoParameterBinder.BindingType.ArgumentCompletion); - if (binding is null) + if (binding == null) { return null; } @@ -6461,7 +6461,7 @@ internal static bool IsPathSafelyExpandable(ExpandableStringExpressionAst expand foreach (ExpressionAst nestedAst in expandableStringAst.NestedExpressions) { var variableAst = nestedAst as VariableExpressionAst; - if (variableAst is null) { return false; } + if (variableAst == null) { return false; } string strValue = CombineVariableWithPartialPath(variableAst, null, executionContext); if (strValue != null) @@ -6490,9 +6490,9 @@ internal static string CombineVariableWithPartialPath(VariableExpressionAst vari { // We check the strict mode inside GetVariableValue object value = VariableOps.GetVariableValue(varPath, executionContext, variableAst); - var strValue = (value is null) ? string.Empty : value as string; + var strValue = (value == null) ? string.Empty : value as string; - if (strValue is null) + if (strValue == null) { object baseObj = PSObject.Base(value); if (baseObj is string || baseObj.GetType().IsPrimitive) @@ -6587,7 +6587,7 @@ internal static void CompleteMemberHelper( if (@static) { var type = PSObject.Base(value) as Type; - if (type is null) + if (type == null) { return; } @@ -6654,7 +6654,7 @@ internal static void CompleteMemberHelper( foreach (DictionaryEntry entry in dictionary) { var key = entry.Key as string; - if (key is null) + if (key == null) continue; if (pattern.IsMatch(key)) @@ -6686,7 +6686,7 @@ private static bool IsValueEnumerable(object value) { object baseValue = PSObject.Base(value); - if (baseValue is null || baseValue is string || baseValue is PSObject || + if (baseValue == null || baseValue is string || baseValue is PSObject || baseValue is IDictionary || baseValue is System.Xml.XmlNode) { return false; @@ -6767,7 +6767,7 @@ private static bool TurnOnLiteralPathOption(CompletionContext completionContext) { bool clearLiteralPathsKey = false; - if (completionContext.Options is null) + if (completionContext.Options == null) { completionContext.Options = new Hashtable { { "LiteralPaths", true } }; clearLiteralPathsKey = true; @@ -6861,7 +6861,7 @@ public int Compare(PSObject x, PSObject y) var yCommandInfo = yObj as CommandInfo; yName = yCommandInfo != null ? yCommandInfo.Name : yObj as string; - if (xName is null || yName is null) + if (xName == null || yName == null) Diagnostics.Assert(false, "Base object of Command PSObject should be either CommandInfo or string"); return string.Compare(xName, yName, StringComparison.OrdinalIgnoreCase); diff --git a/src/System.Management.Automation/engine/CommandCompletion/ExtensibleCompletion.cs b/src/System.Management.Automation/engine/CommandCompletion/ExtensibleCompletion.cs index 350322e38c9..9bb33ef56ba 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/ExtensibleCompletion.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/ExtensibleCompletion.cs @@ -32,7 +32,7 @@ public class ArgumentCompleterAttribute : Attribute /// The type must implement and have a default constructor. public ArgumentCompleterAttribute(Type type) { - if (type is null || (type.GetInterfaces().All(t => t != typeof(IArgumentCompleter)))) + if (type == null || (type.GetInterfaces().All(t => t != typeof(IArgumentCompleter)))) { throw PSTraceSource.NewArgumentException(nameof(type)); } @@ -46,7 +46,7 @@ public ArgumentCompleterAttribute(Type type) /// public ArgumentCompleterAttribute(ScriptBlock scriptBlock) { - if (scriptBlock is null) + if (scriptBlock == null) { throw PSTraceSource.NewArgumentNullException(nameof(scriptBlock)); } @@ -127,7 +127,7 @@ protected override void EndProcessing() (Context.NativeArgumentCompleters = new Dictionary(StringComparer.OrdinalIgnoreCase)); } - if (CommandName is null || CommandName.Length == 0) + if (CommandName == null || CommandName.Length == 0) { CommandName = new[] { "" }; } @@ -174,7 +174,7 @@ public class ArgumentCompletionsAttribute : Attribute /// For invalid arguments. public ArgumentCompletionsAttribute(params string[] completions) { - if (completions is null) + if (completions == null) { throw PSTraceSource.NewArgumentNullException(nameof(completions)); } diff --git a/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs b/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs index 1287dd586c8..d19a4b9bddb 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs @@ -74,7 +74,7 @@ internal sealed class PipeObjectPair : AstParameterArgumentPair { internal PipeObjectPair(string parameterName, Type pipeObjType) { - if (parameterName is null) + if (parameterName == null) throw PSTraceSource.NewArgumentNullException(nameof(parameterName)); Parameter = null; @@ -95,9 +95,9 @@ internal sealed class AstArrayPair : AstParameterArgumentPair { internal AstArrayPair(string parameterName, ICollection arguments) { - if (parameterName is null) + if (parameterName == null) throw PSTraceSource.NewArgumentNullException(nameof(parameterName)); - if (arguments is null || arguments.Count == 0) + if (arguments == null || arguments.Count == 0) throw PSTraceSource.NewArgumentNullException(nameof(arguments)); Parameter = null; @@ -124,7 +124,7 @@ internal sealed class FakePair : AstParameterArgumentPair { internal FakePair(CommandParameterAst parameterAst) { - if (parameterAst is null) + if (parameterAst == null) throw PSTraceSource.NewArgumentNullException(nameof(parameterAst)); Parameter = parameterAst; @@ -144,7 +144,7 @@ internal sealed class SwitchPair : AstParameterArgumentPair { internal SwitchPair(CommandParameterAst parameterAst) { - if (parameterAst is null) + if (parameterAst == null) throw PSTraceSource.NewArgumentNullException(nameof(parameterAst)); Parameter = parameterAst; @@ -174,7 +174,7 @@ internal sealed class AstPair : AstParameterArgumentPair { internal AstPair(CommandParameterAst parameterAst) { - if (parameterAst is null || parameterAst.Argument is null) + if (parameterAst == null || parameterAst.Argument == null) throw PSTraceSource.NewArgumentException(nameof(parameterAst)); Parameter = parameterAst; @@ -194,7 +194,7 @@ internal AstPair(CommandParameterAst parameterAst, ExpressionAst argumentAst) if (parameterAst != null && parameterAst.Argument != null) throw PSTraceSource.NewArgumentException(nameof(parameterAst)); - if (parameterAst is null && argumentAst is null) + if (parameterAst == null && argumentAst == null) throw PSTraceSource.NewArgumentNullException(nameof(argumentAst)); Parameter = parameterAst; @@ -214,7 +214,7 @@ internal AstPair(CommandParameterAst parameterAst, CommandElementAst argumentAst if (parameterAst != null && parameterAst.Argument != null) throw PSTraceSource.NewArgumentException(nameof(parameterAst)); - if (parameterAst is null || argumentAst is null) + if (parameterAst == null || argumentAst == null) throw PSTraceSource.NewArgumentNullException(nameof(argumentAst)); Parameter = parameterAst; @@ -328,11 +328,11 @@ public static StaticBindingResult BindCommand(CommandAst commandAst, bool resolv } PseudoBindingInfo pseudoBinding = null; - if (Runspace.DefaultRunspace is null) + if (Runspace.DefaultRunspace == null) { // Handle static binding from a non-PowerShell / C# application // DefaultRunspace is a thread static field, so race condition will not happen because different threads will access different instances of "DefaultRunspace" - if (t_bindCommandRunspace is null) + if (t_bindCommandRunspace == null) { // Create a mini runspace by remove the types and formats InitialSessionState minimalState = InitialSessionState.CreateDefault2(); @@ -370,7 +370,7 @@ internal StaticBindingResult(CommandAst commandAst, PseudoBindingInfo bindingInf BoundParameters = new Dictionary(StringComparer.OrdinalIgnoreCase); BindingExceptions = new Dictionary(StringComparer.OrdinalIgnoreCase); - if (bindingInfo is null) + if (bindingInfo == null) { CreateBindingResultForSyntacticBind(commandAst); } @@ -574,7 +574,7 @@ private void CreateBindingResultForSuccessfulBind(CommandAst commandAst, PseudoB private void AddDuplicateParameterBindingException(CommandParameterAst duplicateParameter) { - if (duplicateParameter is null) + if (duplicateParameter == null) { return; } @@ -947,7 +947,7 @@ internal enum BindingType /// PseudoBindingInfo. internal PseudoBindingInfo DoPseudoParameterBinding(CommandAst command, Type pipeArgumentType, CommandParameterAst paramAstAtCursor, BindingType bindingType) { - if (command is null) + if (command == null) { throw PSTraceSource.NewArgumentNullException(nameof(command)); } @@ -1039,7 +1039,7 @@ internal PseudoBindingInfo DoPseudoParameterBinding(CommandAst command, Type pip if (!_bindingEffective) { // The command is not a cmdlet, not a script cmdlet, and not a function - if (_bindableParameters is null) + if (_bindableParameters == null) return null; // get all bindable parameters @@ -1447,7 +1447,7 @@ private bool ParseParameterArguments(CommandParameterAst paramAstAtCursor) continue; } - if (matchingParameter is null) + if (matchingParameter == null) { // The parameter cannot be found. The reason could be: // 1. It's a bynamic parameter, and we cannot retrieve the ParameterMetadata for it @@ -1512,7 +1512,7 @@ private bool ParseParameterArguments(CommandParameterAst paramAstAtCursor) MergedCompiledCommandParameter nextMatchingParameter = _bindableParameters.GetMatchingParameter(nextArg.ParameterName, false, true, null); // The next parameter doesn't exist. We use it as an argument - if (nextMatchingParameter is null) + if (nextMatchingParameter == null) { AstPair newArg = new AstPair(argument.Parameter, nextArg.Parameter); result.Add(newArg); @@ -1587,7 +1587,7 @@ private Collection BindNamedParameters() continue; } - if (parameter is null) + if (parameter == null) { // Cannot find a matching parameter. It's not processed in ParseParameterArguments. It comes from // a CommandParameterAst with argument. We ignore it and carry on with our binding @@ -1668,7 +1668,7 @@ private Collection BindPositionalParameter( result, ref unboundArgumentsIndex); - if (argument is null) + if (argument == null) { break; } diff --git a/src/System.Management.Automation/engine/CommandDiscovery.cs b/src/System.Management.Automation/engine/CommandDiscovery.cs index fd10f656218..ef9cb56c636 100644 --- a/src/System.Management.Automation/engine/CommandDiscovery.cs +++ b/src/System.Management.Automation/engine/CommandDiscovery.cs @@ -131,7 +131,7 @@ internal class CommandDiscovery /// internal CommandDiscovery(ExecutionContext context) { - if (context is null) + if (context == null) { throw PSTraceSource.NewArgumentNullException(nameof(context)); } @@ -205,7 +205,7 @@ internal CmdletInfo AddCmdletInfoToCache(string name, CmdletInfo newCmdletInfo, throw PSTraceSource.NewArgumentException(nameof(name)); } - if (newCmdletInfo is null) + if (newCmdletInfo == null) { throw PSTraceSource.NewArgumentNullException("cmdlet"); } @@ -375,9 +375,9 @@ private static void VerifyRequiredSnapins(IEnumerable req { IEnumerable loadedPSSnapIns = null; loadedPSSnapIns = context.InitialSessionState.GetPSSnapIn(requiresPSSnapIn.Name); - if (loadedPSSnapIns is null || !loadedPSSnapIns.Any()) + if (loadedPSSnapIns == null || !loadedPSSnapIns.Any()) { - if (requiresMissingPSSnapIns is null) + if (requiresMissingPSSnapIns == null) { requiresMissingPSSnapIns = new Collection(); } @@ -397,7 +397,7 @@ private static void VerifyRequiredSnapins(IEnumerable req if (!AreInstalledRequiresVersionsCompatible( requiresPSSnapIn.Version, loadedPSSnapIn.Version)) { - if (requiresMissingPSSnapIns is null) + if (requiresMissingPSSnapIns == null) { requiresMissingPSSnapIns = new Collection(); } @@ -508,7 +508,7 @@ private static bool AreInstalledRequiresVersionsCompatible(Version requires, Ver private static string BuildPSSnapInDisplayName(PSSnapInSpecification PSSnapin) { - return PSSnapin.Version is null ? + return PSSnapin.Version == null ? PSSnapin.Name : StringUtil.Format(DiscoveryExceptions.PSSnapInNameVersion, PSSnapin.Name, PSSnapin.Version); @@ -554,7 +554,7 @@ internal CommandProcessorBase LookupCommandProcessor(CommandInfo commandInfo, // If we didn't have the alias target already resolved, see if it can be loaded. - if (commandInfo is null) + if (commandInfo == null) { CommandNotFoundException e = new CommandNotFoundException( @@ -701,7 +701,7 @@ internal static CommandProcessorBase CreateCommandProcessorForScript(ScriptBlock private static CommandProcessorBase GetScriptAsCmdletProcessor(IScriptCommandInfo scriptCommandInfo, ExecutionContext context, bool useNewScope, bool fromScriptFile, SessionStateInternal sessionState) { - if (scriptCommandInfo.ScriptBlock is null || !scriptCommandInfo.ScriptBlock.UsesCmdletBinding) + if (scriptCommandInfo.ScriptBlock == null || !scriptCommandInfo.ScriptBlock.UsesCmdletBinding) { return null; } @@ -784,7 +784,7 @@ internal static CommandInfo LookupCommandInfo( // Check the module auto-loading preference PSModuleAutoLoadingPreference moduleAutoLoadingPreference = GetCommandDiscoveryPreference(context, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference"); - if (eventArgs is null || eventArgs.StopSearch != true) + if (eventArgs == null || eventArgs.StopSearch != true) { do { @@ -816,7 +816,7 @@ internal static CommandInfo LookupCommandInfo( } // Otherwise, invoke the CommandNotFound handler - if (result is null) + if (result == null) { result = InvokeCommandNotFoundHandler(commandName, context, originalCommandName, commandOrigin); } @@ -862,7 +862,7 @@ internal static CommandInfo LookupCommandInfo( } // After all command lookup is done, throw a CommandNotFound if we have no result. - if (result is null) + if (result == null) { discoveryTracer.TraceError( "'{0}' is not recognized as a cmdlet, function, operable program or script file.", @@ -901,7 +901,7 @@ Because this function does not check the result of a (currently failing) `PSSche foreach (var module in System.Management.Automation.ExecutionContext.ModulesWithJobSourceAdapters) { List existingModule = context.Modules.GetModules(new string[] { module }, false); - if (existingModule is null || existingModule.Count == 0) + if (existingModule == null || existingModule.Count == 0) { Exception unUsedException = null; AutoloadSpecifiedModule(module, context, cmdletInfo.Visibility, out unUsedException); @@ -1089,7 +1089,7 @@ private static CommandInfo TryModuleAutoDiscovery(string commandName, string moduleShortName = System.IO.Path.GetFileNameWithoutExtension(expandedModulePath); var exportedCommands = AnalysisCache.GetExportedCommands(expandedModulePath, false, context); - if (exportedCommands is null) { continue; } + if (exportedCommands == null) { continue; } CommandTypes exportedCommandTypes; // Skip if module only has class or other types and no commands. @@ -1101,7 +1101,7 @@ private static CommandInfo TryModuleAutoDiscovery(string commandName, cmdletInfo != null ? cmdletInfo.Visibility : SessionStateEntryVisibility.Private, out exception); lastError = exception; - if ((matchingModule is null) || (matchingModule.Count == 0)) + if ((matchingModule == null) || (matchingModule.Count == 0)) { string error = StringUtil.Format(DiscoveryExceptions.CouldNotAutoImportMatchingModule, commandName, moduleShortName); CommandNotFoundException commandNotFound = new CommandNotFoundException( @@ -1206,14 +1206,14 @@ private static CommandInfo TryModuleAutoLoading(string commandName, ExecutionCon List existingModule = context.Modules.GetModules(new string[] { moduleName }, false); PSModuleInfo discoveredModule = null; - if (existingModule is null || existingModule.Count == 0) + if (existingModule == null || existingModule.Count == 0) { discoveryTracer.WriteLine("Attempting to load module: {0}", moduleName); Exception exception; Collection importedModule = AutoloadSpecifiedModule(moduleName, context, cmdletInfo.Visibility, out exception); lastError = exception; - if ((importedModule is null) || (importedModule.Count == 0)) + if ((importedModule == null) || (importedModule.Count == 0)) { string error = StringUtil.Format(DiscoveryExceptions.CouldNotAutoImportModule, moduleName); CommandNotFoundException commandNotFound = new CommandNotFoundException( @@ -1381,7 +1381,7 @@ internal static string[] PathExtensionsWithPs1Prepended var pathExt = Environment.GetEnvironmentVariable("PATHEXT"); if (!string.Equals(pathExt, s_pathExtCacheKey, StringComparison.OrdinalIgnoreCase) || - s_cachedPathExtCollection is null) + s_cachedPathExtCollection == null) { InitPathExtCache(pathExt); } @@ -1400,7 +1400,7 @@ internal static string[] PathExtensions var pathExt = Environment.GetEnvironmentVariable("PATHEXT"); if (!string.Equals(pathExt, s_pathExtCacheKey, StringComparison.OrdinalIgnoreCase) || - s_cachedPathExtCollection is null) + s_cachedPathExtCollection == null) { InitPathExtCache(pathExt); } @@ -1454,7 +1454,7 @@ internal IEnumerator GetCmdletInfo(string cmdletName, bool searchAll PSSnapinQualifiedName commandName = PSSnapinQualifiedName.GetInstance(cmdletName); - if (commandName is null) + if (commandName == null) { yield break; } @@ -1523,7 +1523,7 @@ internal static PSModuleAutoLoadingPreference GetCommandDiscoveryPreference(Exec Dbg.Assert(variablePath != null, "variablePath must be non empty"); Dbg.Assert(!string.IsNullOrEmpty(environmentVariable), "environmentVariable must be non empty"); - if (context is null) + if (context == null) { throw PSTraceSource.NewArgumentNullException(nameof(context)); } diff --git a/src/System.Management.Automation/engine/CommandInfo.cs b/src/System.Management.Automation/engine/CommandInfo.cs index a5010521ddc..1090a3fbb86 100644 --- a/src/System.Management.Automation/engine/CommandInfo.cs +++ b/src/System.Management.Automation/engine/CommandInfo.cs @@ -110,7 +110,7 @@ internal CommandInfo(string name, CommandTypes type) // The name can be empty for functions and filters but it // can't be null - if (name is null) + if (name == null) { throw new ArgumentNullException(nameof(name)); } @@ -196,7 +196,7 @@ public virtual Version Version { get { - if (_version is null) + if (_version == null) { if (Module != null) { @@ -310,12 +310,12 @@ public virtual SessionStateEntryVisibility Visibility { get { - return CopiedCommand is null ? _visibility : CopiedCommand.Visibility; + return CopiedCommand == null ? _visibility : CopiedCommand.Visibility; } set { - if (CopiedCommand is null) + if (CopiedCommand == null) { _visibility = value; } @@ -375,7 +375,7 @@ public string ModuleName } } - if (moduleName is null) + if (moduleName == null) return string.Empty; return moduleName; @@ -424,7 +424,7 @@ internal virtual bool ImplementsDynamicParameters /// private MergedCommandParameterMetadata GetMergedCommandParameterMetadataSafely() { - if (_context is null) + if (_context == null) return null; MergedCommandParameterMetadata result; @@ -612,7 +612,7 @@ public ReadOnlyCollection ParameterSets { get { - if (_parameterSets is null) + if (_parameterSets == null) { Collection parameterSetInfo = GenerateCommandParameterSetInfo(); @@ -798,7 +798,7 @@ public PSTypeName(string name, Type type) /// The type definition from the ast. public PSTypeName(TypeDefinitionAst typeDefinitionAst) { - if (typeDefinitionAst is null) + if (typeDefinitionAst == null) { throw PSTraceSource.NewArgumentNullException(nameof(typeDefinitionAst)); } @@ -812,7 +812,7 @@ public PSTypeName(TypeDefinitionAst typeDefinitionAst) /// public PSTypeName(ITypeName typeName) { - if (typeName is null) + if (typeName == null) { throw PSTraceSource.NewArgumentNullException(nameof(typeName)); } @@ -853,7 +853,7 @@ public Type Type { if (!_typeWasCalculated) { - if (_type is null) + if (_type == null) { if (TypeDefinitionAst != null) { @@ -865,7 +865,7 @@ public Type Type } } - if (_type is null) + if (_type == null) { // We ignore the exception. if (Name != null && diff --git a/src/System.Management.Automation/engine/CommandMetadata.cs b/src/System.Management.Automation/engine/CommandMetadata.cs index f7a42753e12..edcd9a9cd66 100644 --- a/src/System.Management.Automation/engine/CommandMetadata.cs +++ b/src/System.Management.Automation/engine/CommandMetadata.cs @@ -103,14 +103,14 @@ public CommandMetadata(CommandInfo commandInfo) /// public CommandMetadata(CommandInfo commandInfo, bool shouldGenerateCommonParameters) { - if (commandInfo is null) + if (commandInfo == null) { throw PSTraceSource.NewArgumentNullException(nameof(commandInfo)); } while (commandInfo is AliasInfo) { commandInfo = ((AliasInfo)commandInfo).ResolvedCommand; - if (commandInfo is null) + if (commandInfo == null) { throw PSTraceSource.NewNotSupportedException(); } @@ -160,7 +160,7 @@ public CommandMetadata(string path) /// Object to copy. public CommandMetadata(CommandMetadata other) { - if (other is null) + if (other == null) { throw PSTraceSource.NewArgumentNullException(nameof(other)); } @@ -187,7 +187,7 @@ public CommandMetadata(CommandMetadata other) } // deep copy of the collection, collection items (Attributes) copied by reference - if (other._otherAttributes is null) + if (other._otherAttributes == null) { _otherAttributes = null; } @@ -326,7 +326,7 @@ internal static CommandMetadata Get(string commandName, Type cmdletType, Executi s_commandMetadataCache.TryGetValue(cmdletTypeName, out result); } - if (result is null) + if (result == null) { result = new CommandMetadata(commandName, cmdletType, context); @@ -410,7 +410,7 @@ internal CommandMetadata(string commandName, Type cmdletType, ExecutionContext c /// internal CommandMetadata(ScriptBlock scriptblock, string commandName, ExecutionContext context) { - if (scriptblock is null) + if (scriptblock == null) { throw PSTraceSource.NewArgumentException(nameof(scriptblock)); } @@ -549,7 +549,7 @@ public Dictionary Parameters { get { - if (_parameters is null) + if (_parameters == null) { // Return parameters for a script block if (_scriptBlock != null) @@ -724,7 +724,7 @@ private void ConstructCmdletMetadataUsingReflection() /// private void ProcessCmdletAttribute(CmdletCommonMetadataAttribute attribute) { - if (attribute is null) + if (attribute == null) { throw PSTraceSource.NewArgumentNullException(nameof(attribute)); } diff --git a/src/System.Management.Automation/engine/CommandParameter.cs b/src/System.Management.Automation/engine/CommandParameter.cs index 0459427242b..0ee5f7855f1 100644 --- a/src/System.Management.Automation/engine/CommandParameter.cs +++ b/src/System.Management.Automation/engine/CommandParameter.cs @@ -121,7 +121,7 @@ internal bool ArgumentSplatted /// internal void SetArgumentValue(Ast ast, object value) { - if (_argument is null) + if (_argument == null) { _argument = new Argument(); } diff --git a/src/System.Management.Automation/engine/CommandPathSearch.cs b/src/System.Management.Automation/engine/CommandPathSearch.cs index 7975b41b0ad..1929000d7d3 100644 --- a/src/System.Management.Automation/engine/CommandPathSearch.cs +++ b/src/System.Management.Automation/engine/CommandPathSearch.cs @@ -365,7 +365,7 @@ string IEnumerator.Current { get { - if (_currentDirectoryResults is null) + if (_currentDirectoryResults == null) { throw PSTraceSource.NewInvalidOperationException(); } @@ -490,7 +490,7 @@ private void GetNewDirectoryResults(string pattern, string directory) if (name.Equals(baseNames[i], StringComparison.OrdinalIgnoreCase) || (!Platform.IsWindows && Platform.NonWindowsIsExecutable(name))) { - if (result is null) + if (result == null) result = new Collection(); result.Add(fileNames[i]); break; @@ -517,7 +517,7 @@ private void GetNewDirectoryResults(string pattern, string directory) if (fileName.EndsWith(allowedExt, StringComparison.OrdinalIgnoreCase) || (!Platform.IsWindows && Platform.NonWindowsIsExecutable(fileName))) { - if (result is null) + if (result == null) result = new Collection(); result.Add(fileName); } diff --git a/src/System.Management.Automation/engine/CommandProcessor.cs b/src/System.Management.Automation/engine/CommandProcessor.cs index ced0c85e9d4..4433d75ca99 100644 --- a/src/System.Management.Automation/engine/CommandProcessor.cs +++ b/src/System.Management.Automation/engine/CommandProcessor.cs @@ -102,7 +102,7 @@ internal CommandProcessor(IScriptCommandInfo scriptCommandInfo, ExecutionContext internal ParameterBinderController NewParameterBinderController(InternalCommand command) { Cmdlet cmdlet = command as Cmdlet; - if (cmdlet is null) + if (cmdlet == null) { throw PSTraceSource.NewArgumentException(nameof(command)); } @@ -127,7 +127,7 @@ internal CmdletParameterBinderController CmdletParameterBinderController { get { - if (_cmdletParameterBinderController is null) + if (_cmdletParameterBinderController == null) { NewParameterBinderController(this.Command); } @@ -608,7 +608,7 @@ private void WriteInputObjectError( string errorId, params object[] args) { - Type inputObjectType = (inputObject is null) ? null : inputObject.GetType(); + Type inputObjectType = (inputObject == null) ? null : inputObject.GetType(); ParameterBindingException bindingException = new ParameterBindingException( ErrorCategory.InvalidArgument, @@ -710,7 +710,7 @@ private void Init(CmdletInfo cmdletInformation) { // Create the request object newCmdlet = ConstructInstance(cmdletInformation.ImplementingType); - if (newCmdlet is null) + if (newCmdlet == null) { // We could test the inheritance before constructing, but that's // expensive. Much cheaper to just check for null. diff --git a/src/System.Management.Automation/engine/CommandProcessorBase.cs b/src/System.Management.Automation/engine/CommandProcessorBase.cs index ed549162683..87fd4606c9f 100644 --- a/src/System.Management.Automation/engine/CommandProcessorBase.cs +++ b/src/System.Management.Automation/engine/CommandProcessorBase.cs @@ -33,7 +33,7 @@ internal CommandProcessorBase() /// internal CommandProcessorBase(CommandInfo commandInfo) { - if (commandInfo is null) + if (commandInfo == null) { throw PSTraceSource.NewArgumentNullException(nameof(commandInfo)); } @@ -134,7 +134,7 @@ internal InternalCommand Command // Set the execution context for the command it's currently // null and our context has already been set up. - if (value.Context is null && _context != null) + if (value.Context == null && _context != null) value.Context = _context; } @@ -278,7 +278,7 @@ internal static CommandProcessorBase CreateGetHelpCommandProcessor( string helpTarget, HelpCategory helpCategory) { - if (context is null) + if (context == null) { throw PSTraceSource.NewArgumentNullException(nameof(context)); } @@ -341,7 +341,7 @@ internal void SetCurrentScopeToExecutionScope() // Make sure we have a session state instance for this command. // If one hasn't been explicitly set, then use the session state // available on the engine execution context... - if (CommandSessionState is null) + if (CommandSessionState == null) { CommandSessionState = Context.EngineSessionState; } diff --git a/src/System.Management.Automation/engine/CommandSearcher.cs b/src/System.Management.Automation/engine/CommandSearcher.cs index 5bdc134adb0..d3a1033c932 100644 --- a/src/System.Management.Automation/engine/CommandSearcher.cs +++ b/src/System.Management.Automation/engine/CommandSearcher.cs @@ -365,7 +365,7 @@ public bool MoveNext() try { // the previous call to setupPathSearcher ensures _pathSearcher != null - while (currentMatch is null && _pathSearcher!.MoveNext()) + while (currentMatch == null && _pathSearcher!.MoveNext()) { currentMatch = GetInfoFromPath(((IEnumerator)_pathSearcher).Current); } @@ -404,9 +404,9 @@ CommandInfo IEnumerator.Current { get { - if ((_currentState == SearchState.SearchingAliases && _currentMatch is null) || + if ((_currentState == SearchState.SearchingAliases && _currentMatch == null) || _currentState == SearchState.NoMoreMatches || - _currentMatch is null) + _currentMatch == null) { throw PSTraceSource.NewInvalidOperationException(); } @@ -628,7 +628,7 @@ private static bool checkPath(string path, string commandName) // which is not a legal file system character. } - if (extension is null) + if (extension == null) { result = null; break; @@ -691,7 +691,7 @@ private static bool checkPath(string path, string commandName) if ((_commandResolutionOptions & SearchResolutionOptions.ResolveAliasPatterns) != 0) { - if (_matchingAlias is null) + if (_matchingAlias == null) { // Generate the enumerator of matching alias names @@ -772,7 +772,7 @@ private static bool checkPath(string path, string commandName) if (_commandResolutionOptions.HasFlag(SearchResolutionOptions.ResolveFunctionPatterns)) { - if (_matchingFunctionEnumerator is null) + if (_matchingFunctionEnumerator == null) { Collection matchingFunction = new Collection(); @@ -844,7 +844,7 @@ private static bool checkPath(string path, string commandName) // - Debug prompts calling internal functions that are likely to have code injection private bool ShouldSkipCommandResolutionForConstrainedLanguage(CommandInfo? result, ExecutionContext executionContext) { - if (result is null) + if (result == null) { return false; } @@ -928,7 +928,7 @@ private bool ShouldSkipCommandResolutionForConstrainedLanguage(CommandInfo? resu } } - if (module is null) + if (module == null) { module = modules[0]; } @@ -994,7 +994,7 @@ private bool ShouldSkipCommandResolutionForConstrainedLanguage(CommandInfo? resu CmdletInfo? result = null; bool useAbbreviationExpansion = _commandResolutionOptions.HasFlag(SearchResolutionOptions.UseAbbreviationExpansion); - if (_matchingCmdlet is null) + if (_matchingCmdlet == null) { if (_commandResolutionOptions.HasFlag(SearchResolutionOptions.CommandNameIsPattern) || useAbbreviationExpansion) { @@ -1003,7 +1003,7 @@ private bool ShouldSkipCommandResolutionForConstrainedLanguage(CommandInfo? resu PSSnapinQualifiedName? PSSnapinQualifiedCommandName = PSSnapinQualifiedName.GetInstance(_commandName); - if (!useAbbreviationExpansion && PSSnapinQualifiedCommandName is null) + if (!useAbbreviationExpansion && PSSnapinQualifiedCommandName == null) { return null; } @@ -1143,7 +1143,7 @@ private bool ShouldSkipCommandResolutionForConstrainedLanguage(CommandInfo? resu } if (WildcardPattern.ContainsWildcardCharacters(path) && - ((resolvedPath is null) || (provider is null))) + ((resolvedPath == null) || (provider == null))) { // Let PowerShell resolve relative path with wildcards. Collection resolvedPaths = GetNextFromPathUsingWildcards(path, out provider); @@ -1172,7 +1172,7 @@ private bool ShouldSkipCommandResolutionForConstrainedLanguage(CommandInfo? resu // Try literal path resolution if wildcards are enabled first and wildcard search failed if (!_commandResolutionOptions.HasFlag(SearchResolutionOptions.ResolveLiteralThenPathPatterns) && - ((resolvedPath is null) || (provider is null))) + ((resolvedPath == null) || (provider == null))) { resolvedPath = GetNextLiteralPathThatExists(path, out provider); } @@ -1594,7 +1594,7 @@ private void setupPathSearcher() "The path is relative, so only doing the lookup in the specified directory: {0}", directory); - if (directory is null) + if (directory == null) { _canDoPathLookup = false; } diff --git a/src/System.Management.Automation/engine/CommonCommandParameters.cs b/src/System.Management.Automation/engine/CommonCommandParameters.cs index 7cb0a4bb3b4..9cc0b2ad899 100644 --- a/src/System.Management.Automation/engine/CommonCommandParameters.cs +++ b/src/System.Management.Automation/engine/CommonCommandParameters.cs @@ -26,7 +26,7 @@ public sealed class CommonParameters /// internal CommonParameters(MshCommandRuntime commandRuntime) { - if (commandRuntime is null) + if (commandRuntime == null) { throw PSTraceSource.NewArgumentNullException(nameof(commandRuntime)); } diff --git a/src/System.Management.Automation/engine/CompiledCommandParameter.cs b/src/System.Management.Automation/engine/CompiledCommandParameter.cs index cbbe8856f33..ba4fa1fbb21 100644 --- a/src/System.Management.Automation/engine/CompiledCommandParameter.cs +++ b/src/System.Management.Automation/engine/CompiledCommandParameter.cs @@ -35,7 +35,7 @@ internal class CompiledCommandParameter /// internal CompiledCommandParameter(RuntimeDefinedParameter runtimeDefinedParameter, bool processingDynamicParameters) { - if (runtimeDefinedParameter is null) + if (runtimeDefinedParameter == null) { throw PSTraceSource.NewArgumentNullException(nameof(runtimeDefinedParameter)); } @@ -77,7 +77,7 @@ internal CompiledCommandParameter(RuntimeDefinedParameter runtimeDefinedParamete // If this is a PSCredential type and they haven't added any argument transformation attributes, // add one for credential transformation - if ((this.Type == typeof(PSCredential)) && argTransformationAttributes is null) + if ((this.Type == typeof(PSCredential)) && argTransformationAttributes == null) { ProcessAttribute(runtimeDefinedParameter.Name, new CredentialAttribute(), ref validationAttributes, ref argTransformationAttributes, ref aliases); } @@ -88,13 +88,13 @@ internal CompiledCommandParameter(RuntimeDefinedParameter runtimeDefinedParamete ProcessAttribute(runtimeDefinedParameter.Name, attribute, ref validationAttributes, ref argTransformationAttributes, ref aliases); } - this.ValidationAttributes = validationAttributes is null + this.ValidationAttributes = validationAttributes == null ? Array.Empty() : validationAttributes.ToArray(); - this.ArgumentTransformationAttributes = argTransformationAttributes is null + this.ArgumentTransformationAttributes = argTransformationAttributes == null ? Array.Empty() : argTransformationAttributes.ToArray(); - this.Aliases = aliases is null + this.Aliases = aliases == null ? Array.Empty() : aliases.ToArray(); } @@ -121,7 +121,7 @@ internal CompiledCommandParameter(RuntimeDefinedParameter runtimeDefinedParamete /// internal CompiledCommandParameter(MemberInfo member, bool processingDynamicParameters) { - if (member is null) + if (member == null) { throw PSTraceSource.NewArgumentNullException(nameof(member)); } @@ -179,10 +179,10 @@ internal CompiledCommandParameter(MemberInfo member, bool processingDynamicParam } } - this.ValidationAttributes = validationAttributes is null + this.ValidationAttributes = validationAttributes == null ? Array.Empty() : validationAttributes.ToArray(); - this.ArgumentTransformationAttributes = argTransformationAttributes is null + this.ArgumentTransformationAttributes = argTransformationAttributes == null ? Array.Empty() : argTransformationAttributes.ToArray(); this.Aliases = aliases ?? Array.Empty(); @@ -425,7 +425,7 @@ private void ProcessAttribute( ref Collection argTransformationAttributes, ref string[] aliases) { - if (attribute is null) + if (attribute == null) return; CompiledAttributes.Add(attribute); @@ -440,7 +440,7 @@ private void ProcessAttribute( ValidateArgumentsAttribute validateAttr = attribute as ValidateArgumentsAttribute; if (validateAttr != null) { - if (validationAttributes is null) + if (validationAttributes == null) validationAttributes = new Collection(); validationAttributes.Add(validateAttr); if ((attribute is ValidateNotNullAttribute) || (attribute is ValidateNotNullOrEmptyAttribute)) @@ -454,7 +454,7 @@ private void ProcessAttribute( AliasAttribute aliasAttr = attribute as AliasAttribute; if (aliasAttr != null) { - if (aliases is null) + if (aliases == null) { aliases = aliasAttr.aliasNames; } @@ -473,7 +473,7 @@ private void ProcessAttribute( ArgumentTransformationAttribute argumentAttr = attribute as ArgumentTransformationAttribute; if (argumentAttr != null) { - if (argTransformationAttributes is null) + if (argTransformationAttributes == null) argTransformationAttributes = new Collection(); argTransformationAttributes.Add(argumentAttr); return; diff --git a/src/System.Management.Automation/engine/ContentCmdletProviderInterfaces.cs b/src/System.Management.Automation/engine/ContentCmdletProviderInterfaces.cs index 11d9e1d2e78..382f6b7e46a 100644 --- a/src/System.Management.Automation/engine/ContentCmdletProviderInterfaces.cs +++ b/src/System.Management.Automation/engine/ContentCmdletProviderInterfaces.cs @@ -37,7 +37,7 @@ private ContentCmdletProviderIntrinsics() /// internal ContentCmdletProviderIntrinsics(Cmdlet cmdlet) { - if (cmdlet is null) + if (cmdlet == null) { throw PSTraceSource.NewArgumentNullException(nameof(cmdlet)); } @@ -57,7 +57,7 @@ internal ContentCmdletProviderIntrinsics(Cmdlet cmdlet) /// internal ContentCmdletProviderIntrinsics(SessionStateInternal sessionState) { - if (sessionState is null) + if (sessionState == null) { throw PSTraceSource.NewArgumentNullException(nameof(sessionState)); } diff --git a/src/System.Management.Automation/engine/CoreAdapter.cs b/src/System.Management.Automation/engine/CoreAdapter.cs index 9ecbb7806b9..b6752387d58 100644 --- a/src/System.Management.Automation/engine/CoreAdapter.cs +++ b/src/System.Management.Automation/engine/CoreAdapter.cs @@ -823,7 +823,7 @@ internal string BaseParameterizedPropertyToString(PSParameterizedProperty proper private static Type GetArgumentType(object argument, bool isByRefParameter) { - if (argument is null) + if (argument == null) { return typeof(LanguagePrimitives.Null); } @@ -1036,7 +1036,7 @@ private static OverloadCandidate FindBestCandidate(List candi for (int i = 0; i < candidates.Count; i++) { OverloadCandidate currentCandidate = candidates[i]; - if (bestCandidateSoFar is null) // first iteration + if (bestCandidateSoFar == null) // first iteration { bestCandidateSoFar = currentCandidate; continue; @@ -1196,7 +1196,7 @@ private static bool IsInvocationTargetConstraintSatisfied(MethodInformation meth { Dbg.Assert(method != null, "Caller should verify method != null"); - if (method.method is null) + if (method.method == null) { return true; // do not apply methodTargetType constraint to non-.NET types (i.e. to COM or WMI types) } @@ -1212,7 +1212,7 @@ private static bool IsInvocationTargetConstraintSatisfied(MethodInformation meth // will have no method target type. var methodDeclaringType = method.method.DeclaringType; - if (invocationConstraints is null || invocationConstraints.MethodTargetType is null) + if (invocationConstraints == null || invocationConstraints.MethodTargetType == null) { // If no method target type is specified, we say the constraint is matched as long as the method is not an interface. // This behavior matches V2 - our candidate sets never included methods with declaring type as an interface in V2. @@ -1283,7 +1283,7 @@ private static bool IsInvocationConstraintSatisfied(OverloadCandidate overloadCa { Dbg.Assert(overloadCandidate != null, "Caller should verify overloadCandidate != null"); - if (invocationConstraints is null) + if (invocationConstraints == null) { return true; } @@ -1338,7 +1338,7 @@ internal static MethodInformation FindBestMethod( { callNonVirtually = false; var methodInfo = FindBestMethodImpl(methods, invocationConstraints, allowCastingToByRefLikeType, arguments, ref errorId, ref errorMsg, out expandParamsOnBest); - if (methodInfo is null) + if (methodInfo == null) { return null; } @@ -1397,7 +1397,7 @@ private static MethodInformation FindBestMethodImpl( if ((methods.Length == 1) && (methods[0].hasVarArgs == false) && (methods[0].isGeneric == false) && - (methods[0].method is null || !(methods[0].method.DeclaringType.IsGenericTypeDefinition)) && + (methods[0].method == null || !(methods[0].method.DeclaringType.IsGenericTypeDefinition)) && // generic methods need to be double checked in a loop below - generic methods can be rejected if type inference fails (methods[0].parameters.Length == arguments.Length)) { @@ -1434,7 +1434,7 @@ private static MethodInformation FindBestMethodImpl( } method = TypeInference.Infer(method, argumentTypesForTypeInference); - if (method is null) + if (method == null) { // Skip generic methods for which we cannot infer type arguments continue; @@ -1625,7 +1625,7 @@ internal static Type EffectiveArgumentType(object arg) for (int j = 1; j < argAsArray.Length; ++j) { - if (argAsArray[j] is null || firstType != PSObject.Base(argAsArray[j]).GetType()) + if (argAsArray[j] == null || firstType != PSObject.Base(argAsArray[j]).GetType()) { allSameType = false; break; @@ -1656,16 +1656,16 @@ internal static void SetReferences(object[] arguments, MethodInformation methodI object originalArgument = originalArguments[i]; PSReference originalArgumentReference = originalArgument as PSReference; // It still might be an PSObject wrapping an PSReference - if (originalArgumentReference is null) + if (originalArgumentReference == null) { PSObject originalArgumentObj = originalArgument as PSObject; - if (originalArgumentObj is null) + if (originalArgumentObj == null) { continue; } originalArgumentReference = originalArgumentObj.BaseObject as PSReference; - if (originalArgumentReference is null) + if (originalArgumentReference == null) { continue; } @@ -1715,7 +1715,7 @@ internal static MethodInformation GetBestMethodAndArguments( out expandParamsOnBest, out callNonVirtually); - if (bestMethod is null) + if (bestMethod == null) { throw new MethodException(errorId, null, errorMsg, methodName, arguments.Length); } @@ -1765,7 +1765,7 @@ internal static object[] GetMethodArgumentsBase(string methodName, // and convert them to the propper type, if necessary to be the // one argument for this last parameter int remainingArgumentCount = arguments.Length - parametersLength + 1; - if (remainingArgumentCount == 1 && arguments[arguments.Length - 1] is null) + if (remainingArgumentCount == 1 && arguments[arguments.Length - 1] == null) { // Don't turn a single null argument into an array of 1 element, just pass null. retValue[parametersLength - 1] = null; @@ -1854,7 +1854,7 @@ internal static object MethodArgumentConvertTo(object valueToConvert, { using (PSObject.MemberResolution.TraceScope("Method argument conversion.")) { - if (resultType is null) + if (resultType == null) { throw PSTraceSource.NewArgumentNullException(nameof(resultType)); } @@ -1909,7 +1909,7 @@ internal static object PropertySetAndMethodArgumentConvertTo(object valueToConve { using (PSObject.MemberResolution.TraceScope("Converting parameter \"{0}\" to \"{1}\".", valueToConvert, resultType)) { - if (resultType is null) + if (resultType == null) { throw PSTraceSource.NewArgumentNullException(nameof(resultType)); } @@ -2085,7 +2085,7 @@ internal string methodDefinition { get { - if (_cachedMethodDefinition is null) + if (_cachedMethodDefinition == null) { var name = method is ConstructorInfo ? "new" : method.Name; var methodDefn = DotNetAdapter.GetMethodInfoOverloadDefinition(name, method, method.GetParameters().Length - parameters.Length); @@ -2203,7 +2203,7 @@ internal object Invoke(object target, object[] arguments) if (!_useReflection) { - if (_methodInvoker is null) + if (_methodInvoker == null) { _methodInvoker = GetMethodInvoker(methodInfo); } @@ -2394,7 +2394,7 @@ private MethodInvoker GetMethodInvoker(MethodInfo method) if (method.IsVirtual) { type = FindInterfaceForMethod(method, out methodToCall); - if (type is null) + if (type == null) { _useReflection = true; return null; @@ -2636,7 +2636,7 @@ internal override bool IsHidden { get { - if (_isHidden is null) + if (_isHidden == null) { bool hasHiddenAttribute = false; foreach (var method in methodInformationStructures) @@ -2765,8 +2765,8 @@ internal PropertyCacheEntry(PropertyInfo property) declaringType.IsCOMObject || propertyType.IsCOMObject) { - this.readOnly = property.GetSetMethod() is null; - this.writeOnly = property.GetGetMethod() is null; + this.readOnly = property.GetSetMethod() == null; + this.writeOnly = property.GetGetMethod() == null; this.useReflection = true; return; } @@ -2953,7 +2953,7 @@ internal GetterDelegate getterDelegate { get { - if (_getterDelegate is null) + if (_getterDelegate == null) { InitGetter(); } @@ -2968,7 +2968,7 @@ internal SetterDelegate setterDelegate { get { - if (_setterDelegate is null) + if (_setterDelegate == null) { InitSetter(); } @@ -2991,7 +2991,7 @@ internal override bool IsHidden { get { - if (_isHidden is null) + if (_isHidden == null) { _isHidden = member.GetCustomAttributes(typeof(HiddenAttribute), inherit: false).Length != 0; } @@ -3006,7 +3006,7 @@ internal AttributeCollection Attributes { get { - if (_attributes is null) + if (_attributes == null) { // Since AttributeCollection can only be constructed with an Attribute[], one is built. var objAttributes = this.member.GetCustomAttributes(true); @@ -3082,7 +3082,7 @@ private static void PopulateMethodReflectionTable(Type type, MethodInfo[] method { string methodName = method.Name; var previousMethodEntry = (List)typeMethods[methodName]; - if (previousMethodEntry is null) + if (previousMethodEntry == null) { var methodEntry = new List { method }; typeMethods.Add(methodName, methodEntry); @@ -3105,7 +3105,7 @@ private static void PopulateMethodReflectionTable(ConstructorInfo[] ctors, Cache foreach (var ctor in ctors) { var previousMethodEntry = (List)typeMethods["new"]; - if (previousMethodEntry is null) + if (previousMethodEntry == null) { var methodEntry = new List(); methodEntry.Add(ctor); @@ -3179,7 +3179,7 @@ private static void PopulateMethodReflectionTable(Type type, CacheTable typeMeth } var previousMethodEntry = (List)typeMethods[interfaceMethodDefinition.Name]; - if (previousMethodEntry is null) + if (previousMethodEntry == null) { var methodEntry = new List { interfaceMethodDefinition }; typeMethods.Add(interfaceMethodDefinition.Name, methodEntry); @@ -3199,7 +3199,7 @@ private static void PopulateMethodReflectionTable(Type type, CacheTable typeMeth // We don't add constructors if there was a static method named new. // We don't add constructors if the target type is not public, because it's useless to an internal type. var previousMethodEntry = (List)typeMethods["new"]; - if (previousMethodEntry is null) + if (previousMethodEntry == null) { var ctorBindingFlags = bindingFlags & ~(BindingFlags.FlattenHierarchy | BindingFlags.Static); ctorBindingFlags |= BindingFlags.Instance; @@ -3368,7 +3368,7 @@ private static void PopulatePropertyReflectionTable(Type type, CacheTable typePr FieldInfo field = fields[i]; string fieldName = field.Name; var previousMember = (PropertyCacheEntry)typeProperties[fieldName]; - if (previousMember is null) + if (previousMember == null) { typeProperties.Add(fieldName, new PropertyCacheEntry(field)); } @@ -3689,7 +3689,7 @@ private T GetDotNetMethodImpl(object obj, string methodName, MemberNamePredic ? (MethodCacheEntry)typeTable.GetFirstOrDefault(predicate) : (MethodCacheEntry)typeTable[methodName]; - if (methods is null) + if (methods == null) { return null; } @@ -3745,7 +3745,7 @@ protected T GetFirstDotNetEventOrDefault(object obj, MemberNamePredicate pred protected T GetFirstDynamicMemberOrDefault(object obj, MemberNamePredicate predicate) where T : PSMemberInfo { var idmop = obj as IDynamicMetaObjectProvider; - if (idmop is null || obj is PSObject) + if (idmop == null || obj is PSObject) { return null; } @@ -3785,7 +3785,7 @@ internal void AddAllProperties(object obj, PSMemberInfoInternalCollection { if (lookingForProperties) { - if (!ignoreDuplicates || (members[propertyEntry.member.Name] is null)) + if (!ignoreDuplicates || (members[propertyEntry.member.Name] == null)) { members.Add( new PSProperty( @@ -3800,7 +3800,7 @@ internal void AddAllProperties(object obj, PSMemberInfoInternalCollection else if (lookingForParameterizedProperties) { var parameterizedPropertyEntry = (ParameterizedPropertyCacheEntry)table.memberCollection[i]; - if (!ignoreDuplicates || (members[parameterizedPropertyEntry.propertyName] is null)) + if (!ignoreDuplicates || (members[parameterizedPropertyEntry.propertyName] == null)) { // TODO: check for HiddenAttribute // We can't currently write a parameterized property in a PowerShell class so this isn't too important, @@ -3829,7 +3829,7 @@ internal void AddAllMethods(object obj, PSMemberInfoInternalCollection mem var isCtor = method[0].method is ConstructorInfo; var name = isCtor ? "new" : method[0].method.Name; - if (!ignoreDuplicates || (members[name] is null)) + if (!ignoreDuplicates || (members[name] == null)) { bool isSpecial = !isCtor && method[0].method.IsSpecialName; members.Add(PSMethod.Create(name, this, obj, method, isSpecial, method.IsHidden) as T); @@ -3850,7 +3850,7 @@ internal void AddAllEvents(object obj, PSMemberInfoInternalCollection memb foreach (var psEvent in table.Values) { - if (!ignoreDuplicates || (members[psEvent.events[0].Name] is null)) + if (!ignoreDuplicates || (members[psEvent.events[0].Name] == null)) { members.Add(new PSEvent(psEvent.events[0]) as T); } @@ -3860,7 +3860,7 @@ internal void AddAllEvents(object obj, PSMemberInfoInternalCollection memb internal void AddAllDynamicMembers(object obj, PSMemberInfoInternalCollection members, bool ignoreDuplicates) where T : PSMemberInfo { var idmop = obj as IDynamicMetaObjectProvider; - if (idmop is null || obj is PSObject) + if (idmop == null || obj is PSObject) { return; } @@ -3879,7 +3879,7 @@ internal void AddAllDynamicMembers(object obj, PSMemberInfoInternalCollection private static bool PropertyIsStatic(PSProperty property) { PropertyCacheEntry entry = property.adapterData as PropertyCacheEntry; - if (entry is null) + if (entry == null) { return false; } @@ -4685,7 +4685,7 @@ protected override T GetMember(object obj, string memberName) T returnValue = base.GetDotNetMethod(obj, memberName); // We only return a method if there is no property by the same name // to match the behavior we have in GetMembers - if (returnValue != null && property is null) + if (returnValue != null && property == null) { return returnValue; } @@ -4696,7 +4696,7 @@ protected override T GetMember(object obj, string memberName) PSParameterizedProperty parameterizedProperty = base.GetDotNetProperty(obj, memberName); // We only return a parameterized property if there is no property by the same name // to match the behavior we have in GetMembers - if (parameterizedProperty != null && property is null) + if (parameterizedProperty != null && property == null) { return parameterizedProperty as T; } @@ -4727,7 +4727,7 @@ protected override T GetFirstMemberOrDefault(object obj, MemberNamePredicate // We only return a method if there is no property by the same name // to match the behavior we have in GetMembers - if (returnValue != null && property is null) + if (returnValue != null && property == null) { return returnValue; } @@ -4739,7 +4739,7 @@ protected override T GetFirstMemberOrDefault(object obj, MemberNamePredicate // We only return a parameterized property if there is no property by the same name // to match the behavior we have in GetMembers - if (parameterizedProperty != null && property is null) + if (parameterizedProperty != null && property == null) { return parameterizedProperty as T; } @@ -5120,7 +5120,7 @@ protected override T GetMember(object obj, string memberName) T returnValue = base.GetDotNetMethod(obj, memberName); // We only return a method if there is no property by the same name // to match the behavior we have in GetMembers - if (returnValue != null && property is null) + if (returnValue != null && property == null) { return returnValue; } @@ -5131,7 +5131,7 @@ protected override T GetMember(object obj, string memberName) PSParameterizedProperty parameterizedProperty = base.GetDotNetProperty(obj, memberName); // We only return a parameterized property if there is no property by the same name // to match the behavior we have in GetMembers - if (parameterizedProperty != null && property is null) + if (parameterizedProperty != null && property == null) { return parameterizedProperty as T; } @@ -5163,7 +5163,7 @@ protected override T GetFirstMemberOrDefault(object obj, MemberNamePredicate // We only return a method if there is no property by the same name // to match the behavior we have in GetMembers - if (returnValue != null && property is null) + if (returnValue != null && property == null) { return returnValue; } @@ -5175,7 +5175,7 @@ protected override T GetFirstMemberOrDefault(object obj, MemberNamePredicate // We only return a parameterized property if there is no property by the same name // to match the behavior we have in GetMembers - if (parameterizedProperty != null && property is null) + if (parameterizedProperty != null && property == null) { return parameterizedProperty as T; } @@ -5253,7 +5253,7 @@ protected override IEnumerable GetTypeNameHierarchy(object obj) StringBuilder firstType = null; foreach (string baseType in baseTypeNames) { - if (firstType is null) + if (firstType == null) { firstType = new StringBuilder(baseType); firstType.Append("#"); @@ -5342,7 +5342,7 @@ protected override PSProperty DoGetProperty(object obj, string propertyName) protected override PSProperty DoGetFirstPropertyOrDefault(object obj, MemberNamePredicate predicate) { XmlNode node = FindNode(obj, predicate); - return node is null ? null : new PSProperty(node.LocalName, this, obj, node); + return node == null ? null : new PSProperty(node.LocalName, this, obj, node); } /// @@ -5377,7 +5377,7 @@ protected override bool PropertyIsSettable(PSProperty property) } XmlNodeList nodeChildren = node.ChildNodes; - if ((nodeChildren is null) || (nodeChildren.Count == 0)) + if ((nodeChildren == null) || (nodeChildren.Count == 0)) { return true; } @@ -5499,7 +5499,7 @@ protected override void PropertySet(PSProperty property, object setValue, bool c } XmlNodeList nodeChildren = node.ChildNodes; - if (nodeChildren is null || nodeChildren.Count == 0) + if (nodeChildren == null || nodeChildren.Count == 0) { node.InnerText = valueString; return; @@ -5541,7 +5541,7 @@ protected override string PropertyType(PSProperty property, bool forDisplay) { } - var type = value is null ? typeof(object) : value.GetType(); + var type = value == null ? typeof(object) : value.GetType(); return forDisplay ? ToStringCodeMethods.Type(type) : type.FullName; } #endregion virtual @@ -5635,7 +5635,7 @@ internal class DataRowAdapter : PropertyOnlyAdapter protected override void DoAddAllProperties(object obj, PSMemberInfoInternalCollection members) { DataRow dataRow = (DataRow)obj; - if (dataRow.Table is null || dataRow.Table.Columns is null) + if (dataRow.Table == null || dataRow.Table.Columns == null) { return; } @@ -5757,7 +5757,7 @@ internal class DataRowViewAdapter : PropertyOnlyAdapter protected override void DoAddAllProperties(object obj, PSMemberInfoInternalCollection members) { DataRowView dataRowView = (DataRowView)obj; - if (dataRowView.Row is null || dataRowView.Row.Table is null || dataRowView.Row.Table.Columns is null) + if (dataRowView.Row == null || dataRowView.Row.Table == null || dataRowView.Row.Table.Columns == null) { return; } @@ -5913,7 +5913,7 @@ private static MethodInfo Infer(MethodInfo genericMethod, Type[] typesOfMethodAr // we can try to infer for this signature instead // M)(T1, T2, ..., T3, T3, T3, T3) // where T3 is repeated appropriate number of times depending on the number of actual method arguments. - if (inferredMethod is null && + if (inferredMethod == null && hasVarArgs && typesOfMethodArguments.Length >= (typesOfMethodParameters.Length - 1)) { @@ -5955,7 +5955,7 @@ private static MethodInfo Infer(MethodInfo genericMethod, ICollection type } IEnumerable inferredTypeParameters = typeParameters.Select(typeInference.GetInferredType); - if (inferredTypeParameters.Any(inferredType => inferredType is null)) + if (inferredTypeParameters.Any(inferredType => inferredType == null)) { return null; } @@ -6066,7 +6066,7 @@ internal Type GetInferredType(Type typeParameter) } } - if (inferenceCandidates is null) + if (inferenceCandidates == null) { s_tracer.WriteLine("Couldn't infer type parameter {0}", typeParameter); return null; @@ -6117,7 +6117,7 @@ private bool Unify(Type parameterType, Type argumentType) #endif HashSet inferenceCandidates = _typeParameterIndexToSetOfInferenceCandidates[parameterType.GenericParameterPosition]; - if (inferenceCandidates is null) + if (inferenceCandidates == null) { inferenceCandidates = new HashSet(); _typeParameterIndexToSetOfInferenceCandidates[parameterType.GenericParameterPosition] = inferenceCandidates; diff --git a/src/System.Management.Automation/engine/Credential.cs b/src/System.Management.Automation/engine/Credential.cs index 8cb159fea5e..6b9c4be8d4d 100644 --- a/src/System.Management.Automation/engine/Credential.cs +++ b/src/System.Management.Automation/engine/Credential.cs @@ -113,7 +113,7 @@ public static GetSymmetricEncryptionKey GetSymmetricEncryptionKeyDelegate /// public void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) return; // serialize the secure string @@ -151,7 +151,7 @@ public void GetObjectData(SerializationInfo info, StreamingContext context) /// private PSCredential(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) return; _userName = (string)info.GetValue("UserName", typeof(string)); @@ -218,7 +218,7 @@ public PSCredential(string userName, SecureString password) /// public PSCredential(PSObject pso) { - if (pso is null) + if (pso == null) throw PSTraceSource.NewArgumentNullException(nameof(pso)); if (pso.Properties["UserName"] != null) @@ -256,7 +256,7 @@ private PSCredential() /// public NetworkCredential GetNetworkCredential() { - if (_netCred is null) + if (_netCred == null) { string user = null; string domain = null; @@ -285,7 +285,7 @@ public static explicit operator NetworkCredential(PSCredential credential) { #pragma warning disable 56506 - if (credential is null) + if (credential == null) { throw PSTraceSource.NewArgumentNullException("credential"); } @@ -331,8 +331,8 @@ private static bool IsValidUserName(string input, SplitUserDomain(input, out user, out domain); - if ((user is null) || - (domain is null) || + if ((user == null) || + (domain == null) || (user.Length == 0)) { // UserName is the public property of Credential object. Use this as diff --git a/src/System.Management.Automation/engine/DataStoreAdapter.cs b/src/System.Management.Automation/engine/DataStoreAdapter.cs index 8c5eb927bb5..c7db11bf081 100644 --- a/src/System.Management.Automation/engine/DataStoreAdapter.cs +++ b/src/System.Management.Automation/engine/DataStoreAdapter.cs @@ -125,7 +125,7 @@ internal set /// internal void SetRoot(string path) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -269,7 +269,7 @@ internal void SetRoot(string path) /// protected PSDriveInfo(PSDriveInfo driveInfo) { - if (driveInfo is null) + if (driveInfo == null) { throw PSTraceSource.NewArgumentNullException(nameof(driveInfo)); } @@ -324,17 +324,17 @@ public PSDriveInfo( { // Verify the parameters - if (name is null) + if (name == null) { throw PSTraceSource.NewArgumentNullException(nameof(name)); } - if (provider is null) + if (provider == null) { throw PSTraceSource.NewArgumentNullException(nameof(provider)); } - if (root is null) + if (root == null) { throw PSTraceSource.NewArgumentNullException(nameof(root)); } @@ -532,7 +532,7 @@ internal void SetName(string newName) /// internal void SetProvider(ProviderInfo newProvider) { - if (newProvider is null) + if (newProvider == null) { throw PSTraceSource.NewArgumentNullException(nameof(newProvider)); } @@ -600,7 +600,7 @@ public int CompareTo(PSDriveInfo drive) { #pragma warning disable 56506 - if (drive is null) + if (drive == null) { throw PSTraceSource.NewArgumentNullException(nameof(drive)); } @@ -627,7 +627,7 @@ public int CompareTo(object obj) { PSDriveInfo drive = obj as PSDriveInfo; - if (drive is null) + if (drive == null) { ArgumentException e = PSTraceSource.NewArgumentException( @@ -693,7 +693,7 @@ public bool Equals(PSDriveInfo drive) object drive1Object = drive1; object drive2Object = drive2; - if ((drive1Object is null) == (drive2Object is null)) + if ((drive1Object == null) == (drive2Object == null)) { if (drive1Object != null) { @@ -745,13 +745,13 @@ public bool Equals(PSDriveInfo drive) object drive1Object = drive1; object drive2Object = drive2; - if (drive1Object is null) + if (drive1Object == null) { return (drive2Object != null); } else { - if (drive2Object is null) + if (drive2Object == null) { // Since drive1 is not null and drive2 is, drive1 is greater than drive2 return false; @@ -783,7 +783,7 @@ public bool Equals(PSDriveInfo drive) object drive1Object = drive1; object drive2Object = drive2; - if ((drive1Object is null)) + if ((drive1Object == null)) { // Since both drives are null, they are equal // Since drive1 is null it is less than drive2 which is not null @@ -791,7 +791,7 @@ public bool Equals(PSDriveInfo drive) } else { - if (drive2Object is null) + if (drive2Object == null) { // Since drive1 is not null and drive2 is, drive1 is greater than drive2 return true; @@ -820,7 +820,7 @@ public override int GetHashCode() internal PSNoteProperty GetNotePropertyForProviderCmdlets(string name) { - if (_noteProperty is null) + if (_noteProperty == null) { Interlocked.CompareExchange(ref _noteProperty, new PSNoteProperty(name, this), null); diff --git a/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs b/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs index 751af63626a..f1e798c0edf 100644 --- a/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs +++ b/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs @@ -295,7 +295,7 @@ public override string ToString() /// protected ProviderInfo(ProviderInfo providerInfo) { - if (providerInfo is null) + if (providerInfo == null) { throw PSTraceSource.NewArgumentNullException(nameof(providerInfo)); } @@ -392,12 +392,12 @@ internal ProviderInfo( PSSnapInInfo psSnapIn) { // Verify parameters - if (sessionState is null) + if (sessionState == null) { throw PSTraceSource.NewArgumentNullException(nameof(sessionState)); } - if (implementingType is null) + if (implementingType == null) { throw PSTraceSource.NewArgumentNullException(nameof(implementingType)); } @@ -497,13 +497,13 @@ internal bool IsMatch(WildcardPattern namePattern, PSSnapinQualifiedName psSnapi { bool result = false; - if (psSnapinQualifiedName is null) + if (psSnapinQualifiedName == null) { result = true; } else { - if (namePattern is null) + if (namePattern == null) { if (string.Equals(Name, psSnapinQualifiedName.ShortName, StringComparison.OrdinalIgnoreCase) && IsPSSnapinNameMatch(psSnapinQualifiedName)) @@ -565,7 +565,7 @@ internal Provider.CmdletProvider CreateInstance() object providerInstance = Thread.GetData(instance); - if (providerInstance is null) + if (providerInstance == null) { #else object providerInstance = null; @@ -598,7 +598,7 @@ internal Provider.CmdletProvider CreateInstance() } #endif - if (providerInstance is null) + if (providerInstance == null) { ProviderNotFoundException e = null; @@ -642,7 +642,7 @@ internal Provider.CmdletProvider CreateInstance() /// internal void GetOutputTypes(string cmdletname, List listToAppend) { - if (_providerOutputType is null) + if (_providerOutputType == null) { _providerOutputType = new Dictionary>(); foreach (OutputTypeAttribute outputType in ImplementingType.GetCustomAttributes(false)) @@ -676,7 +676,7 @@ internal void GetOutputTypes(string cmdletname, List listToAppend) internal PSNoteProperty GetNotePropertyForProviderCmdlets(string name) { - if (_noteProperty is null) + if (_noteProperty == null) { Interlocked.CompareExchange(ref _noteProperty, new PSNoteProperty(name, this), null); diff --git a/src/System.Management.Automation/engine/DefaultCommandRuntime.cs b/src/System.Management.Automation/engine/DefaultCommandRuntime.cs index 7402e32294b..95e7572810f 100644 --- a/src/System.Management.Automation/engine/DefaultCommandRuntime.cs +++ b/src/System.Management.Automation/engine/DefaultCommandRuntime.cs @@ -20,7 +20,7 @@ internal class DefaultCommandRuntime : ICommandRuntime2 /// public DefaultCommandRuntime(List outputList) { - if (outputList is null) + if (outputList == null) throw new System.ArgumentNullException(nameof(outputList)); _output = outputList; @@ -75,7 +75,7 @@ public void WriteObject(object sendToPipeline, bool enumerateCollection) if (enumerateCollection) { IEnumerator e = LanguagePrimitives.GetEnumerator(sendToPipeline); - if (e is null) + if (e == null) { _output.Add(sendToPipeline); } diff --git a/src/System.Management.Automation/engine/DriveInterfaces.cs b/src/System.Management.Automation/engine/DriveInterfaces.cs index c79c624ee37..36bfc73c573 100644 --- a/src/System.Management.Automation/engine/DriveInterfaces.cs +++ b/src/System.Management.Automation/engine/DriveInterfaces.cs @@ -36,7 +36,7 @@ private DriveManagementIntrinsics() /// internal DriveManagementIntrinsics(SessionStateInternal sessionState) { - if (sessionState is null) + if (sessionState == null) { throw PSTraceSource.NewArgumentNullException(nameof(sessionState)); } diff --git a/src/System.Management.Automation/engine/DscResourceSearcher.cs b/src/System.Management.Automation/engine/DscResourceSearcher.cs index b675e007680..8bb4f5bd267 100644 --- a/src/System.Management.Automation/engine/DscResourceSearcher.cs +++ b/src/System.Management.Automation/engine/DscResourceSearcher.cs @@ -124,7 +124,7 @@ private DscResourceInfo GetNextDscResource() WildcardPattern resourceMatcher = WildcardPattern.Get(_resourceName, WildcardOptions.IgnoreCase); - if (_matchingResourceList is null) + if (_matchingResourceList == null) { Collection psObjs = ps.Invoke(); diff --git a/src/System.Management.Automation/engine/EngineIntrinsics.cs b/src/System.Management.Automation/engine/EngineIntrinsics.cs index 65c1da34470..d0bc7a2f100 100644 --- a/src/System.Management.Automation/engine/EngineIntrinsics.cs +++ b/src/System.Management.Automation/engine/EngineIntrinsics.cs @@ -35,7 +35,7 @@ private EngineIntrinsics() /// internal EngineIntrinsics(ExecutionContext context) { - if (context is null) + if (context == null) { throw new ArgumentNullException(nameof(context)); } diff --git a/src/System.Management.Automation/engine/EnumExpressionEvaluator.cs b/src/System.Management.Automation/engine/EnumExpressionEvaluator.cs index 0682284227d..88aa49e98d2 100644 --- a/src/System.Management.Automation/engine/EnumExpressionEvaluator.cs +++ b/src/System.Management.Automation/engine/EnumExpressionEvaluator.cs @@ -67,7 +67,7 @@ public FlagsExpression(object[] expression) _underType = Enum.GetUnderlyingType(typeof(T)); - if (expression is null) + if (expression == null) { throw InterpreterError.NewInterpreterException(null, typeof(ArgumentNullException), null, "EmptyInputString", EnumExpressionEvaluatorStrings.EmptyInputString); diff --git a/src/System.Management.Automation/engine/ErrorPackage.cs b/src/System.Management.Automation/engine/ErrorPackage.cs index da96fa1ff76..fc346e2ee96 100644 --- a/src/System.Management.Automation/engine/ErrorPackage.cs +++ b/src/System.Management.Automation/engine/ErrorPackage.cs @@ -193,7 +193,7 @@ public class ErrorCategoryInfo #region ctor internal ErrorCategoryInfo(ErrorRecord errorRecord) { - if (errorRecord is null) + if (errorRecord == null) { throw new ArgumentNullException(nameof(errorRecord)); } @@ -810,7 +810,7 @@ private string BuildMessage( string resourceId, params object[] args) { - if (cmdlet is null) + if (cmdlet == null) { throw PSTraceSource.NewArgumentNullException(nameof(cmdlet)); } @@ -851,7 +851,7 @@ private string BuildMessage( string resourceId, params object[] args) { - if (resourceSupplier is null) + if (resourceSupplier == null) { throw PSTraceSource.NewArgumentNullException(nameof(resourceSupplier)); } @@ -892,7 +892,7 @@ private string BuildMessage( string resourceId, params object[] args) { - if (assembly is null) + if (assembly == null) { throw PSTraceSource.NewArgumentNullException(nameof(assembly)); } @@ -1019,12 +1019,12 @@ public ErrorRecord( ErrorCategory errorCategory, object targetObject) { - if (exception is null) + if (exception == null) { throw PSTraceSource.NewArgumentNullException(nameof(exception)); } - if (errorId is null) + if (errorId == null) { errorId = string.Empty; } @@ -1162,12 +1162,12 @@ private void PopulateProperties( string errorDetails_RecommendedAction, string errorDetails_ScriptStackTrace) { - if (exception is null) + if (exception == null) { throw PSTraceSource.NewArgumentNullException(nameof(exception)); } - if (fullyQualifiedErrorId is null) + if (fullyQualifiedErrorId == null) { throw PSTraceSource.NewArgumentNullException(nameof(fullyQualifiedErrorId)); } @@ -1223,7 +1223,7 @@ private void ToPSObjectForRemoting(PSObject dest, bool serializeExtInfo) RemotingEncoder.AddNoteProperty(dest, "ErrorDetails_RecommendedAction", delegate () { return ErrorDetails.RecommendedAction; }); } - if (!serializeExtInfo || this.InvocationInfo is null) + if (!serializeExtInfo || this.InvocationInfo == null) { RemotingEncoder.AddNoteProperty(dest, "SerializeExtendedInfo", () => false); } @@ -1287,7 +1287,7 @@ internal static ErrorRecord FromPSObjectForRemoting(PSObject serializedErrorReco private void ConstructFromPSObjectForRemoting(PSObject serializedErrorRecord) { - if (serializedErrorRecord is null) + if (serializedErrorRecord == null) { throw PSTraceSource.NewArgumentNullException(nameof(serializedErrorRecord)); } @@ -1394,7 +1394,7 @@ private void ConstructFromPSObjectForRemoting(PSObject serializedErrorRecord) public ErrorRecord(ErrorRecord errorRecord, Exception replaceParentContainsErrorRecordException) { - if (errorRecord is null) + if (errorRecord == null) { throw new PSArgumentNullException(nameof(errorRecord)); } @@ -1549,7 +1549,7 @@ internal void SetInvocationInfo(InvocationInfo invocationInfo) { _invocationInfo = new InvocationInfo(invocationInfo.MyCommand, invocationInfo.ScriptPosition); _invocationInfo.InvocationName = invocationInfo.InvocationName; - if (invocationInfo.MyCommand is null) + if (invocationInfo.MyCommand == null) { // Pass the history id to new InvocationInfo object of command info is null since history // information cannot be obtained in this case. @@ -1651,13 +1651,13 @@ internal bool SerializeExtendedInfo private string GetInvocationTypeName() { InvocationInfo invocationInfo = this.InvocationInfo; - if (invocationInfo is null) + if (invocationInfo == null) { return string.Empty; } CommandInfo commandInfo = invocationInfo.MyCommand; - if (commandInfo is null) + if (commandInfo == null) { return string.Empty; } @@ -1669,7 +1669,7 @@ private string GetInvocationTypeName() } CmdletInfo cmdletInfo = commandInfo as CmdletInfo; - if (cmdletInfo is null) + if (cmdletInfo == null) { return string.Empty; } diff --git a/src/System.Management.Automation/engine/EventManager.cs b/src/System.Management.Automation/engine/EventManager.cs index b6d3dc27909..a962f745eac 100644 --- a/src/System.Management.Automation/engine/EventManager.cs +++ b/src/System.Management.Automation/engine/EventManager.cs @@ -557,7 +557,7 @@ public override PSEventSubscriber SubscribeEvent(object source, string eventName private bool _timerInitialized = false; private bool _isTimerActive = false; /// - /// We sample every 100ms to check if the engine is idle (currentlyRunningPipeline is null). If it's "idle" + /// We sample every 100ms to check if the engine is idle (currentlyRunningPipeline == null). If it's "idle" /// in four consecutive samples, then we believe it's actually idle. In this way we can avoid capturing possible /// pipeline transitions. /// @@ -574,14 +574,14 @@ private void OnElapsedEvent(object source) { var localRunspace = _context.CurrentRunspace as LocalRunspace; - if (localRunspace is null) + if (localRunspace == null) { // This should never happen, the context should always reference to the local runspace _consecutiveIdleSamples = 0; return; } - if (localRunspace.GetCurrentlyRunningPipeline() is null) + if (localRunspace.GetCurrentlyRunningPipeline() == null) { _consecutiveIdleSamples++; } @@ -646,7 +646,7 @@ private void ProcessNewSubscriber(PSEventSubscriber subscriber, object source, s { Delegate handlerDelegate = null; - if (_eventAssembly is null) + if (_eventAssembly == null) { _eventAssembly = AssemblyBuilder.DefineDynamicAssembly( new AssemblyName("PSEventHandler"), @@ -684,7 +684,7 @@ private void ProcessNewSubscriber(PSEventSubscriber subscriber, object source, s eventInfo = sourceType.GetEvent(eventName, bindingFlags); // If we can't find the event, throw an exception - if (eventInfo is null) + if (eventInfo == null) { string errorMessage = StringUtil.Format(EventingResources.CouldNotFindEvent, eventName); throw new ArgumentException(errorMessage, nameof(eventName)); @@ -762,7 +762,7 @@ private void ProcessNewSubscriber(PSEventSubscriber subscriber, object source, s lock (_eventSubscribers) { _eventSubscribers[subscriber] = handlerDelegate; - if (engineEventSourceIdentifier is null) + if (engineEventSourceIdentifier == null) { return; } @@ -817,7 +817,7 @@ public override void UnsubscribeEvent(PSEventSubscriber subscriber) /// private void UnsubscribeEvent(PSEventSubscriber subscriber, bool skipDraining) { - if (subscriber is null) + if (subscriber == null) { throw new ArgumentNullException(nameof(subscriber)); } @@ -1628,7 +1628,7 @@ internal override void AddForwardedEvent(PSEventArgs forwardedEvent) // The computer name will be null the first time the event is forwarded; in this case we need to override with the // remote computer this event manager is associated to. If the event has travelled multiple hops then we do not // want to override this value since we want to preserve the original computer. - if (forwardedEvent.ComputerName is null || forwardedEvent.ComputerName.Length == 0) + if (forwardedEvent.ComputerName == null || forwardedEvent.ComputerName.Length == 0) { forwardedEvent.ComputerName = _computerName; forwardedEvent.RunspaceId = _runspaceId; @@ -2048,7 +2048,7 @@ private ScriptBlock CreateBoundScriptBlock(ScriptBlock scriptAction) /// public bool Equals(PSEventSubscriber other) { - if (other is null) + if (other == null) { return false; } @@ -2362,7 +2362,7 @@ public class PSEventArgsCollection : IEnumerable /// Don't add events to the collection directly; use the EventManager instead internal void Add(PSEventArgs eventToAdd) { - if (eventToAdd is null) + if (eventToAdd == null) { throw new ArgumentNullException(nameof(eventToAdd)); } @@ -2478,11 +2478,11 @@ public class PSEventJob : Job /// /// public PSEventJob(PSEventManager eventManager, PSEventSubscriber subscriber, ScriptBlock action, string name) : - base(action is null ? null : action.ToString(), name) + base(action == null ? null : action.ToString(), name) { - if (eventManager is null) + if (eventManager == null) throw new ArgumentNullException(nameof(eventManager)); - if (subscriber is null) + if (subscriber == null) throw new ArgumentNullException(nameof(subscriber)); UsesResultsCollection = true; diff --git a/src/System.Management.Automation/engine/ExecutionContext.cs b/src/System.Management.Automation/engine/ExecutionContext.cs index 70dec4a3f4e..98f0b3deb5a 100644 --- a/src/System.Management.Automation/engine/ExecutionContext.cs +++ b/src/System.Management.Automation/engine/ExecutionContext.cs @@ -108,7 +108,7 @@ internal bool PSDebugTraceStep // Helper for generated code to handle running w/ no execution context internal static bool IsStrictVersion(ExecutionContext context, int majorVersion) { - if (context is null) + if (context == null) { context = LocalPipeline.GetExecutionContextFromTLS(); } @@ -210,7 +210,7 @@ internal bool TakeResponsibilityForModuleAnalysisAppDomain() return false; } - Diagnostics.Assert(AppDomainForModuleAnalysis is null, "Invalid module analysis app domain state"); + Diagnostics.Assert(AppDomainForModuleAnalysis == null, "Invalid module analysis app domain state"); _responsibilityForModuleAnalysisAppDomainOwned = true; return true; } @@ -249,7 +249,7 @@ internal ProviderNames ProviderNames { get { - if (_providerNames is null) + if (_providerNames == null) { _providerNames = new SingleShellProviderNames(); } @@ -272,7 +272,7 @@ internal string ShellID { get { - if (_shellId is null) + if (_shellId == null) { // Use the ShellID from PSAuthorizationManager before everything else because that's what's used // to check execution policy... @@ -454,9 +454,9 @@ internal static void MarkObjectAsUntrusted(object value) /// internal static void MarkObjectAsUntrustedForVariableAssignment(PSVariable variable, SessionStateScope scope, SessionStateInternal sessionState) { - if (scope.Parent is null || // If it's the global scope, OR + if (scope.Parent == null || // If it's the global scope, OR (sessionState.Module != null && // it's running in a module AND - scope.ScriptScope == scope && scope.Parent.Parent is null)) // it's the module's script scope (scope.Parent is global scope and scope.ScriptScope points to itself) + scope.ScriptScope == scope && scope.Parent.Parent == null)) // it's the module's script scope (scope.Parent is global scope and scope.ScriptScope points to itself) { // We are setting value for either a 'Global:' variable, or a 'Script:' variable within a module in 'ConstrainedLanguage' mode. // Global variable may be referenced within trusted script block (scriptBlock.LanguageMode == 'FullLanguage'), and users could @@ -645,7 +645,7 @@ internal bool GetBooleanPreference(VariablePath preferenceVariablePath, bool def CmdletProviderContext context = null; SessionStateScope scope = null; object val = EngineSessionState.GetVariableValue(preferenceVariablePath, out context, out scope); - if (val is null) + if (val == null) { defaultUsed = true; return defaultPref; @@ -875,7 +875,7 @@ internal void ResetRedirection() internal void AppendDollarError(object obj) { ErrorRecord objAsErrorRecord = obj as ErrorRecord; - if (objAsErrorRecord is null && !(obj is Exception)) + if (objAsErrorRecord == null && !(obj is Exception)) { Diagnostics.Assert(false, "Object to append was neither an ErrorRecord nor an Exception in ExecutionContext.AppendDollarError"); return; @@ -883,7 +883,7 @@ internal void AppendDollarError(object obj) object old = this.DollarErrorVariable; ArrayList arraylist = old as ArrayList; - if (arraylist is null) + if (arraylist == null) { Diagnostics.Assert(false, "$error should be a global constant ArrayList"); return; @@ -961,10 +961,10 @@ internal Runspace CurrentRunspace /// internal void PushPipelineProcessor(PipelineProcessor pp) { - if (_currentRunspace is null) + if (_currentRunspace == null) return; LocalPipeline lpl = (LocalPipeline)((RunspaceBase)_currentRunspace).GetCurrentlyRunningPipeline(); - if (lpl is null) + if (lpl == null) return; lpl.Stopper.Push(pp); } @@ -975,10 +975,10 @@ internal void PushPipelineProcessor(PipelineProcessor pp) /// internal void PopPipelineProcessor(bool fromSteppablePipeline) { - if (_currentRunspace is null) + if (_currentRunspace == null) return; LocalPipeline lpl = (LocalPipeline)((RunspaceBase)_currentRunspace).GetCurrentlyRunningPipeline(); - if (lpl is null) + if (lpl == null) return; lpl.Stopper.Pop(fromSteppablePipeline); } @@ -991,10 +991,10 @@ internal bool CurrentPipelineStopping { get { - if (_currentRunspace is null) + if (_currentRunspace == null) return false; LocalPipeline lpl = (LocalPipeline)((RunspaceBase)_currentRunspace).GetCurrentlyRunningPipeline(); - if (lpl is null) + if (lpl == null) return false; return lpl.IsStopping; } @@ -1230,7 +1230,7 @@ internal TypeTable TypeTable { get { - if (_typeTable is null) + if (_typeTable == null) { _typeTable = new TypeTable(); _typeTableWeakReference = new WeakReference(_typeTable); @@ -1253,7 +1253,7 @@ internal WeakReference TypeTableWeakReference { get { - if (_typeTable is null) + if (_typeTable == null) { var unused = TypeTable; } @@ -1272,7 +1272,7 @@ internal TypeInfoDataBaseManager FormatDBManager { get { - if (_formatDBManager is null) + if (_formatDBManager == null) { // If no Formatter database has been created, then // create and initialize an empty one. @@ -1315,7 +1315,7 @@ internal Assembly AddAssembly(string name, string filename, out Exception error) { Assembly loadedAssembly = LoadAssembly(name, filename, out error); - if (loadedAssembly is null) + if (loadedAssembly == null) return null; if (AssemblyCache.ContainsKey(loadedAssembly.FullName)) @@ -1446,9 +1446,9 @@ internal void ReportEngineStartupError(string resourceString, params object[] ar else { PSHost host = EngineHostInterface; - if (host is null) return; + if (host == null) return; PSHostUserInterface ui = host.UI; - if (ui is null) return; + if (ui == null) return; ui.WriteErrorLine( StringUtil.Format(resourceString, arguments)); } @@ -1476,9 +1476,9 @@ internal void ReportEngineStartupError(string error) else { PSHost host = EngineHostInterface; - if (host is null) return; + if (host == null) return; PSHostUserInterface ui = host.UI; - if (ui is null) return; + if (ui == null) return; ui.WriteErrorLine(error); } } @@ -1511,9 +1511,9 @@ internal void ReportEngineStartupError(Exception e) else { PSHost host = EngineHostInterface; - if (host is null) return; + if (host == null) return; PSHostUserInterface ui = host.UI; - if (ui is null) return; + if (ui == null) return; ui.WriteErrorLine(e.Message); } } @@ -1539,9 +1539,9 @@ internal void ReportEngineStartupError(ErrorRecord errorRecord) else { PSHost host = EngineHostInterface; - if (host is null) return; + if (host == null) return; PSHostUserInterface ui = host.UI; - if (ui is null) return; + if (ui == null) return; ui.WriteErrorLine(errorRecord.ToString()); } } @@ -1626,7 +1626,7 @@ private void InitializeCommon(AutomationEngine engine, PSHost hostInterface) // Initialize the fixed toplevel session state and the current session state TopLevelSessionState = EngineSessionState = new SessionStateInternal(this); - if (AuthorizationManager is null) + if (AuthorizationManager == null) { // if authorizationmanager==null, this means the configuration // explicitly asked for dummy authorization manager. diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/EnableDisableExperimentalFeatureCommand.cs b/src/System.Management.Automation/engine/ExperimentalFeature/EnableDisableExperimentalFeatureCommand.cs index 9a75e428f70..c15d8628cb9 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/EnableDisableExperimentalFeatureCommand.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/EnableDisableExperimentalFeatureCommand.cs @@ -114,7 +114,7 @@ public class ExperimentalFeatureNameCompleter : IArgumentCompleter /// List of Completion Results. public IEnumerable CompleteArgument(string commandName, string parameterName, string wordToComplete, CommandAst commandAst, IDictionary fakeBoundParameters) { - if (fakeBoundParameters is null) + if (fakeBoundParameters == null) { throw PSTraceSource.NewArgumentNullException(nameof(fakeBoundParameters)); } diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs index 73099c9e073..f6993a03a0a 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs @@ -235,7 +235,7 @@ internal static bool IsModuleFeatureName(string featureName, string moduleName = return false; } - if (moduleName is null) + if (moduleName == null) { return true; } @@ -250,7 +250,7 @@ internal static bool IsModuleFeatureName(string featureName, string moduleName = /// internal static ExperimentAction GetActionToTake(string experimentName, ExperimentAction experimentAction) { - if (experimentName is null || experimentAction == ExperimentAction.None) + if (experimentName == null || experimentAction == ExperimentAction.None) { // If either the experiment name or action is not defined, then return 'Show' by default. // This could happen to 'ParameterAttribute' when no experimental related field is declared. diff --git a/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs b/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs index d7b5fe9c577..542ad8bbf7e 100644 --- a/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs +++ b/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs @@ -530,7 +530,7 @@ public class PSInvalidCastException : InvalidCastException, IContainsErrorRecord [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) { throw new PSArgumentNullException(nameof(info)); } @@ -591,7 +591,7 @@ public ErrorRecord ErrorRecord { get { - if (_errorRecord is null) + if (_errorRecord == null) { _errorRecord = new ErrorRecord( new ParentContainsErrorRecordException(this), diff --git a/src/System.Management.Automation/engine/ExternalScriptInfo.cs b/src/System.Management.Automation/engine/ExternalScriptInfo.cs index e2119fb70b1..d87e3027f2e 100644 --- a/src/System.Management.Automation/engine/ExternalScriptInfo.cs +++ b/src/System.Management.Automation/engine/ExternalScriptInfo.cs @@ -188,7 +188,7 @@ public override SessionStateEntryVisibility Visibility { get { - if (Context is null) return SessionStateEntryVisibility.Public; + if (Context == null) return SessionStateEntryVisibility.Public; return Context.EngineSessionState.CheckScriptVisibility(_path); } @@ -203,7 +203,7 @@ public ScriptBlock ScriptBlock { get { - if (_scriptBlock is null) + if (_scriptBlock == null) { // Skip ShouldRun check for .psd1 files. // Use ValidateScriptInfo() for explicitly validating the checkpolicy for psd1 file. @@ -262,7 +262,7 @@ private static ScriptBlock ParseScriptContents(Parser parser, string fileName, s internal ScriptBlockAst GetScriptBlockAst() { var scriptContents = ScriptContents; - if (_scriptBlock is null) + if (_scriptBlock == null) { this.ScriptBlock = ScriptBlock.TryGetCachedScriptBlock(_path, scriptContents); } @@ -272,7 +272,7 @@ internal ScriptBlockAst GetScriptBlockAst() return (ScriptBlockAst)_scriptBlock.Ast; } - if (_scriptBlockAst is null) + if (_scriptBlockAst == null) { ParseError[] errors; Parser parser = new Parser(); @@ -403,7 +403,7 @@ internal string RequiresApplicationID get { var data = GetRequiresData(); - return data is null ? null : data.RequiredApplicationId; + return data == null ? null : data.RequiredApplicationId; } } @@ -417,7 +417,7 @@ internal Version RequiresPSVersion get { var data = GetRequiresData(); - return data is null ? null : data.RequiredPSVersion; + return data == null ? null : data.RequiredPSVersion; } } @@ -426,7 +426,7 @@ internal IEnumerable RequiresPSEditions get { var data = GetRequiresData(); - return data is null ? null : data.RequiredPSEditions; + return data == null ? null : data.RequiredPSEditions; } } @@ -435,7 +435,7 @@ internal IEnumerable RequiresModules get { var data = GetRequiresData(); - return data is null ? null : data.RequiredModules; + return data == null ? null : data.RequiredModules; } } @@ -444,7 +444,7 @@ internal bool RequiresElevation get { var data = GetRequiresData(); - return data is null ? false : data.IsElevationRequired; + return data == null ? false : data.IsElevationRequired; } } @@ -458,7 +458,7 @@ internal IEnumerable RequiresPSSnapIns get { var data = GetRequiresData(); - return data is null ? null : data.RequiresPSSnapIns; + return data == null ? null : data.RequiresPSSnapIns; } } @@ -469,7 +469,7 @@ public string ScriptContents { get { - if (_scriptContents is null) + if (_scriptContents == null) { ReadScriptContents(); } @@ -487,7 +487,7 @@ public Encoding OriginalEncoding { get { - if (_scriptContents is null) + if (_scriptContents == null) { ReadScriptContents(); } @@ -500,7 +500,7 @@ public Encoding OriginalEncoding private void ReadScriptContents() { - if (_scriptContents is null) + if (_scriptContents == null) { // make sure we can actually load the script and that it's non-empty // before we call it. diff --git a/src/System.Management.Automation/engine/ExtraAdapter.cs b/src/System.Management.Automation/engine/ExtraAdapter.cs index 5fe3eb984cf..dd6ba0c0784 100644 --- a/src/System.Management.Automation/engine/ExtraAdapter.cs +++ b/src/System.Management.Automation/engine/ExtraAdapter.cs @@ -66,7 +66,7 @@ protected override T GetMember(object obj, string memberName) object invokeGetValue = entry.InvokeGet(memberName); // if entry.Properties[memberName] returns empty value and invokeGet non-empty // value..take invokeGet's value. This will fix bug Windows Bug 121188. - if ((collection is null) || ((collection.Value is null) && (invokeGetValue != null))) + if ((collection == null) || ((collection.Value == null) && (invokeGetValue != null))) { valueToTake = invokeGetValue; } @@ -79,7 +79,7 @@ protected override T GetMember(object obj, string memberName) } #pragma warning restore 56500 - if (valueToTake is null) + if (valueToTake == null) { property = null; } @@ -91,7 +91,7 @@ protected override T GetMember(object obj, string memberName) if (typeof(T).IsAssignableFrom(typeof(PSMethod))) { - if (property is null) + if (property == null) { #region Readme // we are unable to find a native adsi object property. @@ -113,7 +113,7 @@ protected override T GetMember(object obj, string memberName) // method. #endregion - if (base.GetDotNetProperty(obj, memberName) is null) + if (base.GetDotNetProperty(obj, memberName) == null) { return new PSMethod(memberName, this, obj, null) as T; } @@ -141,7 +141,7 @@ protected override PSMemberInfoInternalCollection GetMembers(object obj) PSMemberInfoInternalCollection members = new PSMemberInfoInternalCollection(); - if (entry.Properties is null || entry.Properties.PropertyNames is null) + if (entry.Properties == null || entry.Properties.PropertyNames == null) { return null; } @@ -202,7 +202,7 @@ protected override void PropertySet(PSProperty property, object setValue, bool c } catch (System.Runtime.InteropServices.COMException e) { - if (e.ErrorCode != unchecked((int)0x80004005) || (setValue is null)) + if (e.ErrorCode != unchecked((int)0x80004005) || (setValue == null)) // When clear is called, DirectoryEntry calls PutEx on AD object with Clear option and Null Value // WinNT provider throws E_FAIL when null value is specified though actually ADS_PROPERTY_CLEAR option is used, // we need to catch this exception here. @@ -212,7 +212,7 @@ protected override void PropertySet(PSProperty property, object setValue, bool c IEnumerable enumValues = LanguagePrimitives.GetEnumerable(setValue); - if (enumValues is null) + if (enumValues == null) { values.Add(setValue); } @@ -233,7 +233,7 @@ protected override void PropertySet(PSProperty property, object setValue, bool c List setValues = new List(); IEnumerable enumValues = LanguagePrimitives.GetEnumerable(setValue); - if (enumValues is null) + if (enumValues == null) { setValues.Add(setValue); } @@ -288,7 +288,7 @@ protected override string PropertyType(PSProperty property, bool forDisplay) { } - var type = value is null ? typeof(object) : value.GetType(); + var type = value == null ? typeof(object) : value.GetType(); return forDisplay ? ToStringCodeMethods.Type(type) : type.FullName; } diff --git a/src/System.Management.Automation/engine/FunctionInfo.cs b/src/System.Management.Automation/engine/FunctionInfo.cs index c537cfeb888..8afe41ece15 100644 --- a/src/System.Management.Automation/engine/FunctionInfo.cs +++ b/src/System.Management.Automation/engine/FunctionInfo.cs @@ -53,7 +53,7 @@ internal FunctionInfo(string name, ScriptBlock function, ExecutionContext contex /// internal FunctionInfo(string name, ScriptBlock function, ExecutionContext context, string helpFile) : base(name, CommandTypes.Function, context) { - if (function is null) + if (function == null) { throw PSTraceSource.NewArgumentNullException(nameof(function)); } @@ -220,7 +220,7 @@ protected internal virtual void Update(FunctionInfo newFunction, bool force, Sco /// internal void Update(ScriptBlock newFunction, bool force, ScopedItemOptions options, string helpFile) { - if (newFunction is null) + if (newFunction == null) { throw PSTraceSource.NewArgumentNullException("function"); } @@ -304,12 +304,12 @@ public ScopedItemOptions Options { get { - return CopiedCommand is null ? _options : ((FunctionInfo)CopiedCommand).Options; + return CopiedCommand == null ? _options : ((FunctionInfo)CopiedCommand).Options; } set { - if (CopiedCommand is null) + if (CopiedCommand == null) { // Check to see if the function is constant, if so // throw an exception because the options cannot be changed. @@ -378,12 +378,12 @@ public string Description { get { - return CopiedCommand is null ? _description : ((FunctionInfo)CopiedCommand).Description; + return CopiedCommand == null ? _description : ((FunctionInfo)CopiedCommand).Description; } set { - if (CopiedCommand is null) + if (CopiedCommand == null) { _description = value; } diff --git a/src/System.Management.Automation/engine/GetCommandCommand.cs b/src/System.Management.Automation/engine/GetCommandCommand.cs index 7c31186d6ed..b3ab36ae19c 100644 --- a/src/System.Management.Automation/engine/GetCommandCommand.cs +++ b/src/System.Management.Automation/engine/GetCommandCommand.cs @@ -80,7 +80,7 @@ public string[] Verb set { - if (value is null) + if (value == null) { value = Array.Empty(); } @@ -106,7 +106,7 @@ public string[] Noun set { - if (value is null) + if (value == null) { value = Array.Empty(); } @@ -132,7 +132,7 @@ public string[] Module set { - if (value is null) + if (value == null) { value = Array.Empty(); } @@ -284,7 +284,7 @@ public string[] ParameterName set { - if (value is null) + if (value == null) { throw new ArgumentNullException("value"); } @@ -314,7 +314,7 @@ public PSTypeName[] ParameterType set { - if (value is null) + if (value == null) { throw new ArgumentNullException("value"); } @@ -402,7 +402,7 @@ protected override void ProcessRecord() } // Initialize the module patterns - if (_modulePatterns is null) + if (_modulePatterns == null) { _modulePatterns = SessionStateUtilities.CreateWildcardsFromStrings(Module, WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); } @@ -432,7 +432,7 @@ protected override void EndProcessing() { // We do not show the pithy aliases (not of the format Verb-Noun) and applications by default. // We will show them only if the Name, All and totalCount are not specified. - if ((this.Name is null) && (!_all) && TotalCount == -1 && !UseFuzzyMatching) + if ((this.Name == null) && (!_all) && TotalCount == -1 && !UseFuzzyMatching) { CommandTypes commandTypesToIgnore = 0; @@ -481,7 +481,7 @@ protected override void EndProcessing() } // Only sort if they didn't fully specify a name) - if ((_names is null) || (_nameContainsWildcard)) + if ((_names == null) || (_nameContainsWildcard)) { // Use the stable sorting to sort the result list _accumulatedResults = _accumulatedResults.OrderBy(a => a, new CommandInfoComparer()).ToList(); @@ -688,12 +688,12 @@ private bool IsNounVerbMatch(CommandInfo command) do // false loop { - if (_verbPatterns is null) + if (_verbPatterns == null) { _verbPatterns = SessionStateUtilities.CreateWildcardsFromStrings(Verb, WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); } - if (_nounPatterns is null) + if (_nounPatterns == null) { _nounPatterns = SessionStateUtilities.CreateWildcardsFromStrings(Noun, WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); } @@ -1151,12 +1151,12 @@ private bool IsDuplicate(CommandInfo info) private bool IsParameterMatch(CommandInfo commandInfo) { - if ((this.ParameterName is null) && (this.ParameterType is null)) + if ((this.ParameterName == null) && (this.ParameterType == null)) { return true; } - if (_matchedParameterNames is null) + if (_matchedParameterNames == null) { _matchedParameterNames = new HashSet(StringComparer.OrdinalIgnoreCase); } @@ -1176,7 +1176,7 @@ private bool IsParameterMatch(CommandInfo commandInfo) // and proceed as if there was no parameter metadata } - if (commandParameters is null) + if (commandParameters == null) { // do not match commands which have not been imported yet / for which we don't have parameter metadata yet return false; @@ -1227,7 +1227,7 @@ private bool IsParameterMatch(ParameterMetadata parameterMetadata) // bool typeIsMatching; - if ((_parameterTypes is null) || (_parameterTypes.Length == 0)) + if ((_parameterTypes == null) || (_parameterTypes.Length == 0)) { typeIsMatching = true; } @@ -1314,7 +1314,7 @@ private bool IsCommandMatch(ref CommandInfo current, out bool isDuplicate) // there are situations where both ResolvedCommand and UnresolvedCommandName // are both null (often due to multiple versions of modules with aliases) // therefore we need to exit early. - if (current is null) + if (current == null) { return false; } @@ -1567,7 +1567,7 @@ private static PSObject[] GetParameterSets(CommandInfo cmdInfo) catch (PSNotSupportedException) { } catch (PSNotImplementedException) { } - if (parameterSets is null) + if (parameterSets == null) { return Array.Empty(); } @@ -1656,7 +1656,7 @@ public class NounArgumentCompleter : IArgumentCompleter /// public IEnumerable CompleteArgument(string commandName, string parameterName, string wordToComplete, CommandAst commandAst, IDictionary fakeBoundParameters) { - if (fakeBoundParameters is null) + if (fakeBoundParameters == null) { throw PSTraceSource.NewArgumentNullException(nameof(fakeBoundParameters)); } diff --git a/src/System.Management.Automation/engine/InformationRecord.cs b/src/System.Management.Automation/engine/InformationRecord.cs index e8ade610f0a..81a9789bb81 100644 --- a/src/System.Management.Automation/engine/InformationRecord.cs +++ b/src/System.Management.Automation/engine/InformationRecord.cs @@ -97,7 +97,7 @@ public string User { get { - if (this._user is null) + if (this._user == null) { // domain\user on Windows, just user on Unix #if UNIX diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index 8f1c39922a8..0d2e1274aa6 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -201,7 +201,7 @@ public SessionStateTypeEntry(string fileName) public SessionStateTypeEntry(TypeTable typeTable) : base("*") { - if (typeTable is null) + if (typeTable == null) { throw PSTraceSource.NewArgumentNullException(nameof(typeTable)); } @@ -217,7 +217,7 @@ public SessionStateTypeEntry(TypeTable typeTable) public SessionStateTypeEntry(TypeData typeData, bool isRemove) : base("*") { - if (typeData is null) + if (typeData == null) { throw PSTraceSource.NewArgumentNullException(nameof(typeData)); } @@ -308,7 +308,7 @@ public SessionStateFormatEntry(string fileName) public SessionStateFormatEntry(FormatTable formattable) : base("*") { - if (formattable is null) + if (formattable == null) { throw PSTraceSource.NewArgumentNullException(nameof(formattable)); } @@ -323,7 +323,7 @@ public SessionStateFormatEntry(FormatTable formattable) public SessionStateFormatEntry(ExtendedTypeDefinition typeDefinition) : base("*") { - if (typeDefinition is null) + if (typeDefinition == null) { throw PSTraceSource.NewArgumentNullException(nameof(typeDefinition)); } @@ -977,7 +977,7 @@ public InitialSessionStateEntryCollection() /// public InitialSessionStateEntryCollection(IEnumerable items) { - if (items is null) + if (items == null) { throw new ArgumentNullException(nameof(items)); } @@ -1081,7 +1081,7 @@ public Collection this[string name] /// internal Collection LookUpByName(string name) { - if (name is null) + if (name == null) { throw new PSArgumentNullException(nameof(name)); } @@ -1151,7 +1151,7 @@ public void Clear() /// The type of object to remove, can be null to remove any type. public void Remove(string name, object type) { - if (name is null) + if (name == null) { throw new ArgumentNullException(nameof(name)); } @@ -1169,12 +1169,12 @@ public void Remove(string name, object type) for (int i = _internalCollection.Count - 1; i >= 0; i--) { T element = _internalCollection[i]; - if (element is null) + if (element == null) { continue; } - if ((objType is null || element.GetType() == objType) && + if ((objType == null || element.GetType() == objType) && string.Equals(element.Name, name, StringComparison.OrdinalIgnoreCase)) { _internalCollection.RemoveAt(i); @@ -1189,7 +1189,7 @@ public void Remove(string name, object type) /// The item to add... public void Add(T item) { - if (item is null) + if (item == null) { throw new ArgumentNullException(nameof(item)); } @@ -1206,7 +1206,7 @@ public void Add(T item) /// public void Add(IEnumerable items) { - if (items is null) + if (items == null) { throw new ArgumentNullException(nameof(items)); } @@ -1837,7 +1837,7 @@ public Microsoft.PowerShell.ExecutionPolicy ExecutionPolicy /// public void ImportPSModule(params string[] name) { - if (name is null) + if (name == null) { throw new ArgumentNullException(nameof(name)); } @@ -1865,7 +1865,7 @@ internal void ClearPSModules() /// public void ImportPSModule(IEnumerable modules) { - if (modules is null) + if (modules == null) { throw new ArgumentNullException(nameof(modules)); } @@ -1896,7 +1896,7 @@ public void ImportPSModulesFromPath(string path) /// internal void ImportPSCoreModule(string[] name) { - if (name is null) + if (name == null) { throw new ArgumentNullException(nameof(name)); } @@ -1931,7 +1931,7 @@ public virtual InitialSessionStateEntryCollection Ass { get { - if (_assemblies is null) + if (_assemblies == null) { Interlocked.CompareExchange(ref _assemblies, new InitialSessionStateEntryCollection(), null); } @@ -1949,7 +1949,7 @@ public virtual InitialSessionStateEntryCollection Types { get { - if (_types is null) + if (_types == null) { Interlocked.CompareExchange(ref _types, new InitialSessionStateEntryCollection(), null); } @@ -1966,7 +1966,7 @@ public virtual InitialSessionStateEntryCollection Forma { get { - if (_formats is null) + if (_formats == null) { Interlocked.CompareExchange(ref _formats, new InitialSessionStateEntryCollection(), null); } @@ -1991,7 +1991,7 @@ public virtual InitialSessionStateEntryCollection Pro { get { - if (_providers is null) + if (_providers == null) { Interlocked.CompareExchange(ref _providers, new InitialSessionStateEntryCollection(), null); } @@ -2009,7 +2009,7 @@ public virtual InitialSessionStateEntryCollection Comm { get { - if (_commands is null) + if (_commands == null) { Interlocked.CompareExchange(ref _commands, new InitialSessionStateEntryCollection(), null); } @@ -2026,7 +2026,7 @@ internal HashSet UnresolvedCommandsToExpose { get { - if (_unresolvedCommandsToExpose is null) + if (_unresolvedCommandsToExpose == null) { Interlocked.CompareExchange(ref _unresolvedCommandsToExpose, new HashSet(StringComparer.OrdinalIgnoreCase), null); } @@ -2041,7 +2041,7 @@ internal Dictionary CommandModifications { get { - if (_commandModifications is null) + if (_commandModifications == null) { Interlocked.CompareExchange(ref _commandModifications, new Dictionary(StringComparer.OrdinalIgnoreCase), null); } @@ -2056,7 +2056,7 @@ internal List DynamicVariablesToDefine { get { - if (_dynamicVariablesToDefine is null) + if (_dynamicVariablesToDefine == null) { Interlocked.CompareExchange(ref _dynamicVariablesToDefine, new List(), null); } @@ -2073,7 +2073,7 @@ public virtual InitialSessionStateEntryCollection Var { get { - if (_variables is null) + if (_variables == null) { Interlocked.CompareExchange(ref _variables, new InitialSessionStateEntryCollection(), null); } @@ -2090,7 +2090,7 @@ public virtual InitialSessionStateEntryCollection Env { get { - if (_environmentVariables is null) + if (_environmentVariables == null) { Interlocked.CompareExchange(ref _environmentVariables, new InitialSessionStateEntryCollection(), null); } @@ -2107,7 +2107,7 @@ public virtual HashSet StartupScripts { get { - if (_startupScripts is null) + if (_startupScripts == null) { Interlocked.CompareExchange(ref _startupScripts, new HashSet(), null); } @@ -2420,11 +2420,11 @@ private void Bind_LoadAssemblies(ExecutionContext context) Exception error = null; Assembly asm = context.AddAssembly(ssae.Name, ssae.FileName, out error); - if (asm is null || error != null) + if (asm == null || error != null) { // If no module was found but there was no specific error, then // create a not found error. - if (error is null) + if (error == null) { string msg = StringUtil.Format(global::Modules.ModuleAssemblyFound, ssae.Name); error = new DllNotFoundException(msg); @@ -2655,7 +2655,7 @@ private void ProcessCommandModifications(Runspace initializedRunspace) Hashtable commandModification = pair.Value; CommandInfo existingCommand = initializedRunspace.SessionStateProxy.InvokeCommand.GetCommand(commandName, CommandTypes.Cmdlet | CommandTypes.Function); - if (existingCommand is null) + if (existingCommand == null) { // Could not find the command - just continue, rather than generating an error. This could just be a missing module // or something similar. @@ -2962,7 +2962,7 @@ private RunspaceOpenModuleLoadException ProcessModulesToImport( ModuleSpecification moduleSpecification = module as ModuleSpecification; if (moduleSpecification != null) { - if ((moduleSpecification.RequiredVersion is null) && (moduleSpecification.Version is null) && (moduleSpecification.MaximumVersion is null) && (moduleSpecification.Guid is null)) + if ((moduleSpecification.RequiredVersion == null) && (moduleSpecification.Version == null) && (moduleSpecification.MaximumVersion == null) && (moduleSpecification.Guid == null)) { // if only name is specified in the module spec, just try import the module // ie., don't take the performance overhead of calling GetModule. @@ -3014,7 +3014,7 @@ private RunspaceOpenModuleLoadException ProcessModulesToImport( } } - if (exceptionToReturn is null) + if (exceptionToReturn == null) { // Now go through the list of commands not yet resolved to ensure they are public if requested foreach (string unresolvedCommand in unresolvedCmdsToExpose.ToArray()) @@ -3317,7 +3317,7 @@ internal static void SetSessionStateDrive(ExecutionContext context, bool setLoca // Make sure we have a CurrentDrive set so that we can deal with // UNC paths - if (context.EngineSessionState.CurrentDrive is null) + if (context.EngineSessionState.CurrentDrive == null) { bool fsDriveSet = false; try @@ -3519,7 +3519,7 @@ internal static void RemoveTypesAndFormats(ExecutionContext context, IList> aliases = null; Dictionary providers = null; - if (psSnapInInfo is null) + if (psSnapInInfo == null) { ArgumentNullException e = new ArgumentNullException(nameof(psSnapInInfo)); throw e; @@ -3883,7 +3883,7 @@ internal PSSnapInInfo ImportPSSnapIn(PSSnapInInfo psSnapInInfo, out PSSnapInExce assembly = PSSnapInHelpers.LoadPSSnapInAssembly(psSnapInInfo); - if (assembly is null) + if (assembly == null) { s_PSSnapInTracer.TraceError("Loading assembly for psSnapIn {0} failed", psSnapInInfo.Name); warning = null; @@ -4002,7 +4002,7 @@ internal List GetPSSnapIn(string psSnapinName) { if (defaultSnapin.Name.Equals(psSnapinName, StringComparison.OrdinalIgnoreCase)) { - if (loadedSnapins is null) + if (loadedSnapins == null) { loadedSnapins = new List(); } @@ -4014,7 +4014,7 @@ internal List GetPSSnapIn(string psSnapinName) PSSnapInInfo importedSnapin = null; if (ImportedSnapins.TryGetValue(psSnapinName, out importedSnapin)) { - if (loadedSnapins is null) + if (loadedSnapins == null) { loadedSnapins = new List(); } @@ -4031,7 +4031,7 @@ internal static Assembly LoadAssemblyFromFile(string fileName) s_PSSnapInTracer.WriteLine("Loading assembly for psSnapIn {0}", fileName); Assembly assembly = Assembly.LoadFrom(fileName); - if (assembly is null) + if (assembly == null) { s_PSSnapInTracer.TraceError("Loading assembly for psSnapIn {0} failed", fileName); return null; @@ -4044,7 +4044,7 @@ internal static Assembly LoadAssemblyFromFile(string fileName) internal void ImportCmdletsFromAssembly(Assembly assembly, PSModuleInfo module) { - if (assembly is null) + if (assembly == null) { ArgumentNullException e = new ArgumentNullException(nameof(assembly)); throw e; @@ -4994,7 +4994,7 @@ internal static void AnalyzePSSnapInAssembly( out string helpFile) { helpFile = null; - if (assembly is null) + if (assembly == null) { throw new ArgumentNullException(nameof(assembly)); } @@ -5015,13 +5015,13 @@ internal static void AnalyzePSSnapInAssembly( { var key = pair.Key; var entry = pair.Value; - if (entry.Item1.PSSnapIn is null && psSnapInInfo != null) + if (entry.Item1.PSSnapIn == null && psSnapInInfo != null) { entry.Item1.SetPSSnapIn(psSnapInInfo); } var newEntry = (SessionStateCmdletEntry)entry.Item1.Clone(); - if (newEntry.PSSnapIn != null && psSnapInInfo is null) + if (newEntry.PSSnapIn != null && psSnapInInfo == null) { newEntry.SetPSSnapIn(null); } @@ -5033,13 +5033,13 @@ internal static void AnalyzePSSnapInAssembly( var aliasList = new List(); foreach (var alias in entry.Item2) { - if (alias.PSSnapIn is null && psSnapInInfo != null) + if (alias.PSSnapIn == null && psSnapInInfo != null) { alias.SetPSSnapIn(psSnapInInfo); } var newAliasEntry = (SessionStateAliasEntry)alias.Clone(); - if (newAliasEntry.PSSnapIn != null && psSnapInInfo is null) + if (newAliasEntry.PSSnapIn != null && psSnapInInfo == null) { newAliasEntry.SetPSSnapIn(null); } @@ -5060,13 +5060,13 @@ internal static void AnalyzePSSnapInAssembly( { var key = pair.Key; var entry = pair.Value; - if (entry.PSSnapIn is null && psSnapInInfo != null) + if (entry.PSSnapIn == null && psSnapInInfo != null) { entry.SetPSSnapIn(psSnapInInfo); } var newEntry = (SessionStateProviderEntry)entry.Clone(); - if (newEntry.PSSnapIn != null && psSnapInInfo is null) + if (newEntry.PSSnapIn != null && psSnapInInfo == null) { newEntry.SetPSSnapIn(null); } @@ -5108,7 +5108,7 @@ internal static void AnalyzePSSnapInAssembly( Dictionary> aliasesCheck = null; AnalyzeModuleAssemblyWithReflection(assembly, name, psSnapInInfo, moduleInfo, helpFile, ref cmdletsCheck, ref aliasesCheck, ref providersCheck); - Diagnostics.Assert(aliasesCheck is null, "InitializeCoreCmdletsAndProviders assumes no aliases are defined in System.Management.Automation.dll"); + Diagnostics.Assert(aliasesCheck == null, "InitializeCoreCmdletsAndProviders assumes no aliases are defined in System.Management.Automation.dll"); Diagnostics.Assert(providersCheck.Count == providers.Count, "new Provider added to System.Management.Automation.dll - update InitializeCoreCmdletsAndProviders"); foreach (var pair in providersCheck) { @@ -5475,7 +5475,7 @@ private static bool IsProviderClass(Type type) [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool HasDefaultConstructor(Type type) { - return !(type.GetConstructor(Type.EmptyTypes) is null); + return !(type.GetConstructor(Type.EmptyTypes) == null); } [MethodImpl(MethodImplOptions.AggressiveInlining)] diff --git a/src/System.Management.Automation/engine/InternalCommands.cs b/src/System.Management.Automation/engine/InternalCommands.cs index 72bb825cde9..7c37cc4f0eb 100644 --- a/src/System.Management.Automation/engine/InternalCommands.cs +++ b/src/System.Management.Automation/engine/InternalCommands.cs @@ -125,7 +125,7 @@ public ScriptBlock[] Process set { - if (value is null) + if (value == null) { _scripts.Add(null); } @@ -172,7 +172,7 @@ public ScriptBlock[] RemainingScripts set { - if (value is null) + if (value == null) { _scripts.Add(null); } @@ -618,7 +618,7 @@ private void StopParallelProcessing() private void EndBlockParameterSet() { - if (_endScript is null) + if (_endScript == null) { return; } @@ -781,7 +781,7 @@ private void ProcessPropertyAndMethodParameterSet() { string resolvedPropertyName = null; bool isBlindDynamicAccess = false; - if (member is null) + if (member == null) { if ((_inputObject.BaseObject is IDynamicMetaObjectProvider) && !WildcardPattern.ContainsWildcardCharacters(_propertyOrMethodName)) @@ -992,7 +992,7 @@ private void InitScriptBlockParameterSet() if (_end < 2) return; - if (_scripts[0] is null) + if (_scripts[0] == null) return; var emptyArray = Array.Empty(); @@ -1235,7 +1235,7 @@ private bool BlockMethodInLanguageMode(object inputObject) internal static ErrorRecord GenerateNameParameterError(string paraName, string resourceString, string errorId, object target, params object[] args) { string message; - if (args is null || 0 == args.Length) + if (args == null || 0 == args.Length) { // Don't format in case the string contains literal curly braces message = resourceString; @@ -2009,7 +2009,7 @@ private void CheckLanguageMode() private object GetLikeRHSOperand(object operand) { var val = operand as string; - if (val is null) + if (val == null) { return operand; } @@ -2688,7 +2688,7 @@ private sealed class ValidateVersionAttribute : ValidateArgumentsAttribute protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) { Version version = arguments as Version; - if (version is null || !PSVersionInfo.IsValidPSVersion(version)) + if (version == null || !PSVersionInfo.IsValidPSVersion(version)) { // No conversion succeeded so throw and exception... throw new ValidationMetadataException( diff --git a/src/System.Management.Automation/engine/ItemCmdletProviderInterfaces.cs b/src/System.Management.Automation/engine/ItemCmdletProviderInterfaces.cs index 80eaae1383f..699d60dafa0 100644 --- a/src/System.Management.Automation/engine/ItemCmdletProviderInterfaces.cs +++ b/src/System.Management.Automation/engine/ItemCmdletProviderInterfaces.cs @@ -36,7 +36,7 @@ private ItemCmdletProviderIntrinsics() /// internal ItemCmdletProviderIntrinsics(Cmdlet cmdlet) { - if (cmdlet is null) + if (cmdlet == null) { throw PSTraceSource.NewArgumentNullException(nameof(cmdlet)); } @@ -56,7 +56,7 @@ internal ItemCmdletProviderIntrinsics(Cmdlet cmdlet) /// internal ItemCmdletProviderIntrinsics(SessionStateInternal sessionState) { - if (sessionState is null) + if (sessionState == null) { throw PSTraceSource.NewArgumentNullException(nameof(sessionState)); } diff --git a/src/System.Management.Automation/engine/LanguagePrimitives.cs b/src/System.Management.Automation/engine/LanguagePrimitives.cs index 60d9e4531ef..43c21f512c1 100644 --- a/src/System.Management.Automation/engine/LanguagePrimitives.cs +++ b/src/System.Management.Automation/engine/LanguagePrimitives.cs @@ -56,7 +56,7 @@ public abstract class PSTypeConverter { private static object GetSourceValueAsObject(PSObject sourceValue) { - if (sourceValue is null) + if (sourceValue == null) { return null; } @@ -446,7 +446,7 @@ private static void InitializeGetEnumerableCache() internal static bool IsTypeEnumerable(Type type) { - if (type is null) { return false; } + if (type == null) { return false; } GetEnumerableDelegate getEnumerable = GetOrCalculateEnumerable(type); return (getEnumerable != LanguagePrimitives.ReturnNullEnumerable); @@ -474,7 +474,7 @@ public static bool IsObjectEnumerable(object obj) public static IEnumerable GetEnumerable(object obj) { obj = PSObject.Base(obj); - if (obj is null) { return null; } + if (obj == null) { return null; } GetEnumerableDelegate getEnumerable = GetOrCalculateEnumerable(obj.GetType()); return getEnumerable(obj); @@ -499,7 +499,7 @@ private static IEnumerable TypicalEnumerable(object obj) // raise an exception. Either of these may have a perfectly // good generic implementation, so we'll try those if the // non-generic is no good. - if (e.GetEnumerator() is null) + if (e.GetEnumerator() == null) { return GetEnumerableFromIEnumerableT(obj); } @@ -575,7 +575,7 @@ public static PSDataCollection GetPSDataCollection(object inputValue) { while (e.MoveNext()) { - result.Add(e.Current is null ? null : PSObject.AsPSObject(e.Current)); + result.Add(e.Current == null ? null : PSObject.AsPSObject(e.Current)); } } else @@ -632,13 +632,13 @@ public static bool Equals(object first, object second, bool ignoreCase, IFormatP // If second can be converted to the type of the first, it does so and returns first.Equals(secondConverted) // Otherwise false is returned - if (formatProvider is null) + if (formatProvider == null) { formatProvider = CultureInfo.InvariantCulture; } var culture = formatProvider as CultureInfo; - if (culture is null) + if (culture == null) { throw PSTraceSource.NewArgumentException(nameof(formatProvider)); } @@ -646,12 +646,12 @@ public static bool Equals(object first, object second, bool ignoreCase, IFormatP first = PSObject.Base(first); second = PSObject.Base(second); - if (first is null) + if (first == null) { - return second is null; + return second == null; } - if (second is null) + if (second == null) { return false; // first is not null } @@ -780,13 +780,13 @@ public static int Compare(object first, object second, bool ignoreCase) /// public static int Compare(object first, object second, bool ignoreCase, IFormatProvider formatProvider) { - if (formatProvider is null) + if (formatProvider == null) { formatProvider = CultureInfo.InvariantCulture; } var culture = formatProvider as CultureInfo; - if (culture is null) + if (culture == null) { throw PSTraceSource.NewArgumentException(nameof(formatProvider)); } @@ -794,12 +794,12 @@ public static int Compare(object first, object second, bool ignoreCase, IFormatP first = PSObject.Base(first); second = PSObject.Base(second); - if (first is null) + if (first == null) { - return second is null ? 0 : CompareObjectToNull(second, true); + return second == null ? 0 : CompareObjectToNull(second, true); } - if (second is null) + if (second == null) { return CompareObjectToNull(first, false); } @@ -807,7 +807,7 @@ public static int Compare(object first, object second, bool ignoreCase, IFormatP if (first is string firstString) { string secondString = second as string; - if (secondString is null) + if (secondString == null) { try { @@ -901,7 +901,7 @@ public static bool TryCompare(object first, object second, bool ignoreCase, out public static bool TryCompare(object first, object second, bool ignoreCase, IFormatProvider formatProvider, out int result) { result = 0; - if (formatProvider is null) + if (formatProvider == null) { formatProvider = CultureInfo.InvariantCulture; } @@ -914,19 +914,19 @@ public static bool TryCompare(object first, object second, bool ignoreCase, IFor first = PSObject.Base(first); second = PSObject.Base(second); - if (first is null && second is null) + if (first == null && second == null) { result = 0; return true; } - if (first is null) + if (first == null) { result = CompareObjectToNull(second, true); return true; } - if (second is null) + if (second == null) { // If it's a positive number, including 0, it's greater than null // for everything else it's less than zero... @@ -989,7 +989,7 @@ public static bool TryCompare(object first, object second, bool ignoreCase, IFor public static bool IsTrue(object obj) { // null is a valid argument - it converts to false... - if (obj is null || obj == AutomationNull.Value) + if (obj == null || obj == AutomationNull.Value) return false; obj = PSObject.Base(obj); @@ -1047,7 +1047,7 @@ internal static bool IsTrue(IList objectArray) // and deal with it. IList firstElement = PSObject.Base(objectArray[0]) as IList; - if (firstElement is null) + if (firstElement == null) { return IsTrue(objectArray[0]); } @@ -1069,7 +1069,7 @@ internal static bool IsTrue(IList objectArray) /// True if the object is null. internal static bool IsNull(object obj) { - return (obj is null || obj == AutomationNull.Value); + return (obj == null || obj == AutomationNull.Value); } /// @@ -1077,7 +1077,7 @@ internal static bool IsNull(object obj) /// internal static PSObject AsPSObjectOrNull(object obj) { - if (obj is null) + if (obj == null) { return null; } @@ -1200,7 +1200,7 @@ internal static T FromObjectAs(object castObject) // First, see if we can cast the direct type PSObject wrapperObject = castObject as PSObject; - if (wrapperObject is null) + if (wrapperObject == null) { try { @@ -1478,7 +1478,7 @@ internal static object GetConverter(Type type, TypeTable backupTypeTable) typesXmlConverter = ecFromTLS.TypeTable.GetTypeConverter(type.FullName); } - if ((typesXmlConverter is null) && (backupTypeTable != null)) + if ((typesXmlConverter == null) && (backupTypeTable != null)) { s_tracer.WriteLine("Using provided TypeTable to get the type converter"); typesXmlConverter = backupTypeTable.GetTypeConverter(type.FullName); @@ -1534,7 +1534,7 @@ private static object NewConverterInstance(string assemblyQualifiedTypeName) catch (Exception e) { TargetInvocationException inner = e as TargetInvocationException; - string message = (inner is null) || (inner.InnerException is null) ? e.Message : inner.InnerException.Message; + string message = (inner == null) || (inner.InnerException == null) ? e.Message : inner.InnerException.Message; typeConversion.WriteLine("Creating an instance of type \"{0}\" caused an exception to be thrown: \"{1}\"", assemblyQualifiedTypeName, message); return null; } @@ -1853,7 +1853,7 @@ public static bool TryConvertTo(object valueToConvert, Type resultType, IFormatP { using (typeConversion.TraceScope("Converting \"{0}\" to \"{1}\".", valueToConvert, resultType)) { - if (resultType is null) + if (resultType == null) { return false; } @@ -1989,7 +1989,7 @@ private static bool IsDefinedEnum(object enumValue, Type enumType) bool isDefined; do { - if (enumValue is null) + if (enumValue == null) { isDefined = false; break; @@ -2096,7 +2096,7 @@ protected static object BaseConvertFrom(object sourceValue, Type destinationType { Diagnostics.Assert(sourceValue != null, "the type converter has a special case for null source values"); string sourceValueString = sourceValue as string; - if (sourceValueString is null) + if (sourceValueString == null) { throw new PSInvalidCastException("InvalidCastEnumFromTypeNotAString", null, ExtendedTypeSystem.InvalidCastException, @@ -2321,7 +2321,7 @@ private static ManagementObject ConvertToWMI(object valueToConvert, ManagementObject wmiObject = new ManagementObject(valueToConvertString); // ManagementObject will not throw if path does not contain valid key - if (wmiObject.SystemProperties["__CLASS"] is null) + if (wmiObject.SystemProperties["__CLASS"] == null) { string message = StringUtil.Format(ExtendedTypeSystem.InvalidWMIPath, valueToConvertString); throw new PSInvalidCastException(message); @@ -2401,7 +2401,7 @@ private static ManagementClass ConvertToWMIClass(object valueToConvert, // ManagementClass will not throw if the path specified is not // a valid class. - if (wmiClass.SystemProperties["__CLASS"] is null) + if (wmiClass.SystemProperties["__CLASS"] == null) { string message = StringUtil.Format(ExtendedTypeSystem.InvalidWMIClassPath, valueToConvertString); throw new PSInvalidCastException(message); @@ -2820,7 +2820,7 @@ private static Type ConvertStringToType(object valueToConvert, Diagnostics.Assert(valueToConvert is string, "Value to convert must be a string"); Exception exception; Type namedType = TypeResolver.ResolveType((string)valueToConvert, out exception); - if (namedType is null) + if (namedType == null) { if (exception is PSInvalidCastException) { @@ -3580,7 +3580,7 @@ private static object ConvertStringToEnum(object valueToConvert, valueToConvert.ToString(), resultType.ToString(), e.Message); } - if (result is null) + if (result == null) { typeConversion.WriteLine("Calling substring disambiguation."); try @@ -3619,7 +3619,7 @@ private static object ConvertEnumerableToEnum(object valueToConvert, else notFirst = true; string current = e.Current as string; - if (current is null) + if (current == null) { // If the object wasn't a string, then we'll try and convert it into an enum value, // then convert the enum back to a string and finally append it to the string builder to @@ -3662,7 +3662,7 @@ internal static PSMethodToDelegateConverter GetConverter(int matchIndex) if (matchIndex >= CacheSize) { return new PSMethodToDelegateConverter(matchIndex); } var result = s_converterCache[matchIndex]; - if (result is null) + if (result == null) { // If the cache entry is null, generate a new instance for the cache slot. var converter = new PSMethodToDelegateConverter(matchIndex); @@ -3858,7 +3858,7 @@ internal object Convert(object valueToConvert, { resultAsList.Add(valueToConvert); } - else if (array is null) + else if (array == null) { object convertedValue = LanguagePrimitives.ConvertTo(valueToConvert, ElementType, formatProvider); resultAsList.Add(convertedValue); @@ -3943,7 +3943,7 @@ internal object Convert(object valueToConvert, // - It's in FullLanguage but not because it's part of a parameter binding that is transitioning from ConstrainedLanguage to FullLanguage // When this is invoked from a parameter binding in transition from ConstrainedLanguage environment to FullLanguage command, we disallow // the property conversion because it's dangerous. - if (ecFromTLS is null || (ecFromTLS.LanguageMode == PSLanguageMode.FullLanguage && !ecFromTLS.LanguageModeTransitionInParameterBinding)) + if (ecFromTLS == null || (ecFromTLS.LanguageMode == PSLanguageMode.FullLanguage && !ecFromTLS.LanguageModeTransitionInParameterBinding)) { result = _constructor(); var psobject = valueToConvert as PSObject; @@ -4617,7 +4617,7 @@ internal static PSObject SetObjectProperties(object o, IDictionary properties, T Type propType; if (TypeResolver.TryResolveType(property.TypeNameOfValue, out propType)) { - if (formatProvider is null) { formatProvider = CultureInfo.InvariantCulture; } + if (formatProvider == null) { formatProvider = CultureInfo.InvariantCulture; } try { @@ -4708,7 +4708,7 @@ internal static IConversionData FigureConversion(object valueToConvert, Type res { PSObject valueAsPsObj; Type originalType; - if (valueToConvert is null || valueToConvert == AutomationNull.Value) + if (valueToConvert == null || valueToConvert == AutomationNull.Value) { valueAsPsObj = null; originalType = typeof(Null); @@ -4736,7 +4736,7 @@ internal static IConversionData FigureConversion(object valueToConvert, Type res Dbg.Assert(valueToConvert != AutomationNull.Value, "PSObject.Base converts AutomationNull.Value to null"); - if (valueToConvert is null) + if (valueToConvert == null) { originalType = typeof(Null); } @@ -4780,7 +4780,7 @@ internal static object ConvertTo(object valueToConvert, { using (typeConversion.TraceScope("Converting \"{0}\" to \"{1}\".", valueToConvert, resultType)) { - if (resultType is null) + if (resultType == null) { throw PSTraceSource.NewArgumentNullException(nameof(resultType)); } @@ -4817,7 +4817,7 @@ internal static Tuple GetInvalidCastMessages(object valueToConve return Tuple.Create(errorId, errorMsg); } - if (PSObject.Base(valueToConvert) is null) + if (PSObject.Base(valueToConvert) == null) { if (resultType.IsEnum) { @@ -5383,7 +5383,7 @@ internal static PSConverter FigureConstructorConversion(Type fromType, T typeConversion.WriteLine("Exception finding Constructor: \"{0}\".", e.Message); } - if (resultConstructor is null) + if (resultConstructor == null) { return null; } @@ -5395,7 +5395,7 @@ internal static PSConverter FigureConstructorConversion(Type fromType, T { ParameterInfo[] targetParams = resultConstructor.GetParameters(); Type targetParamType = targetParams[0].ParameterType; - bool useExplicitConversion = targetParamType.IsValueType && fromType != targetParamType && Nullable.GetUnderlyingType(targetParamType) is null; + bool useExplicitConversion = targetParamType.IsValueType && fromType != targetParamType && Nullable.GetUnderlyingType(targetParamType) == null; converter.TargetCtorLambda = CreateCtorLambdaClosure(resultConstructor, targetParamType, useExplicitConversion); } catch (Exception e) @@ -5442,7 +5442,7 @@ internal static PSConverter FigurePropertyConversion(Type fromType, Type typeConversion.WriteLine("Exception finding Constructor: \"{0}\".", e.Message); } - if (toConstructor is null && !toType.IsValueType) + if (toConstructor == null && !toType.IsValueType) { return null; } @@ -5479,10 +5479,10 @@ internal static PSConverter FigurePropertyConversion(Type fromType, Type internal static PSConverter FigureCastConversion(Type fromType, Type toType, ref ConversionRank rank) { MethodInfo castOperator = FindCastOperator("op_Implicit", toType, fromType, toType); - if (castOperator is null) + if (castOperator == null) { castOperator = FindCastOperator("op_Explicit", toType, fromType, toType); - if (castOperator is null) + if (castOperator == null) { castOperator = FindCastOperator("op_Implicit", fromType, fromType, toType) ?? FindCastOperator("op_Explicit", fromType, fromType, toType); @@ -5614,17 +5614,17 @@ internal static IConversionData FigureConversion(Type fromType, Type toType) rank = valueDependentConversion != null ? ConversionRank.Language : ConversionRank.None; converter = FigureParseConversion(fromType, toType); - if (converter is null) + if (converter == null) { converter = FigureStaticCreateMethodConversion(fromType, toType); - if (converter is null) + if (converter == null) { converter = FigureConstructorConversion(fromType, toType); rank = ConversionRank.Constructor; - if (converter is null) + if (converter == null) { converter = FigureCastConversion(fromType, toType, ref rank); - if (converter is null) + if (converter == null) { if (typeof(IConvertible).IsAssignableFrom(fromType)) { @@ -5679,7 +5679,7 @@ internal static IConversionData FigureConversion(Type fromType, Type toType) rank = ConversionRank.Parse; } - if (converter is null) + if (converter == null) { var tuple = FigureIEnumerableConstructorConversion(fromType, toType); if (tuple != null) @@ -5689,7 +5689,7 @@ internal static IConversionData FigureConversion(Type fromType, Type toType) } } - if (converter is null) + if (converter == null) { converter = FigurePropertyConversion(fromType, toType, ref rank); } @@ -5716,7 +5716,7 @@ internal static IConversionData FigureConversion(Type fromType, Type toType) rank = valueDependentRank; } - if (converter is null) + if (converter == null) { converter = ConvertNoConversion; rank = ConversionRank.None; @@ -5749,7 +5749,7 @@ private static IConversionData FigureConversionFromNull(Type toType) internal static string ObjectToTypeNameString(object o) { - if (o is null) + if (o == null) { return "null"; } diff --git a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs index f308da79615..94e07d3af0e 100644 --- a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs +++ b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs @@ -174,7 +174,7 @@ protected override T GetMember(object obj, string memberName) ManagementBaseObject mgmtObject = obj as ManagementBaseObject; - if (mgmtObject is null) + if (mgmtObject == null) { return null; } @@ -191,7 +191,7 @@ protected override T GetMember(object obj, string memberName) T returnValue = GetManagementObjectMethod(mgmtObject, memberName); // We only return a method if there is no property by the same name // to match the behavior we have in GetMembers - if (returnValue != null && property is null) + if (returnValue != null && property == null) { return returnValue; } @@ -367,7 +367,7 @@ protected override object PropertyGet(PSProperty property) protected override void PropertySet(PSProperty property, object setValue, bool convertIfPossible) { ManagementBaseObject mObj = property.baseObject as ManagementBaseObject; - if (mObj is null) + if (mObj == null) { throw new SetValueInvocationException("CannotSetNonManagementObjectMsg", null, @@ -540,7 +540,7 @@ private static ManagementClass CreateClassFrmObject(ManagementBaseObject mgmtBas ManagementClass mgmtClass = mgmtBaseObject as ManagementClass; // try to use the actual object sent to this method..otherwise construct one - if (mgmtClass is null) + if (mgmtClass == null) { mgmtClass = new ManagementClass(mgmtBaseObject.ClassPath); @@ -572,7 +572,7 @@ protected static string GetEmbeddedObjectTypeName(PropertyData pData) { string result = typeof(object).FullName; - if (pData is null) + if (pData == null) { return result; } @@ -684,7 +684,7 @@ protected static bool IsStaticMethod(MethodData mdata) try { QualifierData staticQualifier = mdata.Qualifiers["static"]; - if (staticQualifier is null) + if (staticQualifier == null) return false; bool result = false; @@ -743,7 +743,7 @@ private object AuxillaryInvokeMethod(ManagementObject obj, WMIMethodCacheEntry m // conversions. So dont convert input arguments if they are null. // We could have done this in the base adapter but the change would be // costly for other adapters which dont mind the conversion. - if ((i < arguments.Length) && (arguments[i] is null)) + if ((i < arguments.Length) && (arguments[i] == null)) { verifiedArguments[i] = null; } @@ -766,7 +766,7 @@ internal static void UpdateParameters(ManagementBaseObject parameters, SortedList parametersList) { // ManagementObject class do not populate parameters when there are none. - if (parameters is null) + if (parameters == null) return; foreach (PropertyData data in parameters.Properties) @@ -1037,7 +1037,7 @@ protected override void AddAllMethods(ManagementBaseObject wmiObject, foreach (WMIMethodCacheEntry methodEntry in table.memberCollection) { - if (members[methodEntry.Name] is null) + if (members[methodEntry.Name] == null) { tracer.WriteLine("Adding method {0}", methodEntry.Name); members.Add(new PSMethod(methodEntry.Name, this, wmiObject, methodEntry) as T); @@ -1064,7 +1064,7 @@ protected override T GetManagementObjectMethod(ManagementBaseObject wmiObject CacheTable typeTable = GetInstanceMethodTable(wmiObject, true); WMIMethodCacheEntry method = (WMIMethodCacheEntry)typeTable[methodName]; - if (method is null) + if (method == null) { return null; } @@ -1225,7 +1225,7 @@ protected override void AddAllMethods(ManagementBaseObject wmiObject, foreach (WMIMethodCacheEntry methodEntry in table.memberCollection) { - if (members[methodEntry.Name] is null) + if (members[methodEntry.Name] == null) { tracer.WriteLine("Adding method {0}", methodEntry.Name); members.Add(new PSMethod(methodEntry.Name, this, wmiObject, methodEntry) as T); @@ -1255,7 +1255,7 @@ protected override T GetManagementObjectMethod(ManagementBaseObject wmiObject typeTable = GetInstanceMethodTable(wmiObject, false); method = (WMIMethodCacheEntry)typeTable[methodName]; - if (method is null) + if (method == null) { return null; } diff --git a/src/System.Management.Automation/engine/MergedCommandParameterMetadata.cs b/src/System.Management.Automation/engine/MergedCommandParameterMetadata.cs index 6caadcc6574..9efd502badb 100644 --- a/src/System.Management.Automation/engine/MergedCommandParameterMetadata.cs +++ b/src/System.Management.Automation/engine/MergedCommandParameterMetadata.cs @@ -79,7 +79,7 @@ internal Collection AddMetadataForBinder( InternalParameterMetadata parameterMetadata, ParameterBinderAssociation binderAssociation) { - if (parameterMetadata is null) + if (parameterMetadata == null) { throw PSTraceSource.NewArgumentNullException(nameof(parameterMetadata)); } diff --git a/src/System.Management.Automation/engine/MinishellParameterBinderController.cs b/src/System.Management.Automation/engine/MinishellParameterBinderController.cs index af6d507c4b5..a85b462abb9 100644 --- a/src/System.Management.Automation/engine/MinishellParameterBinderController.cs +++ b/src/System.Management.Automation/engine/MinishellParameterBinderController.cs @@ -212,7 +212,7 @@ internal Collection BindParameters(Collection BindParameters(Collection AnalyzeScriptModule(string modulePath, ExecutionContext context, DateTime lastWriteTime) { var scriptAnalysis = ScriptAnalysis.Analyze(modulePath, context); - if (scriptAnalysis is null) + if (scriptAnalysis == null) { return null; } @@ -695,7 +695,7 @@ public void QueueSerialization() // If anything is removed, save the cache. private void Cleanup() { - Diagnostics.Assert(Environment.GetEnvironmentVariable("PSDisableModuleAnalysisCacheCleanup") is null, + Diagnostics.Assert(Environment.GetEnvironmentVariable("PSDisableModuleAnalysisCacheCleanup") == null, "Caller to check environment variable before calling"); bool removedSomething = false; @@ -1023,7 +1023,7 @@ public static AnalysisCacheData Deserialize(string filename) entries -= 1; } - if (Environment.GetEnvironmentVariable("PSDisableModuleAnalysisCacheCleanup") is null) + if (Environment.GetEnvironmentVariable("PSDisableModuleAnalysisCacheCleanup") == null) { Task.Delay(10000).ContinueWith(_ => result.Cleanup()); } diff --git a/src/System.Management.Automation/engine/Modules/GetModuleCommand.cs b/src/System.Management.Automation/engine/Modules/GetModuleCommand.cs index 4704e24eb47..bfecce83e4e 100644 --- a/src/System.Management.Automation/engine/Modules/GetModuleCommand.cs +++ b/src/System.Management.Automation/engine/Modules/GetModuleCommand.cs @@ -186,7 +186,7 @@ private PSModuleInfo ConvertCimModuleInfoToPSModuleInfo(RemoteDiscoveryHelper.Ci { bool containedErrors = false; - if (cimModule.MainManifest is null) + if (cimModule.MainManifest == null) { return GetModuleInfoForRemoteModuleWithoutManifest(cimModule); } @@ -204,7 +204,7 @@ private PSModuleInfo ConvertCimModuleInfoToPSModuleInfo(RemoteDiscoveryHelper.Ci temporaryModuleManifestPath, this, ref containedErrors); - if (mainData is null) + if (mainData == null) { return GetModuleInfoForRemoteModuleWithoutManifest(cimModule); } @@ -235,7 +235,7 @@ private PSModuleInfo ConvertCimModuleInfoToPSModuleInfo(RemoteDiscoveryHelper.Ci ref containedErrors); } - if ((moduleInfo is null) || containedErrors) + if ((moduleInfo == null) || containedErrors) { moduleInfo = GetModuleInfoForRemoteModuleWithoutManifest(cimModule); } diff --git a/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs b/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs index cbbe3186684..f6641930bf7 100644 --- a/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs +++ b/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs @@ -119,7 +119,7 @@ public string[] Function { set { - if (value is null) + if (value == null) return; _functionImportList = value; // Create the list of patterns to match at parameter bind time @@ -146,7 +146,7 @@ public string[] Cmdlet { set { - if (value is null) + if (value == null) return; _cmdletImportList = value; @@ -174,7 +174,7 @@ public string[] Variable { set { - if (value is null) + if (value == null) return; _variableExportList = value; // Create the list of patterns to match at parameter bind time @@ -201,7 +201,7 @@ public string[] Alias { set { - if (value is null) + if (value == null) return; _aliasExportList = value; @@ -296,7 +296,7 @@ public string MaximumVersion { get { - if (BaseMaximumVersion is null) + if (BaseMaximumVersion == null) return null; else return BaseMaximumVersion.ToString(); @@ -483,7 +483,7 @@ private void ImportModule_ViaLocalModuleInfo(ImportModuleOptions importModuleOpt // If we're passing in a dynamic module, then the session state will not be // null and we want to just add the module to the module table. Otherwise, it's // a module info from Get-Module -list so we need to read the actual module file. - if (module.SessionState is null) + if (module.SessionState == null) { if (File.Exists(module.Path)) { @@ -624,7 +624,7 @@ private PSModuleInfo ImportModule_LocallyViaName(ImportModuleOptions importModul // See if we can use the cached path for the file. If a version number has been specified, then // we won't look in the cache - if (this.MinimumVersion is null && this.MaximumVersion is null && this.RequiredVersion is null && PSModuleInfo.UseAppDomainLevelModuleCache && !this.BaseForce) + if (this.MinimumVersion == null && this.MaximumVersion == null && this.RequiredVersion == null && PSModuleInfo.UseAppDomainLevelModuleCache && !this.BaseForce) { // See if the name is in the appdomain-level module path name cache... cachedPath = PSModuleInfo.ResolveUsingAppDomainLevelModuleCache(name); @@ -642,7 +642,7 @@ private PSModuleInfo ImportModule_LocallyViaName(ImportModuleOptions importModul } } - if (rootedPath is null) + if (rootedPath == null) { // Check for full-qualified paths - either absolute or relative rootedPath = ResolveRootedFilePath(name, this.Context); @@ -780,7 +780,7 @@ private PSModuleInfo ImportModule_LocallyViaName(ImportModuleOptions importModul { IEnumerable modulePath = ModuleIntrinsics.GetModulePath(false, this.Context); - if (this.MinimumVersion is null && this.RequiredVersion is null && this.MaximumVersion is null) + if (this.MinimumVersion == null && this.RequiredVersion == null && this.MaximumVersion == null) { this.AddToAppDomainLevelCache = true; } @@ -1177,7 +1177,7 @@ private PSModuleInfo ImportModule_RemotelyViaPsrpSession_SinglePreimportedModule private static bool IsNonEmptyManifestField(Hashtable manifestData, string key) { object value = manifestData[key]; - if (value is null) + if (value == null) { return false; } @@ -1198,7 +1198,7 @@ private bool IsMixedModePsCimModule(RemoteDiscoveryHelper.CimModule cimModule) string temporaryModuleManifestPath = RemoteDiscoveryHelper.GetModulePath(cimModule.ModuleName, null, string.Empty, this.Context.CurrentRunspace); bool containedErrors = false; RemoteDiscoveryHelper.CimModuleFile mainManifestFile = cimModule.MainManifest; - if (mainManifestFile is null) + if (mainManifestFile == null) { return true; } @@ -1209,7 +1209,7 @@ private bool IsMixedModePsCimModule(RemoteDiscoveryHelper.CimModule cimModule) this, ref containedErrors); - if (containedErrors || manifestData is null) + if (containedErrors || manifestData == null) { return false; } @@ -1358,7 +1358,7 @@ private bool IsPs1xmlFileHelper(RemoteDiscoveryHelper.CimModuleFile cimModuleFil goodEntries = new List(); } - if (goodEntries is null) + if (goodEntries == null) { goodEntries = new List(); } @@ -1369,7 +1369,7 @@ private bool IsPs1xmlFileHelper(RemoteDiscoveryHelper.CimModuleFile cimModuleFil badEntries = new List(); } - if (badEntries is null) + if (badEntries == null) { badEntries = new List(); } @@ -1453,7 +1453,7 @@ private PSModuleInfo ImportModule_RemotelyViaCimModuleData( { try { - if (remoteCimModule.MainManifest is null) + if (remoteCimModule.MainManifest == null) { string errorMessage = string.Format( CultureInfo.InvariantCulture, @@ -1489,7 +1489,7 @@ private PSModuleInfo ImportModule_RemotelyViaCimModuleData( temporaryModuleManifestPath, out throwAwayTokens, out parseErrors); - if ((scriptBlockAst is null) || + if ((scriptBlockAst == null) || (parseErrors != null && parseErrors.Length > 0)) { throw new ParseException(parseErrors); @@ -1503,7 +1503,7 @@ private PSModuleInfo ImportModule_RemotelyViaCimModuleData( ManifestProcessingFlags.NullOnFirstError | ManifestProcessingFlags.WriteErrors, /* - don't load elements */ ref containedErrors); - if ((data is null) || containedErrors) + if ((data == null) || containedErrors) { return null; } @@ -1581,7 +1581,7 @@ private PSModuleInfo ImportModule_RemotelyViaCimModuleData( BaseGuid, ref importModuleOptions, ref containedErrors); - if (moduleInfo is null) + if (moduleInfo == null) { return null; } @@ -1685,7 +1685,7 @@ private PSModuleInfo ImportModule_RemotelyViaCimModuleData( } finally { - if (moduleInfo is null) + if (moduleInfo == null) { if (Directory.Exists(temporaryModuleDirectory)) { @@ -1901,10 +1901,10 @@ protected override void ProcessRecord() private bool IsModuleInDenyList(string[] moduleDenyList, string moduleName, ModuleSpecification moduleSpec) { - Debug.Assert(string.IsNullOrEmpty(moduleName) ^ (moduleSpec is null), "Either moduleName or moduleSpec must be specified"); + Debug.Assert(string.IsNullOrEmpty(moduleName) ^ (moduleSpec == null), "Either moduleName or moduleSpec must be specified"); // moduleName can be just a module name and it also can be a full path to psd1 from which we need to extract the module name - string exactModuleName = ModuleIntrinsics.GetModuleName(moduleSpec is null ? moduleName : moduleSpec.Name); + string exactModuleName = ModuleIntrinsics.GetModuleName(moduleSpec == null ? moduleName : moduleSpec.Name); bool match = false; foreach (var deniedModuleName in moduleDenyList) @@ -1953,10 +1953,10 @@ private List FilterModuleCollection(IEnumerable moduleCollection) private void PrepareNoClobberWinCompatModuleImport(string moduleName, ModuleSpecification moduleSpec, ref ImportModuleOptions importModuleOptions) { - Debug.Assert(string.IsNullOrEmpty(moduleName) ^ (moduleSpec is null), "Either moduleName or moduleSpec must be specified"); + Debug.Assert(string.IsNullOrEmpty(moduleName) ^ (moduleSpec == null), "Either moduleName or moduleSpec must be specified"); // moduleName can be just a module name and it also can be a full path to psd1 from which we need to extract the module name - string coreModuleToLoad = ModuleIntrinsics.GetModuleName(moduleSpec is null ? moduleName : moduleSpec.Name); + string coreModuleToLoad = ModuleIntrinsics.GetModuleName(moduleSpec == null ? moduleName : moduleSpec.Name); var isModuleToLoadEngineModule = InitialSessionState.IsEngineModule(coreModuleToLoad); string[] noClobberModuleList = PowerShellConfig.Instance.GetWindowsPowerShellCompatibilityNoClobberModuleList(); @@ -1973,7 +1973,7 @@ private void PrepareNoClobberWinCompatModuleImport(string moduleName, ModuleSpec } } - if (moduleSpec is null) + if (moduleSpec == null) { ImportModule_LocallyViaName_WithTelemetry(importModuleOptions, coreModuleToLoad); } @@ -2016,7 +2016,7 @@ internal override IList ImportModulesUsingWinCompat(IEnumerable(); } diff --git a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs index 9a9b0f5361f..f1f8aaff1f7 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs @@ -224,7 +224,7 @@ internal List MatchAll { get { - if (_matchAll is null) + if (_matchAll == null) { _matchAll = new List(); _matchAll.Add(WildcardPattern.Get("*", WildcardOptions.IgnoreCase)); @@ -535,7 +535,7 @@ internal Hashtable LoadModuleManifestData( } Hashtable data = result as Hashtable; - if (data is null) + if (data == null) { if (writingErrors) { @@ -699,7 +699,7 @@ private PSModuleInfo LoadModuleNamedInManifest(PSModuleInfo parentModule, Module } // Now load the module from the module directory first... - if (extension is null) + if (extension == null) { // No extension so we'll have to search using the extensions // @@ -846,7 +846,7 @@ private PSModuleInfo LoadModuleNamedInManifest(PSModuleInfo parentModule, Module // At this point, we haven't found an actual module, so try loading it as a // PSSnapIn and then finally as an assembly in the GAC... - if ((found == false) && (moduleSpecification.Guid is null) && (moduleSpecification.Version is null) && (moduleSpecification.RequiredVersion is null) && (moduleSpecification.MaximumVersion is null)) + if ((found == false) && (moduleSpecification.Guid == null) && (moduleSpecification.Version == null) && (moduleSpecification.RequiredVersion == null) && (moduleSpecification.MaximumVersion == null)) { // If we are in module analysis and the parent module declares non-wildcarded ExportedCmdlets, then we don't need to // actually process the binary module. @@ -945,7 +945,7 @@ internal List GetModule(string[] names, bool all, bool refresh) } // If no names were passed to this function, then this API will return list of all available modules - if (names is null || moduleNames.Count > 0) + if (names == null || moduleNames.Count > 0) { modulesToReturn.AddRange(GetModuleForNames(moduleNames, all, refresh)); } @@ -1070,7 +1070,7 @@ private IEnumerable GetModuleForNames(List names, bool all { IEnumerable modulesFound = GetModulesFromOneModulePath( names, uniquePath, all, refresh).OrderBy(m => m.Name); - allModules = allModules is null ? modulesFound : allModules.Concat(modulesFound); + allModules = allModules == null ? modulesFound : allModules.Concat(modulesFound); } catch (Exception e) when (e is IOException || e is UnauthorizedAccessException) { @@ -1109,12 +1109,12 @@ private IEnumerable GetModulesFromOneModulePath(List names foreach (string file in moduleFiles) { - if (namePatterns is null || + if (namePatterns == null || SessionStateUtilities.MatchesAnyWildcardPattern( Path.GetFileNameWithoutExtension(file), namePatterns, defaultValue: true)) { PSModuleInfo module = CreateModuleInfoForGetModule(file, refresh); - if (module is null) { continue; } + if (module == null) { continue; } if (all || !ModuleUtils.IsModuleInVersionSubdirectory(file, out Version directoryVersion) || directoryVersion == module.Version) { @@ -1231,7 +1231,7 @@ private PSModuleInfo CreateModuleInfoForGetModule(string file, bool refresh) } // return fake PSModuleInfo if can't read the file for any reason - if (moduleInfo is null) + if (moduleInfo == null) { moduleInfo = new PSModuleInfo(file, context: null, sessionState: null); moduleInfo.HadErrorsLoading = true; // Prevent analysis cache from caching a bad module. @@ -1301,7 +1301,7 @@ private PSModuleInfo CreateModuleInfoForGetModule(string file, bool refresh) // 3rd-part call out, catch-all OK // return fake PSModuleInfo if can't read the file for any reason - if (moduleInfo is null) + if (moduleInfo == null) { moduleInfo = new PSModuleInfo(file, null, null); moduleInfo.HadErrorsLoading = true; // Prevent analysis cache from caching a bad module. @@ -1382,7 +1382,7 @@ internal bool LoadModuleManifestData(ExternalScriptInfo scriptInfo, ManifestProc // load the .psd1 files into hashtables localizedData = null; data = LoadModuleManifestData(scriptInfo, ModuleManifestMembers, manifestProcessingFlags, ref containedErrors); - if (data is null) + if (data == null) { return false; } @@ -1392,7 +1392,7 @@ internal bool LoadModuleManifestData(ExternalScriptInfo scriptInfo, ManifestProc if (localizedScriptInfo != null) { localizedData = LoadModuleManifestData(localizedScriptInfo, null, manifestProcessingFlags, ref containedErrors); - if (localizedData is null) + if (localizedData == null) { return false; } @@ -1426,7 +1426,7 @@ private ErrorRecord GetErrorRecordIfUnsupportedRootCdxmlAndNestedModuleScenario( string moduleManifestPath, string rootModulePath) { - if (rootModulePath is null) + if (rootModulePath == null) { return null; } @@ -1672,7 +1672,7 @@ internal PSModuleInfo LoadModuleManifest( } else { - if (moduleVersion is null) + if (moduleVersion == null) { containedErrors = true; if (writingErrors) @@ -1945,7 +1945,7 @@ internal PSModuleInfo LoadModuleManifest( ErrorRecord error = null; PSModuleInfo module = LoadRequiredModule(fakeManifestInfo, normalizedRequiredModuleSpec, moduleManifestPath, manifestProcessingFlags, containedErrors, out error); - if (module is null && error != null) + if (module == null && error != null) { WriteError(error); return null; @@ -2210,7 +2210,7 @@ internal PSModuleInfo LoadModuleManifest( string resolvedFileName = ResolveRootedFilePath(fileName, Context) ?? fileName; foreach (var entry in Context.InitialSessionState.Types) { - if (entry.FileName is null) + if (entry.FileName == null) { continue; } @@ -2254,7 +2254,7 @@ internal PSModuleInfo LoadModuleManifest( bool isAlreadyLoaded = false; foreach (var entry in Context.InitialSessionState.Formats) { - if (entry.FileName is null) + if (entry.FileName == null) { continue; } @@ -2478,27 +2478,27 @@ internal PSModuleInfo LoadModuleManifest( // without ModuleToProcess a manifest will export everything by default // (otherwise we want to honour exports from ModuleToProcess) - if (exportedFunctions is null) + if (exportedFunctions == null) { exportedFunctions = MatchAll; } - if (exportedCmdlets is null) + if (exportedCmdlets == null) { exportedCmdlets = MatchAll; } - if (exportedVariables is null) + if (exportedVariables == null) { exportedVariables = MatchAll; } - if (exportedAliases is null) + if (exportedAliases == null) { exportedAliases = MatchAll; } - if (exportedDscResources is null) + if (exportedDscResources == null) { exportedDscResources = MatchAll; } @@ -2822,7 +2822,7 @@ internal PSModuleInfo LoadModuleManifest( // If we're in analysis, add the detected exports to this module's // exports - if (found && (ss is null)) + if (found && (ss == null)) { foreach (string detectedCmdlet in module.ExportedCmdlets.Keys) { @@ -2854,7 +2854,7 @@ internal PSModuleInfo LoadModuleManifest( // Process nested modules // If we have no session state and are loading a module, return an error - if ((ss is null) && importingModule) + if ((ss == null) && importingModule) { containedErrors = true; if (writingErrors) @@ -2941,7 +2941,7 @@ internal PSModuleInfo LoadModuleManifest( { // If we're in analysis, add the detected exports to this module's // exports - if ((ss is null) && (nestedModule != null)) + if ((ss == null) && (nestedModule != null)) { foreach (string detectedCmdlet in nestedModule.ExportedCmdlets.Keys) { @@ -3030,14 +3030,14 @@ internal PSModuleInfo LoadModuleManifest( ss: ss, options: options, manifestProcessingFlags: manifestProcessingFlags, - loadTypesFiles: (exportedTypeFiles is null || 0 == exportedTypeFiles.Count), // If types files already loaded, don't load snapin files - loadFormatFiles: (exportedFormatFiles is null || 0 == exportedFormatFiles.Count), // if format files already loaded, don't load snapin files + loadTypesFiles: (exportedTypeFiles == null || 0 == exportedTypeFiles.Count), // If types files already loaded, don't load snapin files + loadFormatFiles: (exportedFormatFiles == null || 0 == exportedFormatFiles.Count), // if format files already loaded, don't load snapin files privateData: privateData, found: out found, shortModuleName: null, manifestLanguageMode: ((manifestScriptInfo != null) ? manifestScriptInfo.DefiningLanguageMode.GetValueOrDefault() : (PSLanguageMode?)null)); - if (!found || (newManifestInfo is null)) + if (!found || (newManifestInfo == null)) { containedErrors = true; string errorMessage = StringUtil.Format(Modules.ManifestMemberNotFound, actualRootModule, @@ -3123,7 +3123,7 @@ internal PSModuleInfo LoadModuleManifest( newManifestInfo.SetGuid((Guid)manifestGuid); } - if (newManifestInfo.HelpInfoUri is null && (helpInfoUri != null)) + if (newManifestInfo.HelpInfoUri == null && (helpInfoUri != null)) { newManifestInfo.SetHelpInfoUri(helpInfoUri); } @@ -3136,13 +3136,13 @@ internal PSModuleInfo LoadModuleManifest( } } - if (newManifestInfo.RootModule is null) + if (newManifestInfo.RootModule == null) { newManifestInfo.RootModule = manifestInfo.RootModule; } // If may be the case that a script has already set the PrivateData field in the module // info object, in which case we won't overwrite it. - if (newManifestInfo.PrivateData is null) + if (newManifestInfo.PrivateData == null) { newManifestInfo.PrivateData = manifestInfo.PrivateData; } @@ -3163,7 +3163,7 @@ internal PSModuleInfo LoadModuleManifest( newManifestInfo.ExperimentalFeatures = manifestInfo.ExperimentalFeatures; // If we are in module discovery, then fix the path. - if (ss is null) + if (ss == null) { newManifestInfo.Path = manifestInfo.Path; } @@ -3183,7 +3183,7 @@ internal PSModuleInfo LoadModuleManifest( newManifestInfo.Copyright = copyright; } - if (newManifestInfo.PowerShellVersion is null) + if (newManifestInfo.PowerShellVersion == null) { newManifestInfo.PowerShellVersion = powerShellVersion; } @@ -3193,17 +3193,17 @@ internal PSModuleInfo LoadModuleManifest( newManifestInfo.PowerShellHostName = requestedHostName; } - if (newManifestInfo.PowerShellHostVersion is null) + if (newManifestInfo.PowerShellHostVersion == null) { newManifestInfo.PowerShellHostVersion = requestedHostVersion; } - if (newManifestInfo.DotNetFrameworkVersion is null) + if (newManifestInfo.DotNetFrameworkVersion == null) { newManifestInfo.DotNetFrameworkVersion = requestedDotNetFrameworkVersion; } - if (newManifestInfo.ClrVersion is null) + if (newManifestInfo.ClrVersion == null) { newManifestInfo.ClrVersion = requestedClrVersion; } @@ -3213,7 +3213,7 @@ internal PSModuleInfo LoadModuleManifest( newManifestInfo.Prefix = resolvedCommandPrefix; } - if (newManifestInfo.FileList is null || newManifestInfo.FileList.LongCount() == 0) + if (newManifestInfo.FileList == null || newManifestInfo.FileList.LongCount() == 0) { if (fileList != null) { @@ -3224,7 +3224,7 @@ internal PSModuleInfo LoadModuleManifest( } } - if (newManifestInfo.ModuleList is null || newManifestInfo.ModuleList.LongCount() == 0) + if (newManifestInfo.ModuleList == null || newManifestInfo.ModuleList.LongCount() == 0) { if (moduleList != null) { @@ -3235,7 +3235,7 @@ internal PSModuleInfo LoadModuleManifest( } } - if (newManifestInfo.CompatiblePSEditions is null || newManifestInfo.CompatiblePSEditions.LongCount() == 0) + if (newManifestInfo.CompatiblePSEditions == null || newManifestInfo.CompatiblePSEditions.LongCount() == 0) { if (compatiblePSEditions != null) { @@ -3248,7 +3248,7 @@ internal PSModuleInfo LoadModuleManifest( newManifestInfo.ProcessorArchitecture = requiredProcessorArchitecture; } - if (newManifestInfo.RequiredAssemblies is null || newManifestInfo.RequiredAssemblies.LongCount() == 0) + if (newManifestInfo.RequiredAssemblies == null || newManifestInfo.RequiredAssemblies.LongCount() == 0) { if (assemblyList != null) { @@ -3259,7 +3259,7 @@ internal PSModuleInfo LoadModuleManifest( } } - if (newManifestInfo.Scripts is null || newManifestInfo.Scripts.LongCount() == 0) + if (newManifestInfo.Scripts == null || newManifestInfo.Scripts.LongCount() == 0) { if (scriptsToProcess != null) { @@ -3270,12 +3270,12 @@ internal PSModuleInfo LoadModuleManifest( } } - if (newManifestInfo.RootModuleForManifest is null) + if (newManifestInfo.RootModuleForManifest == null) { newManifestInfo.RootModuleForManifest = manifestInfo.RootModuleForManifest; } - if (newManifestInfo.DeclaredCmdletExports is null || newManifestInfo.DeclaredCmdletExports.Count == 0) + if (newManifestInfo.DeclaredCmdletExports == null || newManifestInfo.DeclaredCmdletExports.Count == 0) { newManifestInfo.DeclaredCmdletExports = manifestInfo.DeclaredCmdletExports; } @@ -3288,7 +3288,7 @@ internal PSModuleInfo LoadModuleManifest( } } - if (newManifestInfo.DeclaredFunctionExports is null || + if (newManifestInfo.DeclaredFunctionExports == null || newManifestInfo.DeclaredFunctionExports.Count == 0) { newManifestInfo.DeclaredFunctionExports = manifestInfo.DeclaredFunctionExports; @@ -3302,7 +3302,7 @@ internal PSModuleInfo LoadModuleManifest( } } - if (newManifestInfo.DeclaredAliasExports is null || newManifestInfo.DeclaredAliasExports.Count == 0) + if (newManifestInfo.DeclaredAliasExports == null || newManifestInfo.DeclaredAliasExports.Count == 0) { newManifestInfo.DeclaredAliasExports = manifestInfo.DeclaredAliasExports; } @@ -3315,7 +3315,7 @@ internal PSModuleInfo LoadModuleManifest( } } - if (newManifestInfo.DeclaredVariableExports is null || + if (newManifestInfo.DeclaredVariableExports == null || newManifestInfo.DeclaredVariableExports.Count == 0) { newManifestInfo.DeclaredVariableExports = manifestInfo.DeclaredVariableExports; @@ -3369,7 +3369,7 @@ internal PSModuleInfo LoadModuleManifest( List fnMatchPattern = ( (manifestScriptInfo.DefiningLanguageMode == PSLanguageMode.FullLanguage) && (Context.LanguageMode != PSLanguageMode.FullLanguage) && - (exportedFunctions is null) + (exportedFunctions == null) ) ? null : MatchAll; ModuleIntrinsics.ExportModuleMembers(cmdlet: this, @@ -3505,12 +3505,12 @@ internal PSModuleInfo LoadModuleManifest( private static void PropagateExportedTypesFromNestedModulesToRootModuleScope(ImportModuleOptions options, PSModuleInfo manifestInfo) { - if (manifestInfo.NestedModules is null) + if (manifestInfo.NestedModules == null) { return; } - if (manifestInfo.SessionState is null) + if (manifestInfo.SessionState == null) { // i.e. Get-Module -ListAvailable, there is no state. return; @@ -3602,7 +3602,7 @@ private static void UpdateCommandCollection(List list, List list, List patterns) { - if (list is null) + if (list == null) { return; } @@ -3694,7 +3694,7 @@ internal static object IsModuleLoaded(ExecutionContext context, ModuleSpecificat } // If the RequiredModule is one of the Engine modules, then they could have been loaded as snapins (using InitialSessionState.CreateDefault()) - if (result is null && InitialSessionState.IsEngineModule(requiredModule.Name)) + if (result == null && InitialSessionState.IsEngineModule(requiredModule.Name)) { result = ModuleCmdletBase.GetEngineSnapIn(context, requiredModule.Name); if (result != null) @@ -3762,7 +3762,7 @@ internal static PSModuleInfo LoadRequiredModule(ExecutionContext context, bool loaded = false; object loadedModule = IsModuleLoaded(context, requiredModuleSpecification, out loadFailureReason, out loaded); - if (loadedModule is null) + if (loadedModule == null) { // Load the module PSModuleInfo requiredModuleInfo = null; @@ -3831,7 +3831,7 @@ internal static PSModuleInfo LoadRequiredModule(ExecutionContext context, case ModuleMatchFailure.MinimumVersion: // If both max and min versions were specified, use a different error message - if (requiredModuleSpecification.MaximumVersion is null) + if (requiredModuleSpecification.MaximumVersion == null) { message = StringUtil.Format( Modules.RequiredModuleNotLoadedWrongVersion, @@ -3852,7 +3852,7 @@ internal static PSModuleInfo LoadRequiredModule(ExecutionContext context, case ModuleMatchFailure.MaximumVersion: // If both max and min versions were specified, use a different error message - if (requiredModuleSpecification.Version is null) + if (requiredModuleSpecification.Version == null) { message = StringUtil.Format( Modules.RequiredModuleNotLoadedWrongMaximumVersion, @@ -3986,7 +3986,7 @@ private static PSModuleInfo ImportRequiredModule(ExecutionContext context, Modul Dbg.Assert(r is PSModuleInfo, "The returned value should be PSModuleInfo"); result = r as PSModuleInfo; - if (result is null) + if (result == null) { string message = StringUtil.Format(Modules.RequiredModuleNotFound, moduleNameToCheckAgainst); if (!string.IsNullOrEmpty(manifestPath)) @@ -4087,7 +4087,7 @@ internal static Collection GetModuleIfAvailable(ModuleSpecificatio Collection result = new Collection(); Collection tempResult = null; System.Management.Automation.PowerShell powerShell = null; - if (rsToUse is null) + if (rsToUse == null) { powerShell = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace); } @@ -4124,7 +4124,7 @@ internal static Collection GetModuleIfAvailable(ModuleSpecificatio guid: requiredModule.Guid, requiredVersion: requiredModule.RequiredVersion, minimumVersion: requiredModule.Version, - maximumVersion: requiredModule.MaximumVersion is null ? null : GetMaximumVersion(requiredModule.MaximumVersion))) + maximumVersion: requiredModule.MaximumVersion == null ? null : GetMaximumVersion(requiredModule.MaximumVersion))) { result.Add(module); } @@ -4136,7 +4136,7 @@ internal static Collection GetModuleIfAvailable(ModuleSpecificatio private static bool HasRequiredModulesCyclicReference(ModuleSpecification currentModuleSpecification, List requiredModules, IEnumerable moduleInfoList, Dictionary> nonCyclicRequiredModules, out ErrorRecord error) { error = null; - if (requiredModules is null || requiredModules.Count == 0 || currentModuleSpecification is null) + if (requiredModules == null || requiredModules.Count == 0 || currentModuleSpecification == null) { return false; } @@ -4507,7 +4507,7 @@ internal bool GetScalarFromData( out T result) { object value = data[key]; - if ((value is null) || (value is string && string.IsNullOrEmpty((string)value))) + if ((value == null) || (value is string && string.IsNullOrEmpty((string)value))) { result = default(T); return true; @@ -4705,7 +4705,7 @@ internal static string ResolveRootedFilePath(string filePath, ExecutionContext c } // Make sure at least one file was found... - if (filePaths is null || filePaths.Count < 1) + if (filePaths == null || filePaths.Count < 1) { return null; } @@ -4741,7 +4741,7 @@ internal static string GetResolvedPath(string filePath, ExecutionContext context return null; } // Make sure that the path is in the file system - that's all we can handle currently... - if ((provider is null) || !provider.NameEquals(context.ProviderNames.FileSystem)) + if ((provider == null) || !provider.NameEquals(context.ProviderNames.FileSystem)) { return null; } @@ -4753,7 +4753,7 @@ internal static string GetResolvedPath(string filePath, ExecutionContext context } // Make sure at least one file was found... - if (filePaths is null || filePaths.Count < 1 || filePaths.Count > 1) + if (filePaths == null || filePaths.Count < 1 || filePaths.Count > 1) { return null; } @@ -4778,7 +4778,7 @@ internal static Collection GetResolvedPathCollection(string filePath, Ex return null; } // Make sure that the path is in the file system - that's all we can handle currently... - if ((provider is null) || !provider.NameEquals(context.ProviderNames.FileSystem)) + if ((provider == null) || !provider.NameEquals(context.ProviderNames.FileSystem)) { return null; } @@ -4790,7 +4790,7 @@ internal static Collection GetResolvedPathCollection(string filePath, Ex } // Make sure at least one file was found... - if (filePaths is null || filePaths.Count < 1) + if (filePaths == null || filePaths.Count < 1) { return null; } @@ -4820,7 +4820,7 @@ internal static PSSession CreateWindowsPowerShellCompatResources() lock (s_WindowsPowerShellCompatSyncObject) { compatSession = GetWindowsPowerShellCompatRemotingSession(); - if (compatSession is null) + if (compatSession == null) { var commandInfo = new CmdletInfo("New-PSSession", typeof(NewPSSessionCommand)); using var ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace); @@ -4984,7 +4984,7 @@ internal void RemoveModule(PSModuleInfo module, string moduleNameInRemoveModuleC // If the entry's module name matches, then remove it from the list... for (int i = matches.Count - 1; i >= 0; i--) { - if (matches[i].Module is null) + if (matches[i].Module == null) { continue; } @@ -5076,7 +5076,7 @@ internal void RemoveModule(PSModuleInfo module, string moduleNameInRemoveModuleC // because the names of the functions might have been changed by the -Prefix parameter of Import-Module) foreach ((var _, FunctionInfo functionInfo) in ss.GetFunctionTable()) { - if (functionInfo.Module is null) + if (functionInfo.Module == null) { continue; } @@ -5120,7 +5120,7 @@ internal void RemoveModule(PSModuleInfo module, string moduleNameInRemoveModuleC foreach (KeyValuePair entry in ss.GetAliasTable()) { AliasInfo ai = entry.Value; - if (ai.Module is null) + if (ai.Module == null) { continue; } @@ -5195,7 +5195,7 @@ private bool ShouldModuleBeRemoved(PSModuleInfo module, string moduleNameInRemov isTopLevelModule = true; // This check makes sure that this module is removed only when we do a Remove-Module of this module // If this module is a nested module of some other module but is also imported as a top level module, then we should not be removing it. - if (moduleNameInRemoveModuleCmdlet is null || module.Name.Equals(moduleNameInRemoveModuleCmdlet, StringComparison.OrdinalIgnoreCase)) + if (moduleNameInRemoveModuleCmdlet == null || module.Name.Equals(moduleNameInRemoveModuleCmdlet, StringComparison.OrdinalIgnoreCase)) { return true; } @@ -5360,7 +5360,7 @@ internal PSModuleInfo LoadUsingExtensions(PSModuleInfo parentModule, // Get the resolved file name fileName = GetResolvedPath(fileName, Context); - if (fileName is null) + if (fileName == null) continue; // If we've found ourselves, then skip and move on to the next extension. @@ -5995,7 +5995,7 @@ internal PSModuleInfo LoadModule(PSModuleInfo parentModule, string fileName, str // If using AppDomain-level module path caching, add this module to the cache. This is only done for // the modules loaded with without version info or other qualifiers. - if (PSModuleInfo.UseAppDomainLevelModuleCache && module != null && moduleBase is null && this.AddToAppDomainLevelCache) + if (PSModuleInfo.UseAppDomainLevelModuleCache && module != null && moduleBase == null && this.AddToAppDomainLevelCache) { // Cache using the actual name specified by the user rather than the module basename PSModuleInfo.AddToAppDomainLevelModuleCache(module.Name, fileName, this.BaseForce); @@ -6009,7 +6009,7 @@ private void CheckForDisallowedDotSourcing( ExternalScriptInfo scriptInfo, ImportModuleOptions options) { - if (ss is null || ss.Internal is null) + if (ss == null || ss.Internal == null) { return; } // A manifest with explicit function export is detected through a shared session state or the nested module options, because nested @@ -6110,7 +6110,7 @@ private static BinaryAnalysisResult GetCmdletsFromBinaryModuleImplementation(str } BinaryAnalysisResult analysisResult = PowerShellModuleAssemblyAnalyzer.AnalyzeModuleAssembly(path, out assemblyVersion); - if (analysisResult is null && Path.IsPathRooted(path)) + if (analysisResult == null && Path.IsPathRooted(path)) { // If we couldn't load it from a file, try finding it in our probing path string assemblyFilename = Path.GetFileName(path); @@ -6149,7 +6149,7 @@ private BinaryAnalysisResult GetCmdletsFromBinaryModuleImplementation(string pat bool cleanupModuleAnalysisAppDomain = false; AppDomain tempDomain = Context.AppDomainForModuleAnalysis; - if (tempDomain is null) + if (tempDomain == null) { cleanupModuleAnalysisAppDomain = Context.TakeResponsibilityForModuleAnalysisAppDomain(); tempDomain = Context.AppDomainForModuleAnalysis = AppDomain.CreateDomain("ReflectionDomain"); @@ -6341,7 +6341,7 @@ private PSModuleInfo AnalyzeScriptFile(string filename, bool force, ExecutionCon // We don't have this cached, analyze the file. var scriptAnalysis = ScriptAnalysis.Analyze(filename, context); - if (scriptAnalysis is null) + if (scriptAnalysis == null) { return module; } @@ -6423,7 +6423,7 @@ private PSModuleInfo AnalyzeScriptFile(string filename, bool force, ExecutionCon processedModules.AddRange(GetModule(new string[] { moduleToProcess }, false, true)); } - if ((processedModules is null) || (processedModules.Count == 0)) + if ((processedModules == null) || (processedModules.Count == 0)) { continue; } @@ -6546,7 +6546,7 @@ internal PSModuleInfo LoadBinaryModule(PSModuleInfo parentModule, bool trySnapIn { PSModuleInfo module = null; - if (string.IsNullOrEmpty(moduleName) && string.IsNullOrEmpty(fileName) && assemblyToLoad is null) + if (string.IsNullOrEmpty(moduleName) && string.IsNullOrEmpty(fileName) && assemblyToLoad == null) throw PSTraceSource.NewArgumentNullException("moduleName,fileName,assemblyToLoad"); // Load the dll and process any cmdlets it might contain... @@ -6672,7 +6672,7 @@ internal PSModuleInfo LoadBinaryModule(PSModuleInfo parentModule, bool trySnapIn { assembly = Context.AddAssembly(moduleName, fileName, out error); - if (assembly is null) + if (assembly == null) { if (error != null) throw error; @@ -6704,7 +6704,7 @@ internal PSModuleInfo LoadBinaryModule(PSModuleInfo parentModule, bool trySnapIn { string binaryPath = fileName; modulePath = fileName; - if (binaryPath is null) + if (binaryPath == null) { binaryPath = System.IO.Path.Combine(moduleBase, moduleName); } @@ -6783,7 +6783,7 @@ internal PSModuleInfo LoadBinaryModule(PSModuleInfo parentModule, bool trySnapIn // this module in which case we add the exported cmdlets to the existing list. SessionStateCmdletEntry cmdletEntry = commandEntry as SessionStateCmdletEntry; SessionStateAliasEntry aliasEntry = null; - if (cmdletEntry is null) + if (cmdletEntry == null) { aliasEntry = commandEntry as SessionStateAliasEntry; } @@ -6844,7 +6844,7 @@ internal PSModuleInfo LoadBinaryModule(PSModuleInfo parentModule, bool trySnapIn for (int i = commands.Count - 1; i >= 0; i--) { SessionStateCommandEntry e = commands[i]; - if (e is null) + if (e == null) continue; string name = e.Name; if (string.IsNullOrEmpty(name)) @@ -7147,7 +7147,7 @@ internal static void ImportModuleMembers( List aliasPatterns, ImportModuleOptions options) { - if (sourceModule is null) + if (sourceModule == null) throw PSTraceSource.NewArgumentNullException(nameof(sourceModule)); bool isImportModulePrivate = cmdlet.CommandInfo.Visibility == SessionStateEntryVisibility.Private || @@ -7184,8 +7184,8 @@ internal static void ImportModuleMembers( } // True if none of -function, -cmdlet, -variable or -alias are specified - bool noPatternsSpecified = functionPatterns is null && - variablePatterns is null && aliasPatterns is null && cmdletPatterns is null; + bool noPatternsSpecified = functionPatterns == null && + variablePatterns == null && aliasPatterns == null && cmdletPatterns == null; // mapping from original to prefixed names (prefixed using -Prefix parameter of the cmdlet) // used to modify AliasInfo.Definition if necessary @@ -7513,7 +7513,7 @@ private static void ValidateCommandName(ModuleCmdletBase cmdlet, } string[] alternates = Verbs.SuggestedAlternates(verb); - if (alternates is null) + if (alternates == null) { message = StringUtil.Format(Modules.ImportingNonStandardVerbVerbose, commandName, moduleName); cmdlet.WriteVerbose(message); diff --git a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs index 7365cb3546d..b20e11e4745 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs @@ -150,7 +150,7 @@ private PSModuleInfo CreateModuleImplementation(string name, string path, object // script scope for the ss. // Allocate the session state instance for this module. - if (ss is null) + if (ss == null) { ss = new SessionState(_context, true, true); } @@ -196,7 +196,7 @@ private PSModuleInfo CreateModuleImplementation(string name, string path, object } } - if (sb is null) + if (sb == null) throw PSTraceSource.NewInvalidOperationException(); sb.SessionStateInternal = ss.Internal; @@ -213,7 +213,7 @@ private PSModuleInfo CreateModuleImplementation(string name, string path, object } // The variables set in the interpreted case get set by InvokeWithPipe in the compiled case. - Diagnostics.Assert(_context.SessionState.Internal.CurrentScope.LocalsTuple is null, + Diagnostics.Assert(_context.SessionState.Internal.CurrentScope.LocalsTuple == null, "No locals tuple should have been created yet."); List resultList = new List(); @@ -279,7 +279,7 @@ internal List GetModules(string[] patterns, bool all) internal List GetExactMatchModules(string moduleName, bool all, bool exactMatch) { - if (moduleName is null) { moduleName = string.Empty; } + if (moduleName == null) { moduleName = string.Empty; } return GetModuleCore(new string[] { moduleName }, all, exactMatch); } @@ -296,7 +296,7 @@ private List GetModuleCore(string[] patterns, bool all, bool exact } else { - if (patterns is null) + if (patterns == null) { patterns = new string[] { "*" }; } @@ -449,7 +449,7 @@ internal static bool IsModuleMatchingModuleSpec( ModuleSpecification moduleSpec, bool skipNameCheck = false) { - if (moduleSpec is null) + if (moduleSpec == null) { matchFailureReason = ModuleMatchFailure.NullModuleSpecification; return false; @@ -462,7 +462,7 @@ internal static bool IsModuleMatchingModuleSpec( moduleSpec.Guid, moduleSpec.RequiredVersion, moduleSpec.Version, - moduleSpec.MaximumVersion is null ? null : ModuleCmdletBase.GetMaximumVersion(moduleSpec.MaximumVersion)); + moduleSpec.MaximumVersion == null ? null : ModuleCmdletBase.GetMaximumVersion(moduleSpec.MaximumVersion)); } /// @@ -516,7 +516,7 @@ internal static bool IsModuleMatchingConstraints( Version maximumVersion) { // Define that a null module does not meet any constraints - if (moduleInfo is null) + if (moduleInfo == null) { matchFailureReason = ModuleMatchFailure.NullModule; return false; @@ -697,7 +697,7 @@ internal static bool MatchesModulePath(string modulePath, string requiredPath) { Dbg.Assert(requiredPath != null, $"Caller to verify that {nameof(requiredPath)} is not null"); - if (modulePath is null) + if (modulePath == null) { return false; } @@ -762,7 +762,7 @@ internal static string NormalizeModuleName( string basePath, ExecutionContext executionContext) { - if (moduleName is null) + if (moduleName == null) { return null; } @@ -937,7 +937,7 @@ internal static bool IsPowerShellModuleExtension(string extension) /// The module name. internal static string GetModuleName(string path) { - string fileName = path is null ? string.Empty : Path.GetFileName(path); + string fileName = path == null ? string.Empty : Path.GetFileName(path); string ext; if (fileName.EndsWith(StringLiterals.PowerShellNgenAssemblyExtension, StringComparison.OrdinalIgnoreCase)) { @@ -1177,7 +1177,7 @@ public static string GetModulePath(string currentProcessModulePath, string hklmM string psHomeModulePath = GetPSHomeModulePath(); // $PSHome\Modules location // If the variable isn't set, then set it to the default value - if (currentProcessModulePath is null) // EVT.Process does Not exist - really corner case + if (currentProcessModulePath == null) // EVT.Process does Not exist - really corner case { // Handle the default case... if (string.IsNullOrEmpty(hkcuUserModulePath)) // EVT.User does Not exist -> set to location @@ -1243,7 +1243,7 @@ internal static string GetWindowsPowerShellModulePath() { string currentModulePath = GetModulePath(); - if (currentModulePath is null) + if (currentModulePath == null) { return null; } @@ -1429,7 +1429,7 @@ private static string ProcessOneModulePath(ExecutionContext context, string envP internal static void RemoveNestedModuleFunctions(PSModuleInfo module) { var input = module.SessionState?.Internal?.ExportedFunctions; - if ((input is null) || (input.Count == 0)) + if ((input == null) || (input.Count == 0)) { return; } List output = new List(input.Count); @@ -1543,7 +1543,7 @@ internal static void ExportModuleMembers( foreach (CmdletInfo element in copy) { - if (doNotExportCmdlets is null + if (doNotExportCmdlets == null || !doNotExportCmdlets.Exists(cmdletName => string.Equals(element.FullName, cmdletName, StringComparison.OrdinalIgnoreCase))) { if (SessionStateUtilities.MatchesAnyWildcardPattern(element.Name, cmdletPatterns, false)) @@ -1565,7 +1565,7 @@ internal static void ExportModuleMembers( foreach (KeyValuePair> entry in ft) { CmdletInfo cmdletToImport = entry.Value[0]; - if (doNotExportCmdlets is null + if (doNotExportCmdlets == null || !doNotExportCmdlets.Exists(cmdletName => string.Equals(cmdletToImport.FullName, cmdletName, StringComparison.OrdinalIgnoreCase))) { if (SessionStateUtilities.MatchesAnyWildcardPattern(entry.Key, cmdletPatterns, false)) diff --git a/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs b/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs index e03a8f8de01..5333e364502 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs @@ -67,7 +67,7 @@ public ModuleSpecification(string moduleName) /// The module specification as a hashtable. public ModuleSpecification(Hashtable moduleSpecification) { - if (moduleSpecification is null) + if (moduleSpecification == null) { throw new ArgumentNullException(nameof(moduleSpecification)); } @@ -149,7 +149,7 @@ internal static Exception ModuleSpecificationInitHelper(ModuleSpecification modu return new MissingMemberException(message); } - if (moduleSpecification.RequiredVersion is null && moduleSpecification.Version is null && moduleSpecification.MaximumVersion is null) + if (moduleSpecification.RequiredVersion == null && moduleSpecification.Version == null && moduleSpecification.MaximumVersion == null) { message = StringUtil.Format(Modules.RequiredModuleMissingModuleVersion); return new MissingMemberException(message); @@ -172,7 +172,7 @@ internal static Exception ModuleSpecificationInitHelper(ModuleSpecification modu internal ModuleSpecification(PSModuleInfo moduleInfo) { - if (moduleInfo is null) + if (moduleInfo == null) { throw new ArgumentNullException(nameof(moduleInfo)); } @@ -190,7 +190,7 @@ internal ModuleSpecification(PSModuleInfo moduleInfo) /// public override string ToString() { - if (Guid is null && Version is null && RequiredVersion is null && MaximumVersion is null) + if (Guid == null && Version == null && RequiredVersion == null && MaximumVersion == null) { return Name; } @@ -336,7 +336,7 @@ public bool Equals(ModuleSpecification x, ModuleSpecification y) /// A hashcode that is always the same for any module specification with the same properties. public int GetHashCode(ModuleSpecification obj) { - if (obj is null) + if (obj == null) { return 0; } diff --git a/src/System.Management.Automation/engine/Modules/ModuleUtils.cs b/src/System.Management.Automation/engine/Modules/ModuleUtils.cs index 4432b4e870f..b825a54fbab 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleUtils.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleUtils.cs @@ -490,7 +490,7 @@ internal static IEnumerable GetMatchingCommands(string pattern, Exe IDictionary exportedCommands = AnalysisCache.GetExportedCommands(modulePath, testOnly: false, context); - if (exportedCommands is null) { continue; } + if (exportedCommands == null) { continue; } tempModuleInfo = new PSModuleInfo(moduleShortName, modulePath, sessionState: null, context: null); if (InitialSessionState.IsEngineModule(moduleShortName)) diff --git a/src/System.Management.Automation/engine/Modules/NewModuleCommand.cs b/src/System.Management.Automation/engine/Modules/NewModuleCommand.cs index a2e23348e46..f61d3bb39bb 100644 --- a/src/System.Management.Automation/engine/Modules/NewModuleCommand.cs +++ b/src/System.Management.Automation/engine/Modules/NewModuleCommand.cs @@ -62,7 +62,7 @@ public string[] Function { set { - if (value is null) + if (value == null) return; _functionImportList = value; @@ -90,7 +90,7 @@ public string[] Cmdlet { set { - if (value is null) + if (value == null) return; _cmdletImportList = value; diff --git a/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs b/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs index 7c3c082fe31..8ee68283ec6 100644 --- a/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs +++ b/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs @@ -536,7 +536,7 @@ public string DefaultCommandPrefix /// The quoted string. private string QuoteName(string name) { - if (name is null) + if (name == null) return "''"; return ("'" + name.Replace("'", "''") + "'"); } @@ -548,7 +548,7 @@ private string QuoteName(string name) /// The quoted AbsoluteUri. private string QuoteName(Uri name) { - if (name is null) + if (name == null) return "''"; return QuoteName(name.AbsoluteUri); } @@ -560,7 +560,7 @@ private string QuoteName(Uri name) /// The quoted Version string. private string QuoteName(Version name) { - if (name is null) + if (name == null) return "''"; return QuoteName(name.ToString()); } @@ -574,7 +574,7 @@ private string QuoteName(Version name) /// The quoted list. private string QuoteNames(IEnumerable names, StreamWriter streamWriter) { - if (names is null) + if (names == null) return "@()"; StringBuilder result = new StringBuilder(); @@ -657,7 +657,7 @@ private string QuoteModules(IEnumerable moduleSpecs, StreamWriter streamWriter) bool firstModule = true; foreach (object spec in moduleSpecs) { - if (spec is null) + if (spec == null) { continue; } @@ -677,7 +677,7 @@ private string QuoteModules(IEnumerable moduleSpecs, StreamWriter streamWriter) firstModule = false; - if ((moduleSpecification.Guid is null) && (moduleSpecification.Version is null) && (moduleSpecification.MaximumVersion is null) && (moduleSpecification.RequiredVersion is null)) + if ((moduleSpecification.Guid == null) && (moduleSpecification.Version == null) && (moduleSpecification.MaximumVersion == null) && (moduleSpecification.RequiredVersion == null)) { result.Append(QuoteName(moduleSpecification.Name)); } @@ -809,7 +809,7 @@ private string QuoteFiles(IEnumerable names, StreamWriter streamWriter) // { // } - // if (fileDir is null + // if (fileDir == null // || !fileDir.StartsWith(basePathDir, StringComparison.OrdinalIgnoreCase)) // { // WriteWarning(StringUtil.Format(Modules.IncludedItemPathFallsOutsideSaveTree, name, @@ -846,7 +846,7 @@ private List TryResolveFilePath(string filePath) sessionState.Path.GetResolvedProviderPathFromPSPath(filePath, out provider); // If the name doesn't resolve to something we can use, just return the unresolved name... - if (!provider.NameEquals(this.Context.ProviderNames.FileSystem) || filePaths is null || filePaths.Count < 1) + if (!provider.NameEquals(this.Context.ProviderNames.FileSystem) || filePaths == null || filePaths.Count < 1) { result.Add(filePath); return result; @@ -949,11 +949,11 @@ protected override void EndProcessing() // wildcards for exported commands that weren't specified on the command line. if (_rootModule != null || _nestedModules != null || _requiredModules != null) { - if (_exportedFunctions is null) + if (_exportedFunctions == null) _exportedFunctions = new string[] { "*" }; - if (_exportedAliases is null) + if (_exportedAliases == null) _exportedAliases = new string[] { "*" }; - if (_exportedCmdlets is null) + if (_exportedCmdlets == null) _exportedCmdlets = new string[] { "*" }; } @@ -1031,7 +1031,7 @@ protected override void EndProcessing() result.Append(streamWriter.NewLine); result.Append(streamWriter.NewLine); - if (_rootModule is null) + if (_rootModule == null) _rootModule = string.Empty; BuildModuleManifest(result, nameof(RootModule), Modules.RootModule, !string.IsNullOrEmpty(_rootModule), () => QuoteName(_rootModule), streamWriter); @@ -1150,9 +1150,9 @@ private void BuildModuleManifest(StringBuilder result, string key, string keyDes private void BuildPrivateDataInModuleManifest(StringBuilder result, StreamWriter streamWriter) { var privateDataHashTable = PrivateData as Hashtable; - bool specifiedPSDataProperties = !(Tags is null && ReleaseNotes is null && ProjectUri is null && IconUri is null && LicenseUri is null); + bool specifiedPSDataProperties = !(Tags == null && ReleaseNotes == null && ProjectUri == null && IconUri == null && LicenseUri == null); - if (_privateData != null && privateDataHashTable is null) + if (_privateData != null && privateDataHashTable == null) { if (specifiedPSDataProperties) { diff --git a/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs b/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs index 92118527fac..033382a565b 100644 --- a/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs +++ b/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs @@ -107,7 +107,7 @@ public PSModuleInfo(bool linkToGlobal) /// internal PSModuleInfo(ExecutionContext context, bool linkToGlobal) { - if (context is null) + if (context == null) throw new InvalidOperationException("PSModuleInfo"); SetDefaultDynamicNameAndPath(this); @@ -128,7 +128,7 @@ internal PSModuleInfo(ExecutionContext context, bool linkToGlobal) /// The scriptblock to use to initialize the module. public PSModuleInfo(ScriptBlock scriptBlock) { - if (scriptBlock is null) + if (scriptBlock == null) { throw PSTraceSource.NewArgumentException(nameof(scriptBlock)); } @@ -136,7 +136,7 @@ public PSModuleInfo(ScriptBlock scriptBlock) // Get the ExecutionContext from the thread. var context = LocalPipeline.GetExecutionContextFromTLS(); - if (context is null) + if (context == null) throw new InvalidOperationException("PSModuleInfo"); SetDefaultDynamicNameAndPath(this); @@ -249,7 +249,7 @@ internal void SetName(string name) /// public string Definition { - get { return _definitionExtent is null ? string.Empty : _definitionExtent.Text; } + get { return _definitionExtent == null ? string.Empty : _definitionExtent.Text; } } internal IScriptExtent _definitionExtent; @@ -598,10 +598,10 @@ public ReadOnlyDictionary GetExportedTypeDefinitions( // because we may not have NestedModules list populated on the first call. // TODO(sevoroby): it may harm perf a little bit. Can we sort it out? - if (_exportedTypeDefinitionsNoNested is null) + if (_exportedTypeDefinitionsNoNested == null) { string rootedPath = null; - if (RootModule is null) + if (RootModule == null) { if (this.Path != null) { @@ -652,7 +652,7 @@ public ReadOnlyDictionary GetExportedTypeDefinitions( /// internal void CreateExportedTypeDefinitions(ScriptBlockAst moduleContentScriptBlockAsts) { - if (moduleContentScriptBlockAsts is null) + if (moduleContentScriptBlockAsts == null) { this._exportedTypeDefinitionsNoNested = s_emptyTypeDefinitionDictionary; } @@ -1117,7 +1117,7 @@ public Dictionary ExportedVariables // If there is no session state object associated with this list, // just return a null list of exports. This will be true if the // module is a compiled module. - if (SessionState is null || SessionState.Internal.ExportedVariables is null) + if (SessionState == null || SessionState.Internal.ExportedVariables == null) { return exportedVariables; } @@ -1159,7 +1159,7 @@ public Dictionary ExportedAliases else { // There is no session state object associated with this list. - if (SessionState is null) + if (SessionState == null) { // Check if we detected any if (DetectedAliasExports.Count > 0) @@ -1239,7 +1239,7 @@ public ScriptBlock NewBoundScriptBlock(ScriptBlock scriptBlockToBind) internal ScriptBlock NewBoundScriptBlock(ScriptBlock scriptBlockToBind, ExecutionContext context) { - if (SessionState is null || context is null) + if (SessionState == null || context == null) { throw PSTraceSource.NewInvalidOperationException(Modules.InvalidOperationOnBinaryModule); } @@ -1274,7 +1274,7 @@ internal ScriptBlock NewBoundScriptBlock(ScriptBlock scriptBlockToBind, Executio /// The result of the invocation. public object Invoke(ScriptBlock sb, params object[] args) { - if (sb is null) + if (sb == null) return null; // Temporarily set the scriptblocks session state to be the @@ -1313,7 +1313,7 @@ public PSVariable GetVariableFromCallersModule(string variableName) foreach (var sf in context.Debugger.GetCallStack()) { var frameModule = sf.InvocationInfo.MyCommand.Module; - if (frameModule is null) + if (frameModule == null) { break; } @@ -1340,7 +1340,7 @@ public PSVariable GetVariableFromCallersModule(string variableName) /// internal void CaptureLocals() { - if (SessionState is null) + if (SessionState == null) { throw PSTraceSource.NewInvalidOperationException(Modules.InvalidOperationOnBinaryModule); } @@ -1381,7 +1381,7 @@ internal void CaptureLocals() /// A custom object. public PSObject AsCustomObject() { - if (SessionState is null) + if (SessionState == null) { throw PSTraceSource.NewInvalidOperationException(Modules.InvalidOperationOnBinaryModule); } diff --git a/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs b/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs index 8a2cc5a03bb..015b2bb72d2 100644 --- a/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs +++ b/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs @@ -34,7 +34,7 @@ private static Collection RehydrateHashtableKeys(PSObject pso, string pr var rehydrationFlags = DeserializingTypeConverter.RehydrationFlags.NullValueOk | DeserializingTypeConverter.RehydrationFlags.MissingPropertyOk; Hashtable hashtable = DeserializingTypeConverter.GetPropertyValue(pso, propertyName, rehydrationFlags); - if (hashtable is null) + if (hashtable == null) { return new Collection(); } @@ -505,7 +505,7 @@ internal static IEnumerable InvokePowerShell( private static T GetPropertyValue(CimInstance cimInstance, string propertyName, T defaultValue) { CimProperty cimProperty = cimInstance.CimInstanceProperties[propertyName]; - if (cimProperty is null) + if (cimProperty == null) { return defaultValue; } @@ -602,7 +602,7 @@ public string FileData { get { - if (_fileData is null) + if (_fileData == null) { using (var ms = new MemoryStream(this.RawFileData)) using (var sr = new StreamReader(ms, detectEncodingFromByteOrderMarks: true)) @@ -783,7 +783,7 @@ private static IEnumerable GetCimModules( options.ResourceUri = resourceUri; } - if (string.IsNullOrEmpty(cimNamespace) && (resourceUri is null)) + if (string.IsNullOrEmpty(cimNamespace) && (resourceUri == null)) { cimNamespace = DiscoveryProviderNamespace; } @@ -899,9 +899,9 @@ private static Exception GetExceptionWhenAuthenticationRequiresCredential(string private static CimCredential GetCimCredentials(string authentication, PSCredential credential) { - if (authentication is null || (authentication.Equals("Default", StringComparison.OrdinalIgnoreCase))) + if (authentication == null || (authentication.Equals("Default", StringComparison.OrdinalIgnoreCase))) { - if (credential is null) + if (credential == null) { return null; } @@ -913,7 +913,7 @@ private static CimCredential GetCimCredentials(string authentication, PSCredenti if (authentication.Equals("Basic", StringComparison.OrdinalIgnoreCase)) { - if (credential is null) + if (credential == null) { throw GetExceptionWhenAuthenticationRequiresCredential(authentication); } @@ -925,7 +925,7 @@ private static CimCredential GetCimCredentials(string authentication, PSCredenti if (authentication.Equals("Negotiate", StringComparison.OrdinalIgnoreCase)) { - if (credential is null) + if (credential == null) { return new CimCredential(ImpersonatedAuthenticationMechanism.Negotiate); } @@ -937,7 +937,7 @@ private static CimCredential GetCimCredentials(string authentication, PSCredenti if (authentication.Equals("CredSSP", StringComparison.OrdinalIgnoreCase)) { - if (credential is null) + if (credential == null) { throw GetExceptionWhenAuthenticationRequiresCredential(authentication); } @@ -949,7 +949,7 @@ private static CimCredential GetCimCredentials(string authentication, PSCredenti if (authentication.Equals("Digest", StringComparison.OrdinalIgnoreCase)) { - if (credential is null) + if (credential == null) { throw GetExceptionWhenAuthenticationRequiresCredential(authentication); } @@ -961,7 +961,7 @@ private static CimCredential GetCimCredentials(string authentication, PSCredenti if (authentication.Equals("Kerberos", StringComparison.OrdinalIgnoreCase)) { - if (credential is null) + if (credential == null) { return new CimCredential(ImpersonatedAuthenticationMechanism.Kerberos); } @@ -1010,7 +1010,7 @@ internal static Hashtable ConvertCimModuleFileToManifestHashtable(RemoteDiscover System.Management.Automation.Language.Token[] throwAwayTokens; ParseError[] parseErrors; scriptBlockAst = System.Management.Automation.Language.Parser.ParseInput(cimModuleFile.FileData, temporaryModuleManifestPath, out throwAwayTokens, out parseErrors); - if ((scriptBlockAst is null) || (parseErrors != null && parseErrors.Length > 0)) + if ((scriptBlockAst == null) || (parseErrors != null && parseErrors.Length > 0)) { containedErrors = true; } diff --git a/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs b/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs index 74e608d8e7d..6ec64a4cf0f 100644 --- a/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs +++ b/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs @@ -212,7 +212,7 @@ public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst fun if (_forCompletion) { - if (Ast.GetAncestorAst(functionDefinitionAst).Parent is null) + if (Ast.GetAncestorAst(functionDefinitionAst).Parent == null) { DiscoveredExports.Add(functionName); } @@ -272,7 +272,7 @@ public override AstVisitAction VisitCommand(CommandAst commandAst) commandAst.GetCommandName() ?? GetSafeValueVisitor.GetSafeValue(commandAst.CommandElements[0], null, GetSafeValueVisitor.SafeValueContext.ModuleAnalysis) as string; - if (commandName is null) + if (commandName == null) return AstVisitAction.SkipChildren; // They are trying to dot a script @@ -427,7 +427,7 @@ public override AstVisitAction VisitCommand(CommandAst commandAst) private void ProcessCmdletArguments(object value, Action onEachArgument) { - if (value is null) return; + if (value == null) return; var commandName = value as string; if (commandName != null) @@ -480,7 +480,7 @@ private Hashtable DoPsuedoParameterBinding(CommandAst commandAst, string command } var argumentAst = specifiedParameter.Argument; - if (argumentAst is null) + if (argumentAst == null) { argumentAst = commandAst.CommandElements[i] as ExpressionAst; if (argumentAst != null) diff --git a/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs b/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs index 6d13c611a07..2f6c0fdd5cf 100644 --- a/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs +++ b/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs @@ -90,7 +90,7 @@ protected override void ProcessRecord() } // Make sure at least one file was found... - if (filePaths is null || filePaths.Count < 1) + if (filePaths == null || filePaths.Count < 1) { string message = StringUtil.Format(Modules.ModuleNotFound, _path); FileNotFoundException fnf = new FileNotFoundException(message); @@ -239,7 +239,7 @@ protected override void ProcessRecord() // Ensure that PowerShellVersion module manifest key value is '5.1' or higher. // var minimumRequiredPowerShellVersion = new Version(5, 1); - if ((module.PowerShellVersion is null) || module.PowerShellVersion < minimumRequiredPowerShellVersion) + if ((module.PowerShellVersion == null) || module.PowerShellVersion < minimumRequiredPowerShellVersion) { string errorMsg = StringUtil.Format(Modules.InvalidPowerShellVersionInModuleManifest, filePath); var errorRecord = new ErrorRecord(new ArgumentException(errorMsg), "Modules_InvalidPowerShellVersionInModuleManifest", ErrorCategory.InvalidArgument, _path); diff --git a/src/System.Management.Automation/engine/MshCmdlet.cs b/src/System.Management.Automation/engine/MshCmdlet.cs index 8d3a6936959..113c3d39dbd 100644 --- a/src/System.Management.Automation/engine/MshCmdlet.cs +++ b/src/System.Management.Automation/engine/MshCmdlet.cs @@ -445,7 +445,7 @@ public CmdletInfo GetCmdletByTypeName(string cmdletTypeName) throw e; } - if (cmdletType is null) + if (cmdletType == null) { return null; } @@ -458,7 +458,7 @@ public CmdletInfo GetCmdletByTypeName(string cmdletTypeName) break; } - if (ca is null) + if (ca == null) { throw PSTraceSource.NewNotSupportedException(); } @@ -485,7 +485,7 @@ public List GetCmdlets() /// A list of CmdletInfo objects... public List GetCmdlets(string pattern) { - if (pattern is null) + if (pattern == null) throw PSTraceSource.NewArgumentNullException(nameof(pattern)); List cmdlets = new List(); @@ -546,7 +546,7 @@ public List GetCmdlets(string pattern) /// A list of command names... public List GetCommandName(string name, bool nameIsPattern, bool returnFullName) { - if (name is null) + if (name == null) { throw PSTraceSource.NewArgumentNullException(nameof(name)); } @@ -606,7 +606,7 @@ public List GetCommandName(string name, bool nameIsPattern, bool returnF /// Collection of command names... public IEnumerable GetCommands(string name, CommandTypes commandTypes, bool nameIsPattern) { - if (name is null) + if (name == null) { throw PSTraceSource.NewArgumentNullException(nameof(name)); } @@ -705,12 +705,12 @@ public Collection InvokeScript(string script, params object[] args) public Collection InvokeScript( SessionState sessionState, ScriptBlock scriptBlock, params object[] args) { - if (scriptBlock is null) + if (scriptBlock == null) { throw PSTraceSource.NewArgumentNullException(nameof(scriptBlock)); } - if (sessionState is null) + if (sessionState == null) { throw PSTraceSource.NewArgumentNullException(nameof(sessionState)); } @@ -743,7 +743,7 @@ public Collection InvokeScript( public Collection InvokeScript( bool useLocalScope, ScriptBlock scriptBlock, IList input, params object[] args) { - if (scriptBlock is null) + if (scriptBlock == null) { throw PSTraceSource.NewArgumentNullException(nameof(scriptBlock)); } @@ -783,7 +783,7 @@ public Collection InvokeScript( public Collection InvokeScript(string script, bool useNewScope, PipelineResultTypes writeToPipeline, IList input, params object[] args) { - if (script is null) + if (script == null) throw new ArgumentNullException(nameof(script)); // Compile the script text into an executable script block. @@ -969,7 +969,7 @@ public PagingParameters PagingParameters return null; } - if (_pagingParameters is null) + if (_pagingParameters == null) { MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime; if (mshCommandRuntime != null) diff --git a/src/System.Management.Automation/engine/MshCommandRuntime.cs b/src/System.Management.Automation/engine/MshCommandRuntime.cs index f9c26c5b574..b67d2d861a5 100644 --- a/src/System.Management.Automation/engine/MshCommandRuntime.cs +++ b/src/System.Management.Automation/engine/MshCommandRuntime.cs @@ -63,7 +63,7 @@ internal bool IsPipelineInputExpected { // No objects in the input pipe // The pipe is closed. So there can't be any more object - if (IsClosed && (_inputPipe is null || _inputPipe.Empty)) + if (IsClosed && (_inputPipe == null || _inputPipe.Empty)) { return false; } @@ -174,7 +174,7 @@ public void WriteObject(object sendToPipeline) #else if (UseSecurityContextRun) { - if (PipelineProcessor is null || PipelineProcessor.SecurityContext is null) + if (PipelineProcessor == null || PipelineProcessor.SecurityContext == null) throw PSTraceSource.NewInvalidOperationException(PipelineStrings.WriteNotPermitted); ContextCallback delegateCallback = new ContextCallback(DoWriteObject); @@ -252,7 +252,7 @@ public void WriteObject(object sendToPipeline, bool enumerateCollection) #else if (UseSecurityContextRun) { - if (PipelineProcessor is null || PipelineProcessor.SecurityContext is null) + if (PipelineProcessor == null || PipelineProcessor.SecurityContext == null) throw PSTraceSource.NewInvalidOperationException(PipelineStrings.WriteNotPermitted); ContextCallback delegateCallback = new ContextCallback(DoWriteObjects); @@ -394,12 +394,12 @@ internal void WriteProgress( ProgressRecord progressRecord, bool overrideInquire) { - if (progressRecord is null) + if (progressRecord == null) { throw PSTraceSource.NewArgumentNullException(nameof(progressRecord)); } - if (Host is null || Host.UI is null) + if (Host == null || Host.UI == null) { Diagnostics.Assert(false, "No host in CommandBase.WriteProgress()"); throw PSTraceSource.NewInvalidOperationException(); @@ -482,7 +482,7 @@ internal void WriteDebug(DebugRecord record, bool overrideInquire = false) if (WriteHelper_ShouldWrite(preference, lastDebugContinueStatus)) { - if (record.InvocationInfo is null) + if (record.InvocationInfo == null) { record.SetInvocationInfo(MyInvocation); } @@ -514,7 +514,7 @@ internal void WriteDebug(DebugRecord record, bool overrideInquire = false) // // If no pipe, write directly to host. // - if (Host is null || Host.UI is null) + if (Host == null || Host.UI == null) { Diagnostics.Assert(false, "No host in CommandBase.WriteDebug()"); throw PSTraceSource.NewInvalidOperationException(); @@ -576,7 +576,7 @@ internal void WriteVerbose(VerboseRecord record, bool overrideInquire = false) if (WriteHelper_ShouldWrite(preference, lastVerboseContinueStatus)) { - if (record.InvocationInfo is null) + if (record.InvocationInfo == null) { record.SetInvocationInfo(MyInvocation); } @@ -608,7 +608,7 @@ internal void WriteVerbose(VerboseRecord record, bool overrideInquire = false) // // If no pipe, write directly to host. // - if (Host is null || Host.UI is null) + if (Host == null || Host.UI == null) { Diagnostics.Assert(false, "No host in CommandBase.WriteVerbose()"); throw PSTraceSource.NewInvalidOperationException(); @@ -670,7 +670,7 @@ internal void WriteWarning(WarningRecord record, bool overrideInquire = false) if (WriteHelper_ShouldWrite(preference, lastWarningContinueStatus)) { - if (record.InvocationInfo is null) + if (record.InvocationInfo == null) { record.SetInvocationInfo(MyInvocation); } @@ -702,7 +702,7 @@ internal void WriteWarning(WarningRecord record, bool overrideInquire = false) // // If no pipe, write directly to host. // - if (Host is null || Host.UI is null) + if (Host == null || Host.UI == null) { Diagnostics.Assert(false, "No host in CommandBase.WriteWarning()"); throw PSTraceSource.NewInvalidOperationException(); @@ -770,7 +770,7 @@ internal void WriteInformation(InformationRecord record, bool overrideInquire = // // If no pipe, write directly to host. // - if (Host is null || Host.UI is null) + if (Host == null || Host.UI == null) { throw PSTraceSource.NewInvalidOperationException("No host in CommandBase.WriteInformation()"); } @@ -898,12 +898,12 @@ private bool InitShouldLogPipelineExecutionDetail() return true; } - if (cmdletInfo.Module is null && cmdletInfo.PSSnapIn != null) + if (cmdletInfo.Module == null && cmdletInfo.PSSnapIn != null) { return cmdletInfo.PSSnapIn.LogPipelineExecutionDetails; } - if (cmdletInfo.PSSnapIn is null && cmdletInfo.Module != null) + if (cmdletInfo.PSSnapIn == null && cmdletInfo.Module != null) { return cmdletInfo.Module.LogPipelineExecutionDetails; } @@ -945,7 +945,7 @@ internal void SetupOutVariable() (!(this.OutVariable.StartsWith('+'))) && string.Equals("Out-Default", _thisCommand.CommandInfo.Name, StringComparison.OrdinalIgnoreCase)) { - if (_state is null) + if (_state == null) _state = new SessionState(Context.EngineSessionState); IList oldValue = null; @@ -978,7 +978,7 @@ internal void SetupPipelineVariable() EnsureVariableParameterAllowed(); - if (_state is null) + if (_state == null) _state = new SessionState(Context.EngineSessionState); // Create the pipeline variable @@ -1426,7 +1426,7 @@ private bool CanShouldProcessAutoConfirm() { // retrieve ConfirmImpact from commandInfo CommandMetadata commandMetadata = _commandInfo.CommandMetadata; - if (commandMetadata is null) + if (commandMetadata == null) { Dbg.Assert(false, "Expected CommandMetadata"); return true; @@ -2052,7 +2052,7 @@ public PSTransactionContext CurrentPSTransaction public void ThrowTerminatingError(ErrorRecord errorRecord) { ThrowIfStopping(); - if (errorRecord is null) + if (errorRecord == null) { throw PSTraceSource.NewArgumentNullException(nameof(errorRecord)); } @@ -2222,7 +2222,7 @@ internal Pipe OutputPipe internal object[] GetResultsAsArray() { - if (_outputPipe is null) + if (_outputPipe == null) return StaticEmptyArray; return _outputPipe.ToArray(); } @@ -2284,7 +2284,7 @@ internal void ThrowIfStopping() /// internal void ThrowIfWriteNotPermitted(bool needsToWriteToPipeline) { - if (this.PipelineProcessor is null + if (this.PipelineProcessor == null || _thisCommand != this.PipelineProcessor._permittedToWrite || needsToWriteToPipeline && !this.PipelineProcessor._permittedToWriteToPipeline || Thread.CurrentThread != this.PipelineProcessor._permittedToWriteThread @@ -2318,13 +2318,13 @@ private class AllowWrite : IDisposable /// internal AllowWrite(InternalCommand permittedToWrite, bool permittedToWriteToPipeline) { - if (permittedToWrite is null) + if (permittedToWrite == null) throw PSTraceSource.NewArgumentNullException(nameof(permittedToWrite)); MshCommandRuntime mcr = permittedToWrite.commandRuntime as MshCommandRuntime; - if (mcr is null) + if (mcr == null) throw PSTraceSource.NewArgumentNullException("permittedToWrite.CommandRuntime"); _pp = mcr.PipelineProcessor; - if (_pp is null) + if (_pp == null) throw PSTraceSource.NewArgumentNullException("permittedToWrite.CommandRuntime.PipelineProcessor"); _wasPermittedToWrite = _pp._permittedToWrite; _wasPermittedToWriteToPipeline = _pp._permittedToWriteToPipeline; @@ -2368,7 +2368,7 @@ public void Dispose() /// PipelineStoppedException. public Exception ManageException(Exception e) { - if (e is null) + if (e == null) throw PSTraceSource.NewArgumentNullException(nameof(e)); if (PipelineProcessor != null) @@ -2446,7 +2446,7 @@ private void EnsureVariableParameterAllowed() /// internal void AppendErrorToVariables(object obj) { - if (obj is null) + if (obj == null) return; AppendDollarError(obj); @@ -2471,7 +2471,7 @@ private void AppendDollarError(object obj) { if (obj is Exception) { - if (this.PipelineProcessor is null || !this.PipelineProcessor.TopLevel) + if (this.PipelineProcessor == null || !this.PipelineProcessor.TopLevel) return; // not outermost scope } @@ -2534,7 +2534,7 @@ internal void SetupVariable(VariableStreamKind streamKind, string variableName, EnsureVariableParameterAllowed(); - if (_state is null) + if (_state == null) _state = new SessionState(Context.EngineSessionState); if (variableName.StartsWith('+')) @@ -2542,7 +2542,7 @@ internal void SetupVariable(VariableStreamKind streamKind, string variableName, variableName = variableName.Substring(1); object oldValue = PSObject.Base(_state.PSVariable.GetValue(variableName)); varList = oldValue as IList; - if (varList is null) + if (varList == null) { varList = new ArrayList(); @@ -2635,7 +2635,7 @@ internal void _WriteObjectSkipAllowCheck(object sendToPipeline) internal void _EnumerateAndWriteObjectSkipAllowCheck(object sendToPipeline) { IEnumerable enumerable = LanguagePrimitives.GetEnumerable(sendToPipeline); - if (enumerable is null) + if (enumerable == null) { _WriteObjectSkipAllowCheck(sendToPipeline); return; @@ -2727,7 +2727,7 @@ internal void WriteError(ErrorRecord errorRecord, bool overrideInquire) #else if (UseSecurityContextRun) { - if (PipelineProcessor is null || PipelineProcessor.SecurityContext is null) + if (PipelineProcessor == null || PipelineProcessor.SecurityContext == null) throw PSTraceSource.NewInvalidOperationException(PipelineStrings.WriteNotPermitted); ContextCallback delegateCallback = new ContextCallback(DoWriteError); @@ -2765,7 +2765,7 @@ private void DoWriteError(object obj) KeyValuePair pair = (KeyValuePair)obj; ErrorRecord errorRecord = pair.Key; ActionPreference preference = pair.Value; - if (errorRecord is null) + if (errorRecord == null) { throw PSTraceSource.NewArgumentNullException("errorRecord"); } @@ -2998,7 +2998,7 @@ internal ActionPreference DebugPreference // If the host couldn't prompt for the debug action anyways, change it to 'Continue'. // This lets hosts still see debug output without having to implement the prompting logic. - if ((CBhost.ExternalHost.UI is null) && (_debugPreference == ActionPreference.Inquire)) + if ((CBhost.ExternalHost.UI == null) && (_debugPreference == ActionPreference.Inquire)) { _debugPreference = ActionPreference.Continue; } @@ -3045,7 +3045,7 @@ internal ActionPreference VerbosePreference { // If the host couldn't prompt for the debug action anyways, use 'Continue'. // This lets hosts still see debug output without having to implement the prompting logic. - if (CBhost.ExternalHost.UI is null) + if (CBhost.ExternalHost.UI == null) { return ActionPreference.Continue; } diff --git a/src/System.Management.Automation/engine/MshMemberInfo.cs b/src/System.Management.Automation/engine/MshMemberInfo.cs index 619dd53e182..451048e2018 100644 --- a/src/System.Management.Automation/engine/MshMemberInfo.cs +++ b/src/System.Management.Automation/engine/MshMemberInfo.cs @@ -534,7 +534,7 @@ private PSMemberInfo LookupMember(string name) private void LookupMember(string name, HashSet visitedAliases, out PSMemberInfo returnedMember, out bool hasCycle) { returnedMember = null; - if (this.instance is null) + if (this.instance == null) { throw new ExtendedTypeSystemException("AliasLookupMemberOutsidePSObject", null, @@ -543,7 +543,7 @@ private void LookupMember(string name, HashSet visitedAliases, out PSMem } PSMemberInfo member = PSObject.AsPSObject(this.instance).Properties[name]; - if (member is null) + if (member == null) { throw new ExtendedTypeSystemException( "AliasLookupMemberNotPresent", @@ -654,7 +654,7 @@ internal void SetGetterFromTypeTable(Type type, string methodName) // We will generate error below if we cannot find exactly one match method. } - if (methodAsMember is null) + if (methodAsMember == null) { throw new ExtendedTypeSystemException( "GetterFormatFromTypeTable", @@ -682,7 +682,7 @@ internal void SetSetterFromTypeTable(Type type, string methodName) // We will generate error below if we cannot find exactly one match method. } - if (methodAsMember is null) + if (methodAsMember == null) { throw new ExtendedTypeSystemException( "SetterFormatFromTypeTable", @@ -698,7 +698,7 @@ internal void SetSetterFromTypeTable(Type type, string methodName) /// internal void SetGetter(MethodInfo methodForGet) { - if (methodForGet is null) + if (methodForGet == null) { GetterCodeReference = null; return; @@ -730,9 +730,9 @@ internal static bool CheckGetterMethodInfo(MethodInfo methodForGet) /// private void SetSetter(MethodInfo methodForSet, MethodInfo methodForGet) { - if (methodForSet is null) + if (methodForSet == null) { - if (methodForGet is null) + if (methodForGet == null) { throw new ExtendedTypeSystemException( "SetterAndGetterNullFormat", @@ -763,7 +763,7 @@ internal static bool CheckSetterMethodInfo(MethodInfo methodForSet, MethodInfo m && methodForSet.ReturnType == typeof(void) && parameters.Length == 2 && parameters[0].ParameterType == typeof(PSObject) - && (methodForGet is null || methodForGet.ReturnType == parameters[1].ParameterType); + && (methodForGet == null || methodForGet.ReturnType == parameters[1].ParameterType); } /// @@ -794,7 +794,7 @@ public PSCodeProperty(string name, MethodInfo getterCodeReference) } this.name = name; - if (getterCodeReference is null) + if (getterCodeReference == null) { throw PSTraceSource.NewArgumentNullException(nameof(getterCodeReference)); } @@ -823,7 +823,7 @@ public PSCodeProperty(string name, MethodInfo getterCodeReference, MethodInfo se } this.name = name; - if (getterCodeReference is null && setterCodeReference is null) + if (getterCodeReference == null && setterCodeReference == null) { throw PSTraceSource.NewArgumentNullException("getterCodeReference setterCodeReference"); } @@ -879,7 +879,7 @@ public override object Value { get { - if (GetterCodeReference is null) + if (GetterCodeReference == null) { throw new GetValueException( "GetWithoutGetterFromCodePropertyValue", @@ -920,7 +920,7 @@ public override object Value set { - if (SetterCodeReference is null) + if (SetterCodeReference == null) { throw new SetValueException( "SetWithoutSetterFromCodeProperty", @@ -968,7 +968,7 @@ public override string TypeNameOfValue { get { - if (GetterCodeReference is null) + if (GetterCodeReference == null) { throw new GetValueException( "GetWithoutGetterFromCodePropertyTypeOfValue", @@ -1185,7 +1185,7 @@ public override string TypeNameOfValue { if (this.isDeserialized) { - if (serializedValue is null) + if (serializedValue == null) { return string.Empty; } @@ -1277,7 +1277,7 @@ public override string ToString() returnValue.Append(" "); returnValue.Append(this.Name); returnValue.Append("="); - returnValue.Append(this.noteValue is null ? "null" : this.noteValue.ToString()); + returnValue.Append(this.noteValue == null ? "null" : this.noteValue.ToString()); return returnValue.ToString(); } @@ -1358,7 +1358,7 @@ public override string TypeNameOfValue { object val = this.Value; - if (val is null) + if (val == null) { return typeof(object).FullName; } @@ -1395,7 +1395,7 @@ internal static string GetDisplayTypeNameOfValue(object val) if (string.IsNullOrEmpty(displayTypeName)) { - displayTypeName = val is null + displayTypeName = val == null ? "object" : ToStringCodeMethods.Type(val.GetType(), dropNamespaces: true); } @@ -1501,7 +1501,7 @@ public override string TypeNameOfValue { object val = _variable.Value; - if (val is null) + if (val == null) { return typeof(object).FullName; } @@ -1579,7 +1579,7 @@ public ScriptBlock GetterScript { // If we don't have a script block for the getter, see if we // have the text for it (to support delayed script compilation). - if ((_getterScript is null) && (_getterScriptText != null)) + if ((_getterScript == null) && (_getterScriptText != null)) { _getterScript = ScriptBlock.Create(_getterScriptText); @@ -1591,7 +1591,7 @@ public ScriptBlock GetterScript _getterScript.DebuggerStepThrough = true; } - if (_getterScript is null) + if (_getterScript == null) { return null; } @@ -1622,7 +1622,7 @@ public ScriptBlock SetterScript { // If we don't have a script block for the setter, see if we // have the text for it (to support delayed script compilation). - if ((_setterScript is null) && (_setterScriptText != null)) + if ((_setterScript == null) && (_setterScriptText != null)) { _setterScript = ScriptBlock.Create(_setterScriptText); @@ -1634,7 +1634,7 @@ public ScriptBlock SetterScript _setterScript.DebuggerStepThrough = true; } - if (_setterScript is null) + if (_setterScript == null) { return null; } @@ -1690,7 +1690,7 @@ public PSScriptProperty(string name, ScriptBlock getterScript, ScriptBlock sette } this.name = name; - if (getterScript is null && setterScript is null) + if (getterScript == null && setterScript == null) { // we only do not allow both getterScript and setterScript to be null throw PSTraceSource.NewArgumentException("getterScript setterScript"); @@ -1727,7 +1727,7 @@ internal PSScriptProperty(string name, string getterScript, string setterScript, } this.name = name; - if (getterScript is null && setterScript is null) + if (getterScript == null && setterScript == null) { // we only do not allow both getterScript and setterScript to be null throw PSTraceSource.NewArgumentException("getterScript setterScript"); @@ -1790,7 +1790,7 @@ public override object Value { get { - if (this.GetterScript is null) + if (this.GetterScript == null) { throw new GetValueException("GetWithoutGetterFromScriptPropertyValue", null, @@ -1803,7 +1803,7 @@ public override object Value set { - if (this.SetterScript is null) + if (this.SetterScript == null) { throw new SetValueException("SetWithoutSetterFromScriptProperty", null, @@ -1924,12 +1924,12 @@ internal PSMethodInvocationConstraints( internal static bool EqualsForCollection(ICollection xs, ICollection ys) { - if (xs is null) + if (xs == null) { - return ys is null; + return ys == null; } - if (ys is null) + if (ys == null) { return false; } @@ -2137,7 +2137,7 @@ internal void SetCodeReference(Type type, string methodName) // We will generate error below if we cannot find exactly one match method. } - if (methodAsMember is null) + if (methodAsMember == null) { throw new ExtendedTypeSystemException("WrongMethodFormatFromTypeTable", null, ExtendedTypeSystem.CodeMethodMethodFormat); @@ -2177,7 +2177,7 @@ public PSCodeMethod(string name, MethodInfo codeReference) throw PSTraceSource.NewArgumentException(nameof(name)); } - if (codeReference is null) + if (codeReference == null) { throw PSTraceSource.NewArgumentNullException(nameof(codeReference)); } @@ -2228,7 +2228,7 @@ public override PSMemberInfo Copy() /// For exceptions invoking the CodeReference. public override object Invoke(params object[] arguments) { - if (arguments is null) + if (arguments == null) { throw PSTraceSource.NewArgumentNullException(nameof(arguments)); } @@ -2240,7 +2240,7 @@ public override object Invoke(params object[] arguments) newArguments[i + 1] = arguments[i]; } - if (_codeReferenceMethodInformation is null) + if (_codeReferenceMethodInformation == null) { _codeReferenceMethodInformation = DotNetAdapter.GetMethodInformationArray(new[] { CodeReference }); } @@ -2363,7 +2363,7 @@ internal PSScriptMethod(string name, ScriptBlock script, bool shouldCloneOnAcces /// For exceptions invoking the Script or if there is no Runspace to run the script. public override object Invoke(params object[] arguments) { - if (arguments is null) + if (arguments == null) { throw PSTraceSource.NewArgumentNullException(nameof(arguments)); } @@ -2558,7 +2558,7 @@ public override object Invoke(params object[] arguments) /// For exceptions invoking the method. internal object Invoke(PSMethodInvocationConstraints invocationConstraints, params object[] arguments) { - if (arguments is null) + if (arguments == null) { throw PSTraceSource.NewArgumentNullException(nameof(arguments)); } @@ -2596,7 +2596,7 @@ internal static PSMethod Create(string name, DotNetAdapter dotNetInstanceAdapter return new PSMethod(name, dotNetInstanceAdapter, baseObject, method, isSpecial, isHidden); } - if (method.PSMethodCtor is null) + if (method.PSMethodCtor == null) { method.PSMethodCtor = CreatePSMethodConstructor(method.methodInformationStructures); } @@ -2949,7 +2949,7 @@ internal PSParameterizedProperty(string name) /// When getting the value of a property throws an exception. public override object Invoke(params object[] arguments) { - if (arguments is null) + if (arguments == null) { throw PSTraceSource.NewArgumentNullException(nameof(arguments)); } @@ -2966,7 +2966,7 @@ public override object Invoke(params object[] arguments) /// When setting the value of a property throws an exception. public void InvokeSet(object valueToSet, params object[] arguments) { - if (arguments is null) + if (arguments == null) { throw PSTraceSource.NewArgumentNullException(nameof(arguments)); } @@ -3085,7 +3085,7 @@ public PSMemberSet(string name, IEnumerable members) } this.name = name; - if (members is null) + if (members == null) { throw PSTraceSource.NewArgumentNullException(nameof(members)); } @@ -3093,7 +3093,7 @@ public PSMemberSet(string name, IEnumerable members) this.internalMembers = new PSMemberInfoInternalCollection(); foreach (PSMemberInfo member in members) { - if (member is null) + if (member == null) { throw PSTraceSource.NewArgumentNullException(nameof(members)); } @@ -3177,7 +3177,7 @@ internal PSMemberSet(string name, PSObject mshObject) } this.name = name; - if (mshObject is null) + if (mshObject == null) { throw PSTraceSource.NewArgumentNullException(nameof(mshObject)); } @@ -3225,7 +3225,7 @@ internal PSMemberSet(string name, PSObject mshObject) /// A new PSMemberInfo that is a copy of this PSMemberInfo. public override PSMemberInfo Copy() { - if (_constructorPSObject is null) + if (_constructorPSObject == null) { PSMemberSet memberSet = new PSMemberSet(name); foreach (PSMemberInfo member in this.Members) @@ -3317,11 +3317,11 @@ internal override PSMemberInfoInternalCollection InternalMembers } // cache "psbase" and "psobject" - if (internalMembers is null) + if (internalMembers == null) { lock (_syncObject) { - if (internalMembers is null) + if (internalMembers == null) { internalMembers = new PSMemberInfoInternalCollection(); @@ -3459,7 +3459,7 @@ public PSPropertySet(string name, IEnumerable referencedPropertyNames) } this.name = name; - if (referencedPropertyNames is null) + if (referencedPropertyNames == null) { throw PSTraceSource.NewArgumentNullException(nameof(referencedPropertyNames)); } @@ -3691,7 +3691,7 @@ internal static PSMemberInfoInternalCollection Match(PSMemberInfoInternalC where T : PSMemberInfo { PSMemberInfoInternalCollection returnValue = new PSMemberInfoInternalCollection(); - if (memberList is null) + if (memberList == null) { throw PSTraceSource.NewArgumentNullException(nameof(memberList)); } @@ -3701,7 +3701,7 @@ internal static PSMemberInfoInternalCollection Match(PSMemberInfoInternalC throw PSTraceSource.NewArgumentException(nameof(name)); } - if (nameMatch is null) + if (nameMatch == null) { T member = memberList[name]; if (member != null && (member.MemberType & memberTypes) != 0) @@ -3883,7 +3883,7 @@ public class ReadOnlyPSMemberInfoCollection : IEnumerable where T : PSMemb /// For invalid arguments. internal ReadOnlyPSMemberInfoCollection(PSMemberInfoInternalCollection members) { - if (members is null) + if (members == null) { throw PSTraceSource.NewArgumentNullException(nameof(members)); } @@ -3990,7 +3990,7 @@ private OrderedDictionary Members { get { - if (_members is null) + if (_members == null) { System.Threading.Interlocked.CompareExchange(ref _members, new OrderedDictionary(StringComparer.OrdinalIgnoreCase), null); } @@ -4068,7 +4068,7 @@ public override void Add(T member) /// For invalid arguments. public override void Add(T member, bool preValidated) { - if (member is null) + if (member == null) { throw PSTraceSource.NewArgumentNullException(nameof(member)); } @@ -4113,7 +4113,7 @@ public override void Remove(string name) name); } - if (_members is null) + if (_members == null) { return; } @@ -4147,7 +4147,7 @@ public override T this[string name] throw PSTraceSource.NewArgumentException(nameof(name)); } - if (_members is null) + if (_members == null) { return null; } @@ -4215,7 +4215,7 @@ private PSMemberInfoInternalCollection GetInternalMembers(MshMemberMatchOptio { PSMemberInfoInternalCollection returnValue = new PSMemberInfoInternalCollection(); - if (_members is null) + if (_members == null) { return returnValue; } @@ -4241,7 +4241,7 @@ internal int Count { get { - if (_members is null) + if (_members == null) { return 0; } @@ -4260,7 +4260,7 @@ internal int VisibleCount { get { - if (_members is null) + if (_members == null) { return 0; } @@ -4281,7 +4281,7 @@ internal T this[int index] { get { - if (_members is null) + if (_members == null) { return null; } @@ -4301,7 +4301,7 @@ internal T this[int index] /// The enumerator for this collection. public override IEnumerator GetEnumerator() { - if (_members is null) + if (_members == null) { return Enumerable.Empty().GetEnumerator(); } @@ -4395,7 +4395,7 @@ private static object GenerateMemberSet(string name, object obj) { PSObject mshOwner = PSObject.AsPSObject(obj); var memberSet = mshOwner.InstanceMembers[name]; - if (memberSet is null) + if (memberSet == null) { memberSet = new PSInternalMemberSet(name, mshOwner) { @@ -4429,7 +4429,7 @@ internal static object GeneratePSExtendedMemberSet(object obj) { PSObject mshOwner = PSObject.AsPSObject(obj); var memberSet = mshOwner.InstanceMembers[PSObject.ExtendedMemberSetName]; - if (memberSet is null) + if (memberSet == null) { memberSet = new PSMemberSet(PSObject.ExtendedMemberSetName, mshOwner) { @@ -4499,19 +4499,19 @@ private void GenerateAllReservedMembers() internal PSMemberInfoIntegratingCollection(object owner, Collection> collections) { - if (owner is null) + if (owner == null) { throw PSTraceSource.NewArgumentNullException(nameof(owner)); } _mshOwner = owner as PSObject; _memberSetOwner = owner as PSMemberSet; - if (_mshOwner is null && _memberSetOwner is null) + if (_mshOwner == null && _memberSetOwner == null) { throw PSTraceSource.NewArgumentException(nameof(owner)); } - if (collections is null) + if (collections == null) { throw PSTraceSource.NewArgumentNullException(nameof(collections)); } @@ -4561,7 +4561,7 @@ public override void Add(T member) /// For invalid arguments. public override void Add(T member, bool preValidated) { - if (member is null) + if (member == null) { throw PSTraceSource.NewArgumentNullException(nameof(member)); } @@ -4626,7 +4626,7 @@ internal void AddToReservedMemberSet(T member, bool preValidated) /// For invalid arguments. internal void AddToTypesXmlCache(T member, bool preValidated) { - if (member is null) + if (member == null) { throw PSTraceSource.NewArgumentNullException(nameof(member)); } @@ -4812,7 +4812,7 @@ public override T this[string name] } } - if (delegateOwner is null) + if (delegateOwner == null) return null; delegateOwner = PSObject.AsPSObject(delegateOwner); @@ -4867,7 +4867,7 @@ private PSMemberInfoInternalCollection GetIntegratedMembers(MshMemberMatchOpt } } - if (delegateOwner is null) + if (delegateOwner == null) return returnValue; delegateOwner = PSObject.AsPSObject(delegateOwner); @@ -5000,7 +5000,7 @@ internal override T FirstOrDefault(MemberNamePredicate predicate) } } - if (delegateOwner is null) + if (delegateOwner == null) { return null; } diff --git a/src/System.Management.Automation/engine/MshObject.cs b/src/System.Management.Automation/engine/MshObject.cs index 90a4177ebc3..cd7a8cf0a14 100644 --- a/src/System.Management.Automation/engine/MshObject.cs +++ b/src/System.Management.Automation/engine/MshObject.cs @@ -70,14 +70,14 @@ internal static T TypeTableGetMemberDelegate(PSObject msjObj, string name) wh private static T TypeTableGetMemberDelegate(PSObject msjObj, TypeTable typeTableToUse, string name) where T : PSMemberInfo { - if (typeTableToUse is null) + if (typeTableToUse == null) { return null; } PSMemberInfoInternalCollection allMembers = typeTableToUse.GetMembers(msjObj.InternalTypeNames); PSMemberInfo member = allMembers[name]; - if (member is null) + if (member == null) { PSObject.MemberResolution.WriteLine("\"{0}\" NOT present in type table.", name); return null; @@ -102,7 +102,7 @@ internal static PSMemberInfoInternalCollection TypeTableGetMembersDelegate internal static PSMemberInfoInternalCollection TypeTableGetMembersDelegate(PSObject msjObj, TypeTable typeTableToUse) where T : PSMemberInfo { - if (typeTableToUse is null) + if (typeTableToUse == null) { return new PSMemberInfoInternalCollection(); } @@ -127,18 +127,18 @@ private static T AdapterGetMemberDelegate(PSObject msjObj, string name) where { if (msjObj.IsDeserialized) { - if (msjObj.AdaptedMembers is null) + if (msjObj.AdaptedMembers == null) { return null; } T adaptedMember = msjObj.AdaptedMembers[name] as T; - PSObject.MemberResolution.WriteLine("Serialized adapted member: {0}.", adaptedMember is null ? "not found" : adaptedMember.Name); + PSObject.MemberResolution.WriteLine("Serialized adapted member: {0}.", adaptedMember == null ? "not found" : adaptedMember.Name); return adaptedMember; } T retValue = msjObj.InternalAdapter.BaseGetMember(msjObj.ImmediateBaseObject, name); - PSObject.MemberResolution.WriteLine("Adapted member: {0}.", retValue is null ? "not found" : retValue.Name); + PSObject.MemberResolution.WriteLine("Adapted member: {0}.", retValue == null ? "not found" : retValue.Name); return retValue; } @@ -146,7 +146,7 @@ private static T AdapterGetFirstMemberOrDefaultDelegate(PSObject msjObj, Memb { if (msjObj.IsDeserialized && typeof(T).IsAssignableFrom(typeof(PSPropertyInfo))) { - if (msjObj.AdaptedMembers is null) + if (msjObj.AdaptedMembers == null) { return null; } @@ -188,7 +188,7 @@ private static PSMemberInfoInternalCollection AdapterGetMembersDelegate(PS { if (msjObj.IsDeserialized) { - if (msjObj.AdaptedMembers is null) + if (msjObj.AdaptedMembers == null) { return new PSMemberInfoInternalCollection(); } @@ -221,7 +221,7 @@ private static T DotNetGetMemberDelegate(PSObject msjObj, string name) where if (msjObj.InternalBaseDotNetAdapter != null) { T retValue = msjObj.InternalBaseDotNetAdapter.BaseGetMember(msjObj._immediateBaseObject, name); - PSObject.MemberResolution.WriteLine("DotNet member: {0}.", retValue is null ? "not found" : retValue.Name); + PSObject.MemberResolution.WriteLine("DotNet member: {0}.", retValue == null ? "not found" : retValue.Name); return retValue; } @@ -265,7 +265,7 @@ internal static Collection> GetMemberCollection( Collection> returnValue = new Collection>(); if ((viewType & PSMemberViewTypes.Extended) == PSMemberViewTypes.Extended) { - if (backupTypeTable is null) + if (backupTypeTable == null) { returnValue.Add(new CollectionEntry( PSObject.TypeTableGetMembersDelegate, @@ -369,7 +369,7 @@ internal static Collection> GetPropertyCollectio Collection> returnValue = new Collection>(); if ((viewType & PSMemberViewTypes.Extended) == PSMemberViewTypes.Extended) { - if (backupTypeTable is null) + if (backupTypeTable == null) { returnValue.Add(new CollectionEntry( PSObject.TypeTableGetMembersDelegate, @@ -487,7 +487,7 @@ internal static AdapterSet GetMappedAdapter(object obj, TypeTable typeTable) } } - if (result is null) + if (result == null) { if (objectType.IsCOMObject) { @@ -568,7 +568,7 @@ public PSObject(int instanceMemberCapacity) : this() [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "obj", Justification = "This is shipped as part of V1. Retaining this for backward compatibility.")] public PSObject(object obj) { - if (obj is null) + if (obj == null) { throw PSTraceSource.NewArgumentNullException(nameof(obj)); } @@ -583,14 +583,14 @@ public PSObject(object obj) /// The streaming context for this instance. protected PSObject(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) { throw PSTraceSource.NewArgumentNullException(nameof(info)); } string serializedData = info.GetValue("CliXml", typeof(string)) as string; - if (serializedData is null) + if (serializedData == null) { throw PSTraceSource.NewArgumentNullException(nameof(info)); } @@ -670,11 +670,11 @@ internal PSMemberInfoInternalCollection InstanceMembers { get { - if (_instanceMembers is null) + if (_instanceMembers == null) { lock (_lockObject) { - if (_instanceMembers is null) + if (_instanceMembers == null) { _instanceMembers = s_instanceMembersResurrectionTable.GetValue( @@ -717,11 +717,11 @@ private AdapterSet InternalAdapterSet { get { - if (_adapterSet is null) + if (_adapterSet == null) { lock (_lockObject) { - if (_adapterSet is null) + if (_adapterSet == null) { _adapterSet = GetMappedAdapter(_immediateBaseObject, GetTypeTable()); } @@ -739,11 +739,11 @@ public PSMemberInfoCollection Members { get { - if (_members is null) + if (_members == null) { lock (_lockObject) { - if (_members is null) + if (_members == null) { _members = new PSMemberInfoIntegratingCollection(this, s_memberCollection); } @@ -761,11 +761,11 @@ public PSMemberInfoCollection Properties { get { - if (_properties is null) + if (_properties == null) { lock (_lockObject) { - if (_properties is null) + if (_properties == null) { _properties = new PSMemberInfoIntegratingCollection(this, s_propertyCollection); } @@ -783,11 +783,11 @@ public PSMemberInfoCollection Methods { get { - if (_methods is null) + if (_methods == null) { lock (_lockObject) { - if (_methods is null) + if (_methods == null) { _methods = new PSMemberInfoIntegratingCollection(this, s_methodCollection); } @@ -862,11 +862,11 @@ internal ConsolidatedString InternalTypeNames { get { - if (_typeNames is null) + if (_typeNames == null) { lock (_lockObject) { - if (_typeNames is null) + if (_typeNames == null) { if (!s_typeNamesResurrectionTable.TryGetValue(GetKeyForResurrectionTables(this), out _typeNames)) { @@ -917,7 +917,7 @@ internal static bool HasInstanceMembers(object obj, out PSMemberInfoInternalColl { lock (psobj) { - if (psobj._instanceMembers is null) + if (psobj._instanceMembers == null) { s_instanceMembersResurrectionTable.TryGetValue(GetKeyForResurrectionTables(psobj), out psobj._instanceMembers); } @@ -989,7 +989,7 @@ public static implicit operator PSObject(bool valueToConvert) internal static object Base(object obj) { PSObject mshObj = obj as PSObject; - if (mshObj is null) + if (mshObj == null) { return obj; } @@ -1014,7 +1014,7 @@ internal static object Base(object obj) internal static PSMemberInfo GetStaticCLRMember(object obj, string methodName) { obj = PSObject.Base(obj); - if (obj is null || methodName is null || methodName.Length == 0) + if (obj == null || methodName == null || methodName.Length == 0) { return null; } @@ -1050,7 +1050,7 @@ public static PSObject AsPSObject(object obj) [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "obj", Justification = "AsPSObject is shipped as part of V1. This is a new overload method.")] internal static PSObject AsPSObject(object obj, bool storeTypeNameAndInstanceMembersLocally) { - if (obj is null) + if (obj == null) { throw PSTraceSource.NewArgumentNullException(nameof(obj)); } @@ -1074,7 +1074,7 @@ internal static PSObject AsPSObject(object obj, bool storeTypeNameAndInstanceMem internal static object GetKeyForResurrectionTables(object obj) { var pso = obj as PSObject; - if (pso is null) + if (pso == null) { return obj; } @@ -1309,9 +1309,9 @@ bool TryFastTrackPrimitiveTypes(object value, out string str) PSObject mshObj = obj as PSObject; #region plain object - if (mshObj is null) + if (mshObj == null) { - if (obj is null) + if (obj == null) { return string.Empty; } @@ -1360,7 +1360,7 @@ bool TryFastTrackPrimitiveTypes(object value, out string str) IFormattable objFormattable = obj as IFormattable; try { - if (objFormattable is null) + if (objFormattable == null) { Type type = obj as Type; if (type != null) @@ -1393,7 +1393,7 @@ bool TryFastTrackPrimitiveTypes(object value, out string str) method = instanceMembers["ToString"] as PSMethodInfo; } - if (method is null) + if (method == null) { if (mshObj.InternalTypeNames.Count != 0) { @@ -1502,7 +1502,7 @@ bool TryFastTrackPrimitiveTypes(object value, out string str) IFormattable msjObjFormattable = baseObject as IFormattable; try { - var result = msjObjFormattable is null ? baseObject.ToString() : msjObjFormattable.ToString(format, formatProvider); + var result = msjObjFormattable == null ? baseObject.ToString() : msjObjFormattable.ToString(format, formatProvider); return result ?? string.Empty; } @@ -1814,7 +1814,7 @@ internal void AddOrSetProperty(PSNoteProperty property) /// The streaming context for this instance. public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) { throw PSTraceSource.NewArgumentNullException(nameof(info)); } @@ -1851,7 +1851,7 @@ internal static object GetNoteSettingValue(PSMemberSet settings, string noteName object defaultValue, Type expectedType, bool shouldReplicateInstance, PSObject ownerObject) { - if (settings is null) + if (settings == null) { return defaultValue; } @@ -1862,13 +1862,13 @@ internal static object GetNoteSettingValue(PSMemberSet settings, string noteName } PSNoteProperty note = settings.Members[noteName] as PSNoteProperty; - if (note is null) + if (note == null) { return defaultValue; } object noteValue = note.Value; - if (noteValue is null || noteValue.GetType() != expectedType) + if (noteValue == null || noteValue.GetType() != expectedType) { return defaultValue; } @@ -2046,7 +2046,7 @@ internal static void CopyDeserializerFields(PSObject source, PSObject target) target.ClrMembers = source.ClrMembers; } - if (target.ToStringFromDeserialization is null) + if (target.ToStringFromDeserialization == null) { target.ToStringFromDeserialization = source.ToStringFromDeserialization; target.TokenText = source.TokenText; @@ -2514,7 +2514,7 @@ private static void AddGenericArguments(StringBuilder sb, Type[] genericArgument internal static string Type(Type type, bool dropNamespaces = false, string key = null) { - if (type is null) + if (type == null) { return string.Empty; } @@ -2550,7 +2550,7 @@ internal static string Type(Type type, bool dropNamespaces = false, string key = else { result = TypeAccelerators.FindBuiltinAccelerator(type, key); - if (result is null) + if (result == null) { if (type == typeof(PSCustomObject)) { @@ -2564,7 +2564,7 @@ internal static string Type(Type type, bool dropNamespaces = false, string key = // For nested types, we should return OuterType+InnerType. For example, // System.Environment+SpecialFolder -> Environment+SpecialFolder string fullName = type.ToString(); - result = type.Namespace is null + result = type.Namespace == null ? fullName : fullName.Substring(type.Namespace.Length + 1); } @@ -2603,7 +2603,7 @@ internal static string Type(Type type, bool dropNamespaces = false, string key = /// Instance of PSObject wrapping a Type. public static string Type(PSObject instance) { - if (instance is null) + if (instance == null) { return string.Empty; } @@ -2618,7 +2618,7 @@ public static string Type(PSObject instance) public static string XmlNode(PSObject instance) { XmlNode node = (XmlNode)instance?.BaseObject; - if (node is null) + if (node == null) { return string.Empty; } @@ -2633,14 +2633,14 @@ public static string XmlNode(PSObject instance) public static string XmlNodeList(PSObject instance) { XmlNodeList nodes = (XmlNodeList)instance?.BaseObject; - if (nodes is null) + if (nodes == null) { return string.Empty; } if (nodes.Count == 1) { - if (nodes[0] is null) + if (nodes[0] == null) { return string.Empty; } diff --git a/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs b/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs index 77baee2486a..ee54859a1ea 100644 --- a/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs +++ b/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs @@ -169,7 +169,7 @@ public override Type ComponentType /// an or an . public override object GetValue(object component) { - if (component is null) + if (component == null) { throw PSTraceSource.NewArgumentNullException(nameof(component)); } @@ -179,7 +179,7 @@ public override object GetValue(object component) try { property = mshObj.Properties[this.Name] as PSPropertyInfo; - if (property is null) + if (property == null) { PSObjectTypeDescriptor.typeDescriptor.WriteLine("Could not find property \"{0}\" to get its value.", this.Name); ExtendedTypeSystemException e = new ExtendedTypeSystemException("PropertyNotFoundInPropertyDescriptorGetValue", @@ -216,10 +216,10 @@ private static PSObject GetComponentPSObject(object component) // If you use the PSObjectTypeDescriptor directly as your object, it will be the component // if you use a provider, the PSObject will be the component. PSObject mshObj = component as PSObject; - if (mshObj is null) + if (mshObj == null) { PSObjectTypeDescriptor descriptor = component as PSObjectTypeDescriptor; - if (descriptor is null) + if (descriptor == null) { throw PSTraceSource.NewArgumentException(nameof(component), ExtendedTypeSystem.InvalidComponent, "component", @@ -268,7 +268,7 @@ private object DealWithGetValueException(ExtendedTypeSystemException e, out bool /// public override void SetValue(object component, object value) { - if (component is null) + if (component == null) { throw PSTraceSource.NewArgumentNullException(nameof(component)); } @@ -277,7 +277,7 @@ public override void SetValue(object component, object value) try { PSPropertyInfo property = mshObj.Properties[this.Name] as PSPropertyInfo; - if (property is null) + if (property == null) { PSObjectTypeDescriptor.typeDescriptor.WriteLine("Could not find property \"{0}\" to set its value.", this.Name); ExtendedTypeSystemException e = new ExtendedTypeSystemException("PropertyNotFoundInPropertyDescriptorSetValue", @@ -384,7 +384,7 @@ private void CheckAndAddProperty(PSPropertyInfo propertyInfo, Attribute[] attrib if (property != null) { DotNetAdapter.PropertyCacheEntry propertyEntry = property.adapterData as DotNetAdapter.PropertyCacheEntry; - if (propertyEntry is null) + if (propertyEntry == null) { typeDescriptor.WriteLine("Skipping attribute check for property \"{0}\" because it is an adapted property (not a .NET property).", property.Name); } @@ -410,7 +410,7 @@ private void CheckAndAddProperty(PSPropertyInfo propertyInfo, Attribute[] attrib } } - if (propertyAttributes is null) + if (propertyAttributes == null) { propertyAttributes = new AttributeCollection(); } @@ -446,7 +446,7 @@ public override PropertyDescriptorCollection GetProperties(Attribute[] attribute using (typeDescriptor.TraceScope("Getting properties.")) { PropertyDescriptorCollection returnValue = new PropertyDescriptorCollection(null); - if (Instance is null) + if (Instance == null) { return returnValue; } @@ -468,12 +468,12 @@ public override PropertyDescriptorCollection GetProperties(Attribute[] attribute public override bool Equals(object obj) { PSObjectTypeDescriptor other = obj as PSObjectTypeDescriptor; - if (other is null) + if (other == null) { return false; } - if (this.Instance is null || other.Instance is null) + if (this.Instance == null || other.Instance == null) { return ReferenceEquals(this, other); } @@ -487,7 +487,7 @@ public override bool Equals(object obj) /// A hash code for the current object. public override int GetHashCode() { - if (this.Instance is null) + if (this.Instance == null) { return base.GetHashCode(); } @@ -501,7 +501,7 @@ public override int GetHashCode() /// An that represents the default property for this object, or a null reference (Nothing in Visual Basic) if this object does not have properties. public override PropertyDescriptor GetDefaultProperty() { - if (this.Instance is null) + if (this.Instance == null) { return null; } @@ -517,7 +517,7 @@ public override PropertyDescriptor GetDefaultProperty() } } - if (defaultProperty is null) + if (defaultProperty == null) { object[] defaultPropertyAttributes = this.Instance.BaseObject.GetType().GetCustomAttributes(typeof(DefaultPropertyAttribute), true); if (defaultPropertyAttributes.Length == 1) @@ -554,7 +554,7 @@ public override PropertyDescriptor GetDefaultProperty() /// A that is the converter for this object, or a null reference (Nothing in Visual Basic) if there is no for this object. public override TypeConverter GetConverter() { - if (this.Instance is null) + if (this.Instance == null) { // If we return null, some controls will have an exception saying that this // GetConverter returned an illegal value @@ -598,7 +598,7 @@ public override object GetPropertyOwner(PropertyDescriptor pd) /// An that represents the default event for this object, or a null reference (Nothing in Visual Basic) if this object does not have events. public override EventDescriptor GetDefaultEvent() { - if (this.Instance is null) + if (this.Instance == null) { return null; } @@ -612,7 +612,7 @@ public override EventDescriptor GetDefaultEvent() /// An that represents the events for this component instance. public override EventDescriptorCollection GetEvents() { - if (this.Instance is null) + if (this.Instance == null) { return new EventDescriptorCollection(null); } @@ -627,7 +627,7 @@ public override EventDescriptorCollection GetEvents() /// An that represents the events for this component instance that match the given set of attributes. public override EventDescriptorCollection GetEvents(Attribute[] attributes) { - if (this.Instance is null) + if (this.Instance == null) { return null; } @@ -641,7 +641,7 @@ public override EventDescriptorCollection GetEvents(Attribute[] attributes) /// An with the attributes for this object. public override AttributeCollection GetAttributes() { - if (this.Instance is null) + if (this.Instance == null) { return new AttributeCollection(); } @@ -655,7 +655,7 @@ public override AttributeCollection GetAttributes() /// The class name of the object, or a null reference (Nothing in Visual Basic) if the class does not have a name. public override string GetClassName() { - if (this.Instance is null) + if (this.Instance == null) { return null; } @@ -669,7 +669,7 @@ public override string GetClassName() /// The name of the object, or a null reference (Nothing in Visual Basic) if object does not have a name. public override string GetComponentName() { - if (this.Instance is null) + if (this.Instance == null) { return null; } @@ -684,7 +684,7 @@ public override string GetComponentName() /// An object of the specified type that is the editor for this object, or a null reference (Nothing in Visual Basic) if the editor cannot be found. public override object GetEditor(Type editorBaseType) { - if (this.Instance is null) + if (this.Instance == null) { return null; } diff --git a/src/System.Management.Automation/engine/MshSecurityException.cs b/src/System.Management.Automation/engine/MshSecurityException.cs index 498e23521ec..878de10e2b4 100644 --- a/src/System.Management.Automation/engine/MshSecurityException.cs +++ b/src/System.Management.Automation/engine/MshSecurityException.cs @@ -93,7 +93,7 @@ public override ErrorRecord ErrorRecord { get { - if (_errorRecord is null) + if (_errorRecord == null) { _errorRecord = new ErrorRecord( new ParentContainsErrorRecordException(this), diff --git a/src/System.Management.Automation/engine/MshSnapinQualifiedName.cs b/src/System.Management.Automation/engine/MshSnapinQualifiedName.cs index 86aed4ad1e3..b23df2202eb 100644 --- a/src/System.Management.Automation/engine/MshSnapinQualifiedName.cs +++ b/src/System.Management.Automation/engine/MshSnapinQualifiedName.cs @@ -66,7 +66,7 @@ private PSSnapinQualifiedName(string[] splitName) /// internal static PSSnapinQualifiedName? GetInstance(string? name) { - if (name is null) + if (name == null) return null; string[] splitName = name.Split(Utils.Separators.Backslash); if (splitName.Length == 0 || splitName.Length > 2) diff --git a/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs b/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs index e951f5b5f05..0091596a443 100644 --- a/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs +++ b/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs @@ -169,14 +169,14 @@ private void AppendOneNativeArgument(ExecutionContext context, object obj, Array { IEnumerator list = LanguagePrimitives.GetEnumerator(obj); - Diagnostics.Assert((argArrayAst is null) || obj is object[] && ((object[])obj).Length == argArrayAst.Elements.Count, "array argument and ArrayLiteralAst differ in number of elements"); + Diagnostics.Assert((argArrayAst == null) || obj is object[] && ((object[])obj).Length == argArrayAst.Elements.Count, "array argument and ArrayLiteralAst differ in number of elements"); int currentElement = -1; string separator = string.Empty; do { string arg; - if (list is null) + if (list == null) { arg = PSObject.ToStringParser(context, obj); } @@ -446,7 +446,7 @@ internal static bool NeedQuotes(string stringToCheck) private static string GetEnumerableArgSeparator(ArrayLiteralAst arrayLiteralAst, int index) { - if (arrayLiteralAst is null) return " "; + if (arrayLiteralAst == null) return " "; // index points to the *next* element, so we're looking for space between // it and the previous element. diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index 7d3ec0d2bfc..3a12dab6295 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -159,7 +159,7 @@ internal class NativeCommandProcessor : CommandProcessorBase internal NativeCommandProcessor(ApplicationInfo applicationInfo, ExecutionContext context) : base(applicationInfo) { - if (applicationInfo is null) + if (applicationInfo == null) { throw PSTraceSource.NewArgumentNullException(nameof(applicationInfo)); } @@ -270,7 +270,7 @@ internal NativeCommandParameterBinderController NativeParameterBinderController { get { - if (_nativeParameterBinderController is null) + if (_nativeParameterBinderController == null) { NewParameterBinderController(this.Command); } @@ -1283,7 +1283,7 @@ private void CalculateIORedirection(out bool redirectOutput, out bool redirectEr if (_runStandAlone) { - if (s_supportScreenScrape is null) + if (s_supportScreenScrape == null) { try { @@ -1609,7 +1609,7 @@ private List DeserializeCliXmlObject(string xml, bool isOut } // Null is allowed only in output stream - if (stream != MinishellStream.Output && obj is null) + if (stream != MinishellStream.Output && obj == null) { continue; } @@ -1729,7 +1729,7 @@ internal ProcessInputWriter(InternalCommand command) /// internal void Add(object input) { - if (_stopping || _streamWriter is null) + if (_stopping || _streamWriter == null) { // if _streamWriter is already null, then we already called Dispose() // so we should just discard the input. @@ -1890,7 +1890,7 @@ internal void Done() } else // Text { - // if _pipeline is null, we already called Dispose(), + // if _pipeline == null, we already called Dispose(), // for example, because downstream process finished if (_pipeline != null) { diff --git a/src/System.Management.Automation/engine/PSClassSearcher.cs b/src/System.Management.Automation/engine/PSClassSearcher.cs index 7bb815ba6e9..613035820d0 100644 --- a/src/System.Management.Automation/engine/PSClassSearcher.cs +++ b/src/System.Management.Automation/engine/PSClassSearcher.cs @@ -132,7 +132,7 @@ private PSClassInfo GetNextClass() PSClassInfo returnValue = null; WildcardPattern classNameMatcher = WildcardPattern.Get(_className, WildcardOptions.IgnoreCase); - if (_matchingClassList is null) + if (_matchingClassList == null) { _matchingClassList = new Collection(); diff --git a/src/System.Management.Automation/engine/PSConfiguration.cs b/src/System.Management.Automation/engine/PSConfiguration.cs index 8912dd3c3fa..aacf5c50e32 100644 --- a/src/System.Management.Automation/engine/PSConfiguration.cs +++ b/src/System.Management.Automation/engine/PSConfiguration.cs @@ -388,7 +388,7 @@ private T ReadValueFromFile(ConfigScope scope, string key, T defaultValue = d string fileName = GetConfigFilePath(scope); JObject configData = configRoots[(int)scope]; - if (configData is null) + if (configData == null) { if (File.Exists(fileName)) { @@ -487,7 +487,7 @@ private void UpdateValueInFile(ConfigScope scope, string key, T value, bool a jsonObject = serializer.Deserialize(jsonReader); JProperty propertyToModify = jsonObject.Property(key); - if (propertyToModify is null) + if (propertyToModify == null) { // The property doesn't exist, so add it if (addValue) diff --git a/src/System.Management.Automation/engine/PSVersionInfo.cs b/src/System.Management.Automation/engine/PSVersionInfo.cs index 3e31e1ac0f9..09f9829c289 100644 --- a/src/System.Management.Automation/engine/PSVersionInfo.cs +++ b/src/System.Management.Automation/engine/PSVersionInfo.cs @@ -563,7 +563,7 @@ public SemanticVersion(int major) : this(major, 0, 0) { } /// public SemanticVersion(Version version) { - if (version is null) throw PSTraceSource.NewArgumentNullException(nameof(version)); + if (version == null) throw PSTraceSource.NewArgumentNullException(nameof(version)); if (version.Revision > 0) throw PSTraceSource.NewArgumentException(nameof(version)); Major = version.Major; @@ -651,7 +651,7 @@ public static implicit operator Version(SemanticVersion semver) /// public static SemanticVersion Parse(string version) { - if (version is null) throw PSTraceSource.NewArgumentNullException(nameof(version)); + if (version == null) throw PSTraceSource.NewArgumentNullException(nameof(version)); if (version == string.Empty) throw new FormatException(nameof(version)); var r = new VersionResult(); @@ -709,14 +709,14 @@ private static bool TryParseVersion(string version, ref VersionResult result) // 'PreReleaseLabel' can contains dashes. if (plusIndex == -1) { - // No buildLabel: buildLabel is null + // No buildLabel: buildLabel == null // Format is 'major.minor.patch-PreReleaseLabel' preLabel = version.Substring(dashIndex + 1); versionSansLabel = version.Substring(0, dashIndex); } else { - // No PreReleaseLabel: preLabel is null + // No PreReleaseLabel: preLabel == null // Format is 'major.minor.patch+BuildLabel' buildLabel = version.Substring(plusIndex + 1); versionSansLabel = version.Substring(0, plusIndex); @@ -728,8 +728,8 @@ private static bool TryParseVersion(string version, ref VersionResult result) if (dashIndex == -1) { // Here dashIndex == plusIndex == -1 - // No preLabel - preLabel is null; - // No buildLabel - buildLabel is null; + // No preLabel - preLabel == null; + // No buildLabel - buildLabel == null; // Format is 'major.minor.patch' versionSansLabel = version; } @@ -794,7 +794,7 @@ private static bool TryParseVersion(string version, ref VersionResult result) /// public override string ToString() { - if (versionString is null) + if (versionString == null) { StringBuilder result = new StringBuilder(); @@ -839,13 +839,13 @@ public static int Compare(SemanticVersion versionA, SemanticVersion versionB) /// public int CompareTo(object version) { - if (version is null) + if (version == null) { return 1; } var v = version as SemanticVersion; - if (v is null) + if (v == null) { throw PSTraceSource.NewArgumentException(nameof(version)); } @@ -859,7 +859,7 @@ public int CompareTo(object version) /// public int CompareTo(SemanticVersion value) { - if ((object)value is null) + if ((object)value == null) return 1; if (Major != value.Major) diff --git a/src/System.Management.Automation/engine/ParameterBinderBase.cs b/src/System.Management.Automation/engine/ParameterBinderBase.cs index 79176966a2c..4dcb5488041 100644 --- a/src/System.Management.Automation/engine/ParameterBinderBase.cs +++ b/src/System.Management.Automation/engine/ParameterBinderBase.cs @@ -232,7 +232,7 @@ private void ValidatePSTypeName( Dbg.Assert(parameter != null, "Caller should verify parameter != null"); Dbg.Assert(parameterMetadata != null, "Caller should verify parameterMetadata != null"); - if (parameterValue is null) + if (parameterValue == null) { return; } @@ -335,12 +335,12 @@ internal virtual bool BindParameter( bool coerceTypeIfNeeded = (flags & ParameterBindingFlags.ShouldCoerceType) != 0; bool isDefaultValue = (flags & ParameterBindingFlags.IsDefaultValue) != 0; - if (parameter is null) + if (parameter == null) { throw PSTraceSource.NewArgumentNullException(nameof(parameter)); } - if (parameterMetadata is null) + if (parameterMetadata == null) { throw PSTraceSource.NewArgumentNullException(nameof(parameterMetadata)); } @@ -439,7 +439,7 @@ internal virtual bool BindParameter( GetErrorExtent(parameter), parameterMetadata.Name, parameterMetadata.Type, - (parameterValue is null) ? null : parameterValue.GetType(), + (parameterValue == null) ? null : parameterValue.GetType(), ParameterBinderStrings.ParameterArgumentTransformationError, "ParameterArgumentTransformationError", e.Message); @@ -522,7 +522,7 @@ internal virtual bool BindParameter( GetErrorExtent(parameter), parameterMetadata.Name, parameterMetadata.Type, - (parameterValue is null) ? null : parameterValue.GetType(), + (parameterValue == null) ? null : parameterValue.GetType(), ParameterBinderStrings.ParameterArgumentValidationError, "ParameterArgumentValidationError", e.Message); @@ -586,7 +586,7 @@ internal virtual bool BindParameter( if (bindError != null) { - Type specifiedType = (parameterValue is null) ? null : parameterValue.GetType(); + Type specifiedType = (parameterValue == null) ? null : parameterValue.GetType(); ParameterBindingException bindingException = new ParameterBindingException( bindError, @@ -694,7 +694,7 @@ private void ValidateNullOrEmptyArgument( object parameterValue, bool recurseIntoCollections) { - if (parameterValue is null && argumentType != typeof(bool?)) + if (parameterValue == null && argumentType != typeof(bool?)) { if (!parameterMetadata.AllowsNullArgument) { @@ -736,7 +736,7 @@ private void ValidateNullOrEmptyArgument( GetErrorExtent(parameter), parameterMetadata.Name, parameterMetadata.Type, - (parameterValue is null) ? null : parameterValue.GetType(), + (parameterValue == null) ? null : parameterValue.GetType(), ParameterBinderStrings.ParameterArgumentValidationErrorEmptyStringNotAllowed, "ParameterArgumentValidationErrorEmptyStringNotAllowed"); throw bindingException; @@ -813,7 +813,7 @@ private void ValidateNullOrEmptyArgument( GetErrorExtent(parameter), parameterMetadata.Name, parameterMetadata.Type, - (parameterValue is null) ? null : parameterValue.GetType(), + (parameterValue == null) ? null : parameterValue.GetType(), resourceString, errorId); throw bindingException; @@ -829,9 +829,9 @@ private bool ShouldContinueUncoercedBind( bool isDefaultValue = (flags & ParameterBindingFlags.IsDefaultValue) != 0; Type parameterType = parameterMetadata.Type; - if (parameterValue is null) + if (parameterValue == null) { - return parameterType is null || + return parameterType == null || isDefaultValue || (!parameterType.IsValueType && parameterType != typeof(string)); @@ -883,7 +883,7 @@ private bool ShouldContinueUncoercedBind( false, out coercionRequired); - if (encodedValue is null || coercionRequired) + if (encodedValue == null || coercionRequired) { // Don't attempt the bind because the // PSObject BaseObject is not of the correct @@ -987,19 +987,19 @@ private object CoerceTypeAsNeeded( ParameterCollectionTypeInformation collectionTypeInfo, object currentValue) { - if (argument is null) + if (argument == null) { throw PSTraceSource.NewArgumentNullException(nameof(argument)); } - if (toType is null) + if (toType == null) { throw PSTraceSource.NewArgumentNullException(nameof(toType)); } // Construct the collection type information if it wasn't passed in. - if (collectionTypeInfo is null) + if (collectionTypeInfo == null) { collectionTypeInfo = new ParameterCollectionTypeInformation(toType); } @@ -1272,7 +1272,7 @@ private object CoerceTypeAsNeeded( bindingTracer.WriteLine( "CONVERT SUCCESSFUL using LanguagePrimitives.ConvertTo: [{0}]", - (result is null) ? "null" : result.ToString()); + (result == null) ? "null" : result.ToString()); } while (false); } catch (NotSupportedException notSupported) @@ -1335,7 +1335,7 @@ private static bool IsNullParameterValue(object currentValue) { bool result = false; - if (currentValue is null || + if (currentValue == null || currentValue == AutomationNull.Value || currentValue == UnboundParameter.Value) { @@ -1471,13 +1471,13 @@ private object EncodeCollection( bindingTracer.WriteLine( "Binding collection parameter {0}: argument type [{1}], parameter type [{2}], collection type {3}, element type [{4}], {5}", parameterName, - (currentValue is null) ? "null" : currentValue.GetType().Name, + (currentValue == null) ? "null" : currentValue.GetType().Name, toType, collectionTypeInformation.ParameterCollectionType, collectionTypeInformation.ElementType, coerceElementTypeIfNeeded ? "coerceElementType" : "no coerceElementType"); - if (currentValue is null) + if (currentValue == null) { break; } @@ -1590,7 +1590,7 @@ private object EncodeCollection( getMethodError = e; } - if (addMethod is null) + if (addMethod == null) { ParameterBindingException bindingException = new ParameterBindingException( @@ -1603,7 +1603,7 @@ private object EncodeCollection( currentValue.GetType(), ParameterBinderStrings.CannotExtractAddMethod, "CannotExtractAddMethod", - (getMethodError is null) ? string.Empty : getMethodError.Message); + (getMethodError == null) ? string.Empty : getMethodError.Message); throw bindingException; } } @@ -1702,7 +1702,7 @@ private object EncodeCollection( { bindingTracer.WriteLine( "COERCE collection element from type {0} to type {1}", - (valueElement is null) ? "null" : valueElement.GetType().Name, + (valueElement == null) ? "null" : valueElement.GetType().Name, collectionElementType); // Coerce the element to the appropriate type. @@ -1727,7 +1727,7 @@ private object EncodeCollection( { bindingTracer.WriteLine( "COERCION REQUIRED: Did not attempt to coerce collection element from type {0} to type {1}", - (valueElement is null) ? "null" : valueElement.GetType().Name, + (valueElement == null) ? "null" : valueElement.GetType().Name, collectionElementType); coercionRequired = true; @@ -1744,7 +1744,7 @@ private object EncodeCollection( { bindingTracer.WriteLine( "Adding element of type {0} to array position {1}", - (currentValueElement is null) ? "null" : currentValueElement.GetType().Name, + (currentValueElement == null) ? "null" : currentValueElement.GetType().Name, arrayIndex); resultAsIList[arrayIndex++] = currentValueElement; } @@ -1752,14 +1752,14 @@ private object EncodeCollection( { bindingTracer.WriteLine( "Adding element of type {0} via IList.Add", - (currentValueElement is null) ? "null" : currentValueElement.GetType().Name); + (currentValueElement == null) ? "null" : currentValueElement.GetType().Name); resultAsIList.Add(currentValueElement); } else { bindingTracer.WriteLine( "Adding element of type {0} via ICollection::Add()", - (currentValueElement is null) ? "null" : currentValueElement.GetType().Name); + (currentValueElement == null) ? "null" : currentValueElement.GetType().Name); addMethod.Invoke(resultCollection, new object[1] { currentValueElement }); } } @@ -1781,7 +1781,7 @@ private object EncodeCollection( GetErrorExtent(argument), parameterName, toType, - (currentValueElement is null) ? null : currentValueElement.GetType(), + (currentValueElement == null) ? null : currentValueElement.GetType(), ParameterBinderStrings.CannotConvertArgument, "CannotConvertArgument", currentValueElement ?? "null", @@ -1790,7 +1790,7 @@ private object EncodeCollection( } } } - else // (currentValueAsIList is null) + else // (currentValueAsIList == null) { bindingTracer.WriteLine( "Argument type {0} is not IList, treating this as scalar", @@ -1841,7 +1841,7 @@ private object EncodeCollection( { bindingTracer.WriteLine( "Adding scalar element of type {0} to array position {1}", - (currentValue is null) ? "null" : currentValue.GetType().Name, + (currentValue == null) ? "null" : currentValue.GetType().Name, 0); resultAsIList[0] = currentValue; } @@ -1849,14 +1849,14 @@ private object EncodeCollection( { bindingTracer.WriteLine( "Adding scalar element of type {0} via IList.Add", - (currentValue is null) ? "null" : currentValue.GetType().Name); + (currentValue == null) ? "null" : currentValue.GetType().Name); resultAsIList.Add(currentValue); } else { bindingTracer.WriteLine( "Adding scalar element of type {0} via ICollection::Add()", - (currentValue is null) ? "null" : currentValue.GetType().Name); + (currentValue == null) ? "null" : currentValue.GetType().Name); addMethod.Invoke(resultCollection, new object[1] { currentValue }); } } @@ -1878,7 +1878,7 @@ private object EncodeCollection( GetErrorExtent(argument), parameterName, toType, - (currentValue is null) ? null : currentValue.GetType(), + (currentValue == null) ? null : currentValue.GetType(), ParameterBinderStrings.CannotConvertArgument, "CannotConvertArgument", currentValue ?? "null", @@ -2022,7 +2022,7 @@ internal void SetPSBoundParametersVariable(ExecutionContext context) internal void SetImplicitUsingParameters(object obj) { _dictionary.ImplicitUsingParameters = PSObject.Base(obj) as IDictionary; - if (_dictionary.ImplicitUsingParameters is null) + if (_dictionary.ImplicitUsingParameters == null) { // Handle downlevel V4 case where using parameters are passed as an array list. IList implicitArrayUsingParameters = PSObject.Base(obj) as IList; diff --git a/src/System.Management.Automation/engine/ParameterBinderController.cs b/src/System.Management.Automation/engine/ParameterBinderController.cs index d69291bb2ca..a68192c7a90 100644 --- a/src/System.Management.Automation/engine/ParameterBinderController.cs +++ b/src/System.Management.Automation/engine/ParameterBinderController.cs @@ -159,7 +159,7 @@ internal void ReparseUnboundArguments() true, new InvocationInfo(this.InvocationInfo.MyCommand, argument.ParameterExtent)); - if (matchingParameter is null) + if (matchingParameter == null) { // Since we couldn't find a match, just add the argument as it was // and continue @@ -618,7 +618,7 @@ out ParameterBindingException outgoingBindingException result, ref unboundArgumentsIndex); - if (argument is null) + if (argument == null) { break; } @@ -870,7 +870,7 @@ out ParameterBindingException bindingException /// protected void ThrowElaboratedBindingException(ParameterBindingException pbex) { - if (pbex is null) + if (pbex == null) { throw PSTraceSource.NewArgumentNullException(nameof(pbex)); } diff --git a/src/System.Management.Automation/engine/ParameterInfo.cs b/src/System.Management.Automation/engine/ParameterInfo.cs index 1bb9b875e31..cf1784a7b62 100644 --- a/src/System.Management.Automation/engine/ParameterInfo.cs +++ b/src/System.Management.Automation/engine/ParameterInfo.cs @@ -30,7 +30,7 @@ internal CommandParameterInfo( CompiledCommandParameter parameter, uint parameterSetFlag) { - if (parameter is null) + if (parameter == null) { throw PSTraceSource.NewArgumentNullException(nameof(parameter)); } diff --git a/src/System.Management.Automation/engine/ParameterSetInfo.cs b/src/System.Management.Automation/engine/ParameterSetInfo.cs index c328d4f8883..c166f749b1c 100644 --- a/src/System.Management.Automation/engine/ParameterSetInfo.cs +++ b/src/System.Management.Automation/engine/ParameterSetInfo.cs @@ -55,7 +55,7 @@ internal CommandParameterSetInfo( throw PSTraceSource.NewArgumentException(nameof(name)); } - if (parameterMetadata is null) + if (parameterMetadata == null) { throw PSTraceSource.NewArgumentNullException(nameof(parameterMetadata)); } @@ -168,7 +168,7 @@ internal void GenerateParametersInDisplayOrder( foreach (CommandParameterInfo parameter in sortedPositionalParameters) { - if (parameter is null) + if (parameter == null) { continue; } @@ -179,7 +179,7 @@ internal void GenerateParametersInDisplayOrder( // Now convert the named mandatory parameters into a string foreach (CommandParameterInfo parameter in namedMandatoryParameters) { - if (parameter is null) + if (parameter == null) { continue; } @@ -192,7 +192,7 @@ internal void GenerateParametersInDisplayOrder( // Now convert the named parameters into a string foreach (CommandParameterInfo parameter in namedParameters) { - if (parameter is null) + if (parameter == null) { continue; } diff --git a/src/System.Management.Automation/engine/ParameterSetSpecificMetadata.cs b/src/System.Management.Automation/engine/ParameterSetSpecificMetadata.cs index c25b32d3ebc..4cc4ca7540e 100644 --- a/src/System.Management.Automation/engine/ParameterSetSpecificMetadata.cs +++ b/src/System.Management.Automation/engine/ParameterSetSpecificMetadata.cs @@ -19,7 +19,7 @@ internal class ParameterSetSpecificMetadata /// internal ParameterSetSpecificMetadata(ParameterAttribute attribute) { - if (attribute is null) + if (attribute == null) { throw PSTraceSource.NewArgumentNullException(nameof(attribute)); } diff --git a/src/System.Management.Automation/engine/PathInterfaces.cs b/src/System.Management.Automation/engine/PathInterfaces.cs index 4ab103aad70..d11a225797e 100644 --- a/src/System.Management.Automation/engine/PathInterfaces.cs +++ b/src/System.Management.Automation/engine/PathInterfaces.cs @@ -38,7 +38,7 @@ private PathIntrinsics() /// internal PathIntrinsics(SessionStateInternal sessionState) { - if (sessionState is null) + if (sessionState == null) { throw PSTraceSource.NewArgumentNullException(nameof(sessionState)); } diff --git a/src/System.Management.Automation/engine/Pipe.cs b/src/System.Management.Automation/engine/Pipe.cs index a82c8bc090d..ac9350487a0 100644 --- a/src/System.Management.Automation/engine/Pipe.cs +++ b/src/System.Management.Automation/engine/Pipe.cs @@ -44,7 +44,7 @@ internal CommandProcessorBase DownstreamCmdlet set { - Diagnostics.Assert(_resultList is null, "Tried to set downstream cmdlet when _resultList not null"); + Diagnostics.Assert(_resultList == null, "Tried to set downstream cmdlet when _resultList not null"); _downstreamCmdlet = value; } } @@ -80,7 +80,7 @@ internal PipelineWriter ExternalWriter set { - Diagnostics.Assert(_resultList is null, "Tried to set Pipe ExternalWriter when resultList not null"); + Diagnostics.Assert(_resultList == null, "Tried to set Pipe ExternalWriter when resultList not null"); _externalWriter = value; } } @@ -217,7 +217,7 @@ internal void AddVariableList(VariableStreamKind kind, IList list) switch (kind) { case VariableStreamKind.Error: - if (_errorVariableList is null) + if (_errorVariableList == null) { _errorVariableList = new List(); } @@ -225,7 +225,7 @@ internal void AddVariableList(VariableStreamKind kind, IList list) _errorVariableList.Add(list); break; case VariableStreamKind.Warning: - if (_warningVariableList is null) + if (_warningVariableList == null) { _warningVariableList = new List(); } @@ -233,7 +233,7 @@ internal void AddVariableList(VariableStreamKind kind, IList list) _warningVariableList.Add(list); break; case VariableStreamKind.Output: - if (_outVariableList is null) + if (_outVariableList == null) { _outVariableList = new List(); } @@ -241,7 +241,7 @@ internal void AddVariableList(VariableStreamKind kind, IList list) _outVariableList.Add(list); break; case VariableStreamKind.Information: - if (_informationVariableList is null) + if (_informationVariableList == null) { _informationVariableList = new List(); } @@ -485,7 +485,7 @@ internal void AddItems(object objects) IEnumerator ie = LanguagePrimitives.GetEnumerator(objects); try { - if (ie is null) + if (ie == null) { Add(objects); } @@ -600,7 +600,7 @@ internal void Clear() /// Possibly empty array of objects, but not null. internal object[] ToArray() { - if (ObjectQueue is null || ObjectQueue.Count == 0) + if (ObjectQueue == null || ObjectQueue.Count == 0) return MshCommandRuntime.StaticEmptyArray; return ObjectQueue.ToArray(); diff --git a/src/System.Management.Automation/engine/ProgressRecord.cs b/src/System.Management.Automation/engine/ProgressRecord.cs index 6765663126d..f040e24e416 100644 --- a/src/System.Management.Automation/engine/ProgressRecord.cs +++ b/src/System.Management.Automation/engine/ProgressRecord.cs @@ -472,7 +472,7 @@ internal static int GetPercentageComplete(DateTime startTime, TimeSpan expectedD /// internal static ProgressRecord FromPSObjectForRemoting(PSObject progressAsPSObject) { - if (progressAsPSObject is null) + if (progressAsPSObject == null) { throw PSTraceSource.NewArgumentNullException(nameof(progressAsPSObject)); } diff --git a/src/System.Management.Automation/engine/PropertyCmdletProviderInterfaces.cs b/src/System.Management.Automation/engine/PropertyCmdletProviderInterfaces.cs index 469b70aaede..9c1f9379190 100644 --- a/src/System.Management.Automation/engine/PropertyCmdletProviderInterfaces.cs +++ b/src/System.Management.Automation/engine/PropertyCmdletProviderInterfaces.cs @@ -36,7 +36,7 @@ private PropertyCmdletProviderIntrinsics() /// internal PropertyCmdletProviderIntrinsics(Cmdlet cmdlet) { - if (cmdlet is null) + if (cmdlet == null) { throw PSTraceSource.NewArgumentNullException(nameof(cmdlet)); } @@ -56,7 +56,7 @@ internal PropertyCmdletProviderIntrinsics(Cmdlet cmdlet) /// internal PropertyCmdletProviderIntrinsics(SessionStateInternal sessionState) { - if (sessionState is null) + if (sessionState == null) { throw PSTraceSource.NewArgumentNullException(nameof(sessionState)); } diff --git a/src/System.Management.Automation/engine/ProviderInterfaces.cs b/src/System.Management.Automation/engine/ProviderInterfaces.cs index c03b30fcc83..27e2680af5c 100644 --- a/src/System.Management.Automation/engine/ProviderInterfaces.cs +++ b/src/System.Management.Automation/engine/ProviderInterfaces.cs @@ -38,7 +38,7 @@ private CmdletProviderManagementIntrinsics() /// internal CmdletProviderManagementIntrinsics(SessionStateInternal sessionState) { - if (sessionState is null) + if (sessionState == null) { throw PSTraceSource.NewArgumentNullException(nameof(sessionState)); } diff --git a/src/System.Management.Automation/engine/ProxyCommand.cs b/src/System.Management.Automation/engine/ProxyCommand.cs index 55ce7c64bfc..1bb3d15baf3 100644 --- a/src/System.Management.Automation/engine/ProxyCommand.cs +++ b/src/System.Management.Automation/engine/ProxyCommand.cs @@ -39,7 +39,7 @@ private ProxyCommand() /// public static string Create(CommandMetadata commandMetadata) { - if (commandMetadata is null) + if (commandMetadata == null) { throw PSTraceSource.NewArgumentNullException("commandMetaData"); } @@ -65,7 +65,7 @@ public static string Create(CommandMetadata commandMetadata) /// public static string Create(CommandMetadata commandMetadata, string helpComment) { - if (commandMetadata is null) + if (commandMetadata == null) { throw PSTraceSource.NewArgumentNullException("commandMetaData"); } @@ -95,7 +95,7 @@ public static string Create(CommandMetadata commandMetadata, string helpComment) /// public static string Create(CommandMetadata commandMetadata, string helpComment, bool generateDynamicParameters) { - if (commandMetadata is null) + if (commandMetadata == null) { throw PSTraceSource.NewArgumentNullException("commandMetaData"); } @@ -118,7 +118,7 @@ public static string Create(CommandMetadata commandMetadata, string helpComment, /// public static string GetCmdletBindingAttribute(CommandMetadata commandMetadata) { - if (commandMetadata is null) + if (commandMetadata == null) { throw PSTraceSource.NewArgumentNullException("commandMetaData"); } @@ -143,7 +143,7 @@ public static string GetCmdletBindingAttribute(CommandMetadata commandMetadata) [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] public static string GetParamBlock(CommandMetadata commandMetadata) { - if (commandMetadata is null) + if (commandMetadata == null) { throw PSTraceSource.NewArgumentNullException("commandMetaData"); } @@ -167,7 +167,7 @@ public static string GetParamBlock(CommandMetadata commandMetadata) /// public static string GetBegin(CommandMetadata commandMetadata) { - if (commandMetadata is null) + if (commandMetadata == null) { throw PSTraceSource.NewArgumentNullException("commandMetaData"); } @@ -191,7 +191,7 @@ public static string GetBegin(CommandMetadata commandMetadata) /// public static string GetProcess(CommandMetadata commandMetadata) { - if (commandMetadata is null) + if (commandMetadata == null) { throw PSTraceSource.NewArgumentNullException("commandMetaData"); } @@ -215,7 +215,7 @@ public static string GetProcess(CommandMetadata commandMetadata) /// public static string GetDynamicParam(CommandMetadata commandMetadata) { - if (commandMetadata is null) + if (commandMetadata == null) { throw PSTraceSource.NewArgumentNullException("commandMetaData"); } @@ -239,7 +239,7 @@ public static string GetDynamicParam(CommandMetadata commandMetadata) /// public static string GetEnd(CommandMetadata commandMetadata) { - if (commandMetadata is null) + if (commandMetadata == null) { throw PSTraceSource.NewArgumentNullException("commandMetaData"); } @@ -352,7 +352,7 @@ private static void AppendType(StringBuilder sb, string section, PSObject parent /// When the help argument is not recognized as a HelpInfo object. public static string GetHelpComments(PSObject help) { - if (help is null) + if (help == null) { throw new ArgumentNullException(nameof(help)); } diff --git a/src/System.Management.Automation/engine/PseudoParameterBinder.cs b/src/System.Management.Automation/engine/PseudoParameterBinder.cs index ab74c899e60..bddbe643f59 100644 --- a/src/System.Management.Automation/engine/PseudoParameterBinder.cs +++ b/src/System.Management.Automation/engine/PseudoParameterBinder.cs @@ -36,8 +36,8 @@ internal RuntimeDefinedParameterBinder( { string key = pair.Key; RuntimeDefinedParameter pp = pair.Value; - string ppName = (pp is null) ? null : pp.Name; - if (pp is null || key != ppName) + string ppName = (pp == null) ? null : pp.Name; + if (pp == null || key != ppName) { ParameterBindingException bindingException = new ParameterBindingException( diff --git a/src/System.Management.Automation/engine/PseudoParameters.cs b/src/System.Management.Automation/engine/PseudoParameters.cs index bb9ff5d4a3e..78ef034cf5b 100644 --- a/src/System.Management.Automation/engine/PseudoParameters.cs +++ b/src/System.Management.Automation/engine/PseudoParameters.cs @@ -56,7 +56,7 @@ public RuntimeDefinedParameter(string name, Type parameterType, Collection GetSetter(Type type, string property) var propertyExpr = GetPropertyOrFieldExpr(type, property, Expression.Convert(target, type)); Expression expr = Expression.Assign(propertyExpr, Expression.Convert(value, propertyExpr.Type)); - if (propertyExpr.Type.IsValueType && Nullable.GetUnderlyingType(propertyExpr.Type) is null) + if (propertyExpr.Type.IsValueType && Nullable.GetUnderlyingType(propertyExpr.Type) == null) { var throwInvalidCastExceptionExpr = Expression.Call(Language.CachedReflectionInfo.LanguagePrimitives_ThrowInvalidCastException, diff --git a/src/System.Management.Automation/engine/ScopedItemSearcher.cs b/src/System.Management.Automation/engine/ScopedItemSearcher.cs index c2ea4ff9c10..4d5f2f1107f 100644 --- a/src/System.Management.Automation/engine/ScopedItemSearcher.cs +++ b/src/System.Management.Automation/engine/ScopedItemSearcher.cs @@ -33,12 +33,12 @@ internal ScopedItemSearcher( SessionStateInternal sessionState, VariablePath lookupPath) { - if (sessionState is null) + if (sessionState == null) { throw PSTraceSource.NewArgumentNullException(nameof(sessionState)); } - if (lookupPath is null) + if (lookupPath == null) { throw PSTraceSource.NewArgumentNullException(nameof(lookupPath)); } @@ -286,7 +286,7 @@ protected override bool GetScopeItem( // isn't the current scope, claim that the variable // doesn't exist so that the lookup continues. - if (variable is null || + if (variable == null || (variable.IsPrivate && scope != sessionState.CurrentScope)) { @@ -339,7 +339,7 @@ protected override bool GetScopeItem( // isn't the current scope, claim that the alias // doesn't exist so that the lookup continues. - if (alias is null || + if (alias == null || ((alias.Options & ScopedItemOptions.Private) != 0 && scope != sessionState.CurrentScope)) { @@ -477,7 +477,7 @@ protected override bool GetScopeItem( bool result = true; drive = scope.GetDrive(name.DriveName); - if (drive is null) + if (drive == null) { result = false; } diff --git a/src/System.Management.Automation/engine/ScriptCommandProcessor.cs b/src/System.Management.Automation/engine/ScriptCommandProcessor.cs index dfe7d49906c..89e898a5532 100644 --- a/src/System.Management.Automation/engine/ScriptCommandProcessor.cs +++ b/src/System.Management.Automation/engine/ScriptCommandProcessor.cs @@ -71,7 +71,7 @@ internal ScriptParameterBinderController ScriptParameterBinderController { get { - if (_scriptParameterBinderController is null) + if (_scriptParameterBinderController == null) { // Set up the hashtable that will be used to hold all of the bound parameters... _scriptParameterBinderController = @@ -145,7 +145,7 @@ internal override bool IsHelpRequested(out string helpTarget, out HelpCategory h string unused; HelpInfo helpInfo = _scriptBlock.GetHelpInfo(context: Context, commandInfo: CommandInfo, dontSearchOnRemoteComputer: false, scriptBlockTokenCache: scriptBlockTokenCache, helpFile: out unused, helpUriFromDotLink: out unused); - if (helpInfo is null) + if (helpInfo == null) { break; } @@ -279,7 +279,7 @@ private void Init() if (UseLocalScope) { - Diagnostics.Assert(CommandScope.LocalsTuple is null, "a newly created scope shouldn't have it's tuple set."); + Diagnostics.Assert(CommandScope.LocalsTuple == null, "a newly created scope shouldn't have it's tuple set."); CommandScope.LocalsTuple = _localsTuple; } } @@ -381,7 +381,7 @@ internal override void ProcessRecord() { // accumulate the input when working in "synchronous" mode Debug.Assert(this.Command.MyInvocation.PipelineIterationInfo != null); // this should have been allocated when the pipe was started - if (this.CommandRuntime.InputPipe.ExternalReader is null) + if (this.CommandRuntime.InputPipe.ExternalReader == null) { while (Read()) { @@ -410,7 +410,7 @@ internal override void Complete() if (_scriptBlock.HasEndBlock) { var endBlock = _runOptimizedCode ? _scriptBlock.EndBlock : _scriptBlock.UnoptimizedEndBlock; - if (this.CommandRuntime.InputPipe.ExternalReader is null) + if (this.CommandRuntime.InputPipe.ExternalReader == null) { if (IsPipelineInputExpected()) { @@ -529,7 +529,7 @@ private void RunClause(Action clause, object dollarUnderbar, ob if (inputToProcess != AutomationNull.Value) { - if (inputToProcess is null) + if (inputToProcess == null) { inputToProcess = MshCommandRuntime.StaticEmptyArray.GetEnumerator(); } diff --git a/src/System.Management.Automation/engine/ScriptInfo.cs b/src/System.Management.Automation/engine/ScriptInfo.cs index 7023b874d00..7a5112a341d 100644 --- a/src/System.Management.Automation/engine/ScriptInfo.cs +++ b/src/System.Management.Automation/engine/ScriptInfo.cs @@ -31,7 +31,7 @@ public class ScriptInfo : CommandInfo, IScriptCommandInfo internal ScriptInfo(string name, ScriptBlock script, ExecutionContext context) : base(name, CommandTypes.Script, context) { - if (script is null) + if (script == null) { throw PSTraceSource.NewArgumentException(nameof(script)); } diff --git a/src/System.Management.Automation/engine/SecurityDescriptorCmdletProviderInterfaces.cs b/src/System.Management.Automation/engine/SecurityDescriptorCmdletProviderInterfaces.cs index 6c0e6279b86..826fff642c3 100644 --- a/src/System.Management.Automation/engine/SecurityDescriptorCmdletProviderInterfaces.cs +++ b/src/System.Management.Automation/engine/SecurityDescriptorCmdletProviderInterfaces.cs @@ -34,7 +34,7 @@ private SecurityDescriptorCmdletProviderIntrinsics() /// internal SecurityDescriptorCmdletProviderIntrinsics(Cmdlet cmdlet) { - if (cmdlet is null) + if (cmdlet == null) { throw PSTraceSource.NewArgumentNullException(nameof(cmdlet)); } @@ -52,7 +52,7 @@ internal SecurityDescriptorCmdletProviderIntrinsics(Cmdlet cmdlet) /// internal SecurityDescriptorCmdletProviderIntrinsics(SessionStateInternal sessionState) { - if (sessionState is null) + if (sessionState == null) { throw PSTraceSource.NewArgumentNullException(nameof(sessionState)); } diff --git a/src/System.Management.Automation/engine/SessionState.cs b/src/System.Management.Automation/engine/SessionState.cs index af3886ba708..f011a87a2aa 100644 --- a/src/System.Management.Automation/engine/SessionState.cs +++ b/src/System.Management.Automation/engine/SessionState.cs @@ -54,7 +54,7 @@ internal SessionStateInternal(ExecutionContext context) : this(null, false, cont internal SessionStateInternal(SessionStateInternal parent, bool linkToGlobal, ExecutionContext context) { - if (context is null) + if (context == null) { throw PSTraceSource.NewArgumentNullException(nameof(context)); } @@ -392,7 +392,7 @@ internal SessionStateEntryVisibility CheckApplicationVisibility(string applicati private SessionStateEntryVisibility checkPathVisibility(List list, string path) { - if (list is null || list.Count == 0) return SessionStateEntryVisibility.Private; + if (list == null || list.Count == 0) return SessionStateEntryVisibility.Private; if (string.IsNullOrEmpty(path)) return SessionStateEntryVisibility.Private; if (list.Contains("*")) return SessionStateEntryVisibility.Public; diff --git a/src/System.Management.Automation/engine/SessionStateAliasAPIs.cs b/src/System.Management.Automation/engine/SessionStateAliasAPIs.cs index 7d6e9b9137a..17ed891f862 100644 --- a/src/System.Management.Automation/engine/SessionStateAliasAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateAliasAPIs.cs @@ -403,7 +403,7 @@ internal AliasInfo SetAliasValue( /// internal AliasInfo SetAliasItem(AliasInfo alias, bool force, CommandOrigin origin) { - if (alias is null) + if (alias == null) { throw PSTraceSource.NewArgumentNullException(nameof(alias)); } @@ -450,7 +450,7 @@ internal AliasInfo SetAliasItem(AliasInfo alias, bool force, CommandOrigin origi /// internal AliasInfo SetAliasItemAtScope(AliasInfo alias, string scopeID, bool force, CommandOrigin origin) { - if (alias is null) + if (alias == null) { throw PSTraceSource.NewArgumentNullException(nameof(alias)); } diff --git a/src/System.Management.Automation/engine/SessionStateContainer.cs b/src/System.Management.Automation/engine/SessionStateContainer.cs index cd1c72257c7..f4f2a46d2a5 100644 --- a/src/System.Management.Automation/engine/SessionStateContainer.cs +++ b/src/System.Management.Automation/engine/SessionStateContainer.cs @@ -58,7 +58,7 @@ internal sealed partial class SessionStateInternal /// internal bool ItemExists(string path, bool force, bool literalPath) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -106,7 +106,7 @@ internal bool ItemExists( string path, CmdletProviderContext context) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -250,7 +250,7 @@ internal bool ItemExists( /// internal object ItemExistsDynamicParameters(string path, CmdletProviderContext context) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -390,7 +390,7 @@ private object ItemExistsDynamicParameters( /// internal bool IsValidPath(string path) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -436,7 +436,7 @@ internal bool IsValidPath( string path, CmdletProviderContext context) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -560,7 +560,7 @@ private bool IsValidPath( /// internal bool IsItemContainer(string path) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -606,7 +606,7 @@ internal bool IsItemContainer( string path, CmdletProviderContext context) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -787,7 +787,7 @@ private bool IsItemContainer( /// internal void RemoveItem(string[] paths, bool recurse, bool force, bool literalPath) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -838,14 +838,14 @@ internal void RemoveItem( bool recurse, CmdletProviderContext context) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } foreach (string path in paths) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -1079,7 +1079,7 @@ internal object RemoveItemDynamicParameters( bool recurse, CmdletProviderContext context) { - if (path is null) + if (path == null) { return null; } @@ -1238,7 +1238,7 @@ private object RemoveItemDynamicParameters( /// internal Collection GetChildItems(string[] paths, bool recurse, uint depth, bool force, bool literalPath) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -1249,7 +1249,7 @@ internal Collection GetChildItems(string[] paths, bool recurse, uint d foreach (string path in paths) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -1305,12 +1305,12 @@ internal void GetChildItems( uint depth, CmdletProviderContext context) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } - if (context is null) + if (context == null) { throw PSTraceSource.NewArgumentNullException(nameof(context)); } @@ -1344,7 +1344,7 @@ internal void GetChildItems( path = parentName; } // dir c:\tem* -include *.ps1 -rec => No change - if ((context.Include is null) || (context.Include.Count == 0)) + if ((context.Include == null) || (context.Include.Count == 0)) { // dir c:\tem* -rec => dir c:\ -include tem* -rec // dir tem* -rec => dir -include tem* -rec @@ -1843,7 +1843,7 @@ private void ProcessPathItems( string childName = childNameObjects[index].BaseObject as string; - if (childName is null) + if (childName == null) { continue; } @@ -1852,7 +1852,7 @@ private void ProcessPathItems( string qualifiedPath = MakePath(providerInstance, path, childName, context); - if (qualifiedPath is null) + if (qualifiedPath == null) { continue; } @@ -1989,7 +1989,7 @@ internal object GetChildItemsDynamicParameters( bool recurse, CmdletProviderContext context) { - if (path is null) + if (path == null) { return null; } @@ -2032,7 +2032,7 @@ internal object GetChildItemsDynamicParameters( // ItemNotFoundException will be thrown out. In this case, we catch the exception // and check if the "providerInstance" is identified. If providerInstance is not null, // we can carry on with the get-dynamic-parameters method. - if (providerInstance is null) + if (providerInstance == null) { throw; } @@ -2075,7 +2075,7 @@ private bool HasGetChildItemDynamicParameters(ProviderInfo providerInfo) BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly); providerType = providerType.BaseType; } while ( - (mi is null) && + (mi == null) && (providerType != null) && (providerType != typeof(ContainerCmdletProvider)) ); @@ -2227,7 +2227,7 @@ internal Collection GetChildNames( bool force, bool literalPath) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -2238,7 +2238,7 @@ internal Collection GetChildNames( foreach (string path in paths) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -2318,7 +2318,7 @@ internal void GetChildNames( uint depth, CmdletProviderContext context) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -2590,7 +2590,7 @@ private void DoGetChildNamesManually( string name = result.BaseObject as string; - if (name is null) + if (name == null) { continue; } @@ -2640,7 +2640,7 @@ private void DoGetChildNamesManually( string name = result.BaseObject as string; - if (name is null) + if (name == null) { continue; } @@ -2798,7 +2798,7 @@ internal object GetChildNamesDynamicParameters( string path, CmdletProviderContext context) { - if (path is null) + if (path == null) { return null; } @@ -2831,7 +2831,7 @@ internal object GetChildNamesDynamicParameters( // ItemNotFoundException will be thrown out. In this case, we catch the exception // and check if the "providerInstance" is identified. If providerInstance is not null, // we can carry on with the get-dynamic-parameters method. - if (providerInstance is null) + if (providerInstance == null) { throw; } @@ -2977,7 +2977,7 @@ private object GetChildNamesDynamicParameters( /// internal Collection RenameItem(string path, string newName, bool force) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -3035,7 +3035,7 @@ internal void RenameItem( string newName, CmdletProviderContext context) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -3186,7 +3186,7 @@ internal object RenameItemDynamicParameters( string newName, CmdletProviderContext context) { - if (path is null) + if (path == null) { return null; } @@ -3343,7 +3343,7 @@ private object RenameItemDynamicParameters( /// internal Collection NewItem(string[] paths, string name, string type, object content, bool force) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -3407,7 +3407,7 @@ internal void NewItem( object content, CmdletProviderContext context) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -3415,7 +3415,7 @@ internal void NewItem( foreach (string path in paths) { string resolvePath = null; - if (path is null) + if (path == null) { PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -3658,7 +3658,7 @@ internal object NewItemDynamicParameters( object newItemValue, CmdletProviderContext context) { - if (path is null) + if (path == null) { return null; } @@ -3812,7 +3812,7 @@ private object NewItemDynamicParameters( /// internal bool HasChildItems(string path, bool force, bool literalPath) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -3864,7 +3864,7 @@ internal bool HasChildItems( string path, CmdletProviderContext context) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -3922,7 +3922,7 @@ internal bool HasChildItems( throw PSTraceSource.NewArgumentException(nameof(providerId)); } - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -4090,12 +4090,12 @@ internal Collection CopyItem(string[] paths, bool force, bool literalPath) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } - if (copyPath is null) + if (copyPath == null) { copyPath = string.Empty; } @@ -4156,12 +4156,12 @@ internal void CopyItem( CopyContainers copyContainers, CmdletProviderContext context) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } - if (copyPath is null) + if (copyPath == null) { copyPath = string.Empty; } @@ -4240,7 +4240,7 @@ internal void CopyItem( } string root = ValidateRemotePathAndGetRoot(providerDestinationPath, session, context, remoteLanguageMode, false); - if (root is null) + if (root == null) { return; } @@ -4253,7 +4253,7 @@ internal void CopyItem( foreach (string path in paths) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -4264,7 +4264,7 @@ internal void CopyItem( { // Get the root for the remote path string root = ValidateRemotePathAndGetRoot(path, session, context, remoteLanguageMode, true); - if (root is null) + if (root == null) { return; } @@ -4629,7 +4629,7 @@ internal object CopyItemDynamicParameters( bool recurse, CmdletProviderContext context) { - if (path is null) + if (path == null) { return null; } @@ -4840,7 +4840,7 @@ private string ValidateRemotePathAndGetRoot(string path, Runspaces.PSSession ses op = Microsoft.PowerShell.Commands.SafeInvokeCommand.Invoke(ps, null, context); } - if (op is null) + if (op == null) { context.WriteError(new ErrorRecord( new InvalidOperationException( @@ -4883,7 +4883,7 @@ private string ValidateRemotePathAndGetRoot(string path, Runspaces.PSSession ses bool invalidRemoteSource = (sourceIsRemote && (!pathExist)); // 2) For a remote destination, if the root does not exist, error out. - bool invalidRemoteDestination = (root is null); + bool invalidRemoteDestination = (root == null); if (invalidRemoteSource || invalidRemoteDestination) { @@ -4902,7 +4902,7 @@ private string ValidateRemotePathAndGetRoot(string path, Runspaces.PSSession ses private bool isValidSession(PSSession session, CmdletProviderContext context, out PSLanguageMode? languageMode) { - // session is null is validated by the parameter binding + // session == null is validated by the parameter binding if (session.Availability != RunspaceAvailability.Available) { context.WriteError(new ErrorRecord( diff --git a/src/System.Management.Automation/engine/SessionStateContent.cs b/src/System.Management.Automation/engine/SessionStateContent.cs index 4184850461a..0f1cc74bc49 100644 --- a/src/System.Management.Automation/engine/SessionStateContent.cs +++ b/src/System.Management.Automation/engine/SessionStateContent.cs @@ -53,7 +53,7 @@ internal sealed partial class SessionStateInternal /// internal Collection GetContentReader(string[] paths, bool force, bool literalPath) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -105,7 +105,7 @@ internal Collection GetContentReader( string[] paths, CmdletProviderContext context) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -117,7 +117,7 @@ internal Collection GetContentReader( foreach (string path in paths) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -254,7 +254,7 @@ internal object GetContentReaderDynamicParameters( string path, CmdletProviderContext context) { - if (path is null) + if (path == null) { return null; } @@ -394,7 +394,7 @@ private object GetContentReaderDynamicParameters( /// internal Collection GetContentWriter(string[] paths, bool force, bool literalPath) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -446,7 +446,7 @@ internal Collection GetContentWriter( string[] paths, CmdletProviderContext context) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -457,7 +457,7 @@ internal Collection GetContentWriter( foreach (string path in paths) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -592,7 +592,7 @@ internal object GetContentWriterDynamicParameters( string path, CmdletProviderContext context) { - if (path is null) + if (path == null) { return null; } @@ -736,7 +736,7 @@ private object GetContentWriterDynamicParameters( /// internal void ClearContent(string[] paths, bool force, bool literalPath) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -783,7 +783,7 @@ internal void ClearContent( string[] paths, CmdletProviderContext context) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -793,7 +793,7 @@ internal void ClearContent( foreach (string path in paths) { - if (path is null) + if (path == null) { PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -917,7 +917,7 @@ internal object ClearContentDynamicParameters( string path, CmdletProviderContext context) { - if (path is null) + if (path == null) { return null; } diff --git a/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs b/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs index 3ff8ee56e72..23e9fdc0475 100644 --- a/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs @@ -63,7 +63,7 @@ internal sealed partial class SessionStateInternal /// internal PSDriveInfo NewDrive(PSDriveInfo drive, string scopeID) { - if (drive is null) + if (drive == null) { throw PSTraceSource.NewArgumentNullException(nameof(drive)); } @@ -138,12 +138,12 @@ internal PSDriveInfo NewDrive(PSDriveInfo drive, string scopeID) /// internal void NewDrive(PSDriveInfo drive, string scopeID, CmdletProviderContext context) { - if (drive is null) + if (drive == null) { throw PSTraceSource.NewArgumentNullException(nameof(drive)); } - if (context is null) + if (context == null) { throw PSTraceSource.NewArgumentNullException(nameof(context)); } @@ -165,7 +165,7 @@ internal void NewDrive(PSDriveInfo drive, string scopeID, CmdletProviderContext // We assume that the provider wrote the error message as they // are suppose to. - if (result is null) + if (result == null) { return; } @@ -203,7 +203,7 @@ internal void NewDrive(PSDriveInfo drive, string scopeID, CmdletProviderContext throw; } - if (ProvidersCurrentWorkingDrive[drive.Provider] is null) + if (ProvidersCurrentWorkingDrive[drive.Provider] == null) { // Set the new drive as the current // drive for the provider since there isn't one set. @@ -376,7 +376,7 @@ private string GetProviderRootFromSpecifiedRoot(string root, ProviderInfo provid /// internal object NewDriveDynamicParameters(string providerId, CmdletProviderContext context) { - if (providerId is null) + if (providerId == null) { // If the provider hasn't been specified yet, just return null. // The provider can be specified as pipeline input. @@ -430,7 +430,7 @@ internal PSDriveInfo GetDrive(string name) private PSDriveInfo GetDrive(string name, bool automount) { - if (name is null) + if (name == null) { throw PSTraceSource.NewArgumentNullException(nameof(name)); } @@ -471,14 +471,14 @@ private PSDriveInfo GetDrive(string name, bool automount) ++scopeID; } - if (result is null && automount) + if (result == null && automount) { // Attempt to automount as a file system drive // or as a BuiltIn drive (e.g. "Cert"/"Certificate"/"WSMan") result = AutomountFileSystemDrive(name) ?? AutomountBuiltInDrive(name); } - if (result is null) + if (result == null) { DriveNotFoundException driveNotFound = new DriveNotFoundException( @@ -522,7 +522,7 @@ private PSDriveInfo GetDrive(string name, bool automount) /// internal PSDriveInfo GetDrive(string name, string scopeID) { - if (name is null) + if (name == null) { throw PSTraceSource.NewArgumentNullException(nameof(name)); } @@ -561,7 +561,7 @@ internal PSDriveInfo GetDrive(string name, string scopeID) } } - if (result is null) + if (result == null) { result = AutomountFileSystemDrive(name); } @@ -991,14 +991,14 @@ internal Collection GetDrivesForProvider(string providerId) /// internal void RemoveDrive(string driveName, bool force, string scopeID) { - if (driveName is null) + if (driveName == null) { throw PSTraceSource.NewArgumentNullException(nameof(driveName)); } PSDriveInfo drive = GetDrive(driveName, scopeID); - if (drive is null) + if (drive == null) { DriveNotFoundException e = new DriveNotFoundException( driveName, @@ -1034,7 +1034,7 @@ internal void RemoveDrive( string scopeID, CmdletProviderContext context) { - if (driveName is null) + if (driveName == null) { throw PSTraceSource.NewArgumentNullException(nameof(driveName)); } @@ -1045,7 +1045,7 @@ internal void RemoveDrive( PSDriveInfo drive = GetDrive(driveName, scopeID); - if (drive is null) + if (drive == null) { DriveNotFoundException e = new DriveNotFoundException( driveName, @@ -1076,7 +1076,7 @@ internal void RemoveDrive( /// internal void RemoveDrive(PSDriveInfo drive, bool force, string scopeID) { - if (drive is null) + if (drive == null) { throw PSTraceSource.NewArgumentNullException(nameof(drive)); } @@ -1238,12 +1238,12 @@ internal void RemoveDrive( /// private bool CanRemoveDrive(PSDriveInfo drive, CmdletProviderContext context) { - if (context is null) + if (context == null) { throw PSTraceSource.NewArgumentNullException(nameof(context)); } - if (drive is null) + if (drive == null) { throw PSTraceSource.NewArgumentNullException(nameof(drive)); } diff --git a/src/System.Management.Automation/engine/SessionStateDynamicProperty.cs b/src/System.Management.Automation/engine/SessionStateDynamicProperty.cs index 2282d57cf5b..575c3387d5e 100644 --- a/src/System.Management.Automation/engine/SessionStateDynamicProperty.cs +++ b/src/System.Management.Automation/engine/SessionStateDynamicProperty.cs @@ -68,12 +68,12 @@ internal Collection NewProperty( bool force, bool literalPath) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } - if (property is null) + if (property == null) { throw PSTraceSource.NewArgumentNullException(nameof(property)); } @@ -139,12 +139,12 @@ internal void NewProperty( object value, CmdletProviderContext context) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } - if (property is null) + if (property == null) { throw PSTraceSource.NewArgumentNullException(nameof(property)); } @@ -154,7 +154,7 @@ internal void NewProperty( foreach (string path in paths) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -306,7 +306,7 @@ internal object NewPropertyDynamicParameters( object value, CmdletProviderContext context) { - if (path is null) + if (path == null) { return null; } @@ -465,12 +465,12 @@ private object NewPropertyDynamicParameters( /// internal void RemoveProperty(string[] paths, string property, bool force, bool literalPath) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } - if (property is null) + if (property == null) { throw PSTraceSource.NewArgumentNullException(nameof(property)); } @@ -521,19 +521,19 @@ internal void RemoveProperty( string property, CmdletProviderContext context) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } - if (property is null) + if (property == null) { throw PSTraceSource.NewArgumentNullException(nameof(property)); } foreach (string path in paths) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -672,7 +672,7 @@ internal object RemovePropertyDynamicParameters( string propertyName, CmdletProviderContext context) { - if (path is null) + if (path == null) { return null; } @@ -838,22 +838,22 @@ internal Collection CopyProperty( bool force, bool literalPath) { - if (sourcePaths is null) + if (sourcePaths == null) { throw PSTraceSource.NewArgumentNullException(nameof(sourcePaths)); } - if (sourceProperty is null) + if (sourceProperty == null) { throw PSTraceSource.NewArgumentNullException(nameof(sourceProperty)); } - if (destinationPath is null) + if (destinationPath == null) { throw PSTraceSource.NewArgumentNullException(nameof(destinationPath)); } - if (destinationProperty is null) + if (destinationProperty == null) { throw PSTraceSource.NewArgumentNullException(nameof(destinationProperty)); } @@ -919,29 +919,29 @@ internal void CopyProperty( string destinationProperty, CmdletProviderContext context) { - if (sourcePaths is null) + if (sourcePaths == null) { throw PSTraceSource.NewArgumentNullException(nameof(sourcePaths)); } - if (sourceProperty is null) + if (sourceProperty == null) { throw PSTraceSource.NewArgumentNullException(nameof(sourceProperty)); } - if (destinationPath is null) + if (destinationPath == null) { throw PSTraceSource.NewArgumentNullException(nameof(destinationPath)); } - if (destinationProperty is null) + if (destinationProperty == null) { throw PSTraceSource.NewArgumentNullException(nameof(destinationProperty)); } foreach (string sourcePath in sourcePaths) { - if (sourcePath is null) + if (sourcePath == null) { throw PSTraceSource.NewArgumentNullException(nameof(sourcePaths)); } @@ -1137,7 +1137,7 @@ internal object CopyPropertyDynamicParameters( string destinationProperty, CmdletProviderContext context) { - if (path is null) + if (path == null) { return null; } @@ -1325,22 +1325,22 @@ internal Collection MoveProperty( bool force, bool literalPath) { - if (sourcePaths is null) + if (sourcePaths == null) { throw PSTraceSource.NewArgumentNullException(nameof(sourcePaths)); } - if (sourceProperty is null) + if (sourceProperty == null) { throw PSTraceSource.NewArgumentNullException(nameof(sourceProperty)); } - if (destinationPath is null) + if (destinationPath == null) { throw PSTraceSource.NewArgumentNullException(nameof(destinationPath)); } - if (destinationProperty is null) + if (destinationProperty == null) { throw PSTraceSource.NewArgumentNullException(nameof(destinationProperty)); } @@ -1409,22 +1409,22 @@ internal void MoveProperty( string destinationProperty, CmdletProviderContext context) { - if (sourcePaths is null) + if (sourcePaths == null) { throw PSTraceSource.NewArgumentNullException(nameof(sourcePaths)); } - if (sourceProperty is null) + if (sourceProperty == null) { throw PSTraceSource.NewArgumentNullException(nameof(sourceProperty)); } - if (destinationPath is null) + if (destinationPath == null) { throw PSTraceSource.NewArgumentNullException(nameof(destinationPath)); } - if (destinationProperty is null) + if (destinationProperty == null) { throw PSTraceSource.NewArgumentNullException(nameof(destinationProperty)); } @@ -1462,7 +1462,7 @@ internal void MoveProperty( { foreach (string sourcePath in sourcePaths) { - if (sourcePath is null) + if (sourcePath == null) { throw PSTraceSource.NewArgumentNullException(nameof(sourcePaths)); } @@ -1623,7 +1623,7 @@ internal object MovePropertyDynamicParameters( string destinationProperty, CmdletProviderContext context) { - if (path is null) + if (path == null) { return null; } @@ -1803,17 +1803,17 @@ internal Collection RenameProperty( bool force, bool literalPath) { - if (sourcePaths is null) + if (sourcePaths == null) { throw PSTraceSource.NewArgumentNullException(nameof(sourcePaths)); } - if (sourceProperty is null) + if (sourceProperty == null) { throw PSTraceSource.NewArgumentNullException(nameof(sourceProperty)); } - if (destinationProperty is null) + if (destinationProperty == null) { throw PSTraceSource.NewArgumentNullException(nameof(destinationProperty)); } @@ -1872,24 +1872,24 @@ internal void RenameProperty( string destinationProperty, CmdletProviderContext context) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } - if (sourceProperty is null) + if (sourceProperty == null) { throw PSTraceSource.NewArgumentNullException(nameof(sourceProperty)); } - if (destinationProperty is null) + if (destinationProperty == null) { throw PSTraceSource.NewArgumentNullException(nameof(destinationProperty)); } foreach (string path in paths) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -2040,7 +2040,7 @@ internal object RenamePropertyDynamicParameters( string destinationProperty, CmdletProviderContext context) { - if (path is null) + if (path == null) { return null; } diff --git a/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs b/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs index 8960f872271..42d3607cadb 100644 --- a/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs @@ -182,7 +182,7 @@ private bool IsFunctionVisibleInDebugger(FunctionInfo fnInfo, CommandOrigin orig // Early out. // Always allow built-in functions needed for command line debugging. if ((this.ExecutionContext.LanguageMode == PSLanguageMode.FullLanguage) || - (fnInfo is null) || + (fnInfo == null) || (fnInfo.Name.Equals("prompt", StringComparison.OrdinalIgnoreCase)) || (fnInfo.Name.Equals("TabExpansion2", StringComparison.OrdinalIgnoreCase)) || (fnInfo.Name.Equals("Clear-Host", StringComparison.Ordinal))) @@ -222,7 +222,7 @@ internal FunctionInfo GetFunction(string name) private IEnumerable GetFunctionAliases(IParameterMetadataProvider ipmp) { - if (ipmp is null || ipmp.Body.ParamBlock is null) + if (ipmp == null || ipmp.Body.ParamBlock == null) yield break; var attributes = ipmp.Body.ParamBlock.Attributes; @@ -272,7 +272,7 @@ internal FunctionInfo SetFunctionRaw( throw PSTraceSource.NewArgumentException(nameof(name)); } - if (function is null) + if (function == null) { throw PSTraceSource.NewArgumentNullException(nameof(function)); } @@ -507,7 +507,7 @@ internal FunctionInfo SetFunction( throw PSTraceSource.NewArgumentException(nameof(name)); } - if (function is null) + if (function == null) { throw PSTraceSource.NewArgumentNullException(nameof(function)); } @@ -586,7 +586,7 @@ internal FunctionInfo SetFunction( throw PSTraceSource.NewArgumentException(nameof(name)); } - if (function is null) + if (function == null) { throw PSTraceSource.NewArgumentNullException(nameof(function)); } diff --git a/src/System.Management.Automation/engine/SessionStateItem.cs b/src/System.Management.Automation/engine/SessionStateItem.cs index c8a51c90e2d..3d5262bf6c0 100644 --- a/src/System.Management.Automation/engine/SessionStateItem.cs +++ b/src/System.Management.Automation/engine/SessionStateItem.cs @@ -54,7 +54,7 @@ internal sealed partial class SessionStateInternal /// internal Collection GetItem(string[] paths, bool force, bool literalPath) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -112,7 +112,7 @@ internal void GetItem( string[] paths, CmdletProviderContext context) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -122,7 +122,7 @@ internal void GetItem( foreach (string path in paths) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -243,7 +243,7 @@ private void GetItemPrivate( /// internal object GetItemDynamicParameters(string path, CmdletProviderContext context) { - if (path is null) + if (path == null) { return null; } @@ -393,7 +393,7 @@ private object GetItemDynamicParameters( /// internal Collection SetItem(string[] paths, object value, bool force, bool literalPath) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -449,14 +449,14 @@ internal void SetItem( object value, CmdletProviderContext context) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } foreach (string path in paths) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -590,7 +590,7 @@ private void SetItem( /// internal object SetItemDynamicParameters(string path, object value, CmdletProviderContext context) { - if (path is null) + if (path == null) { return null; } @@ -746,7 +746,7 @@ private object SetItemDynamicParameters( /// internal Collection ClearItem(string[] paths, bool force, bool literalPath) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -798,7 +798,7 @@ internal void ClearItem( string[] paths, CmdletProviderContext context) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -808,7 +808,7 @@ internal void ClearItem( foreach (string path in paths) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -932,7 +932,7 @@ private void ClearItemPrivate( /// internal object ClearItemDynamicParameters(string path, CmdletProviderContext context) { - if (path is null) + if (path == null) { return null; } @@ -1077,7 +1077,7 @@ private object ClearItemDynamicParameters( /// internal void InvokeDefaultAction(string[] paths, bool literalPath) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -1125,7 +1125,7 @@ internal void InvokeDefaultAction( string[] paths, CmdletProviderContext context) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -1135,7 +1135,7 @@ internal void InvokeDefaultAction( foreach (string path in paths) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -1259,7 +1259,7 @@ private void InvokeDefaultActionPrivate( /// internal object InvokeDefaultActionDynamicParameters(string path, CmdletProviderContext context) { - if (path is null) + if (path == null) { return null; } diff --git a/src/System.Management.Automation/engine/SessionStateLocationAPIs.cs b/src/System.Management.Automation/engine/SessionStateLocationAPIs.cs index c260f866dd3..4cd4718aca5 100644 --- a/src/System.Management.Automation/engine/SessionStateLocationAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateLocationAPIs.cs @@ -31,7 +31,7 @@ internal PathInfo CurrentLocation { get { - if (CurrentDrive is null) + if (CurrentDrive == null) { // We need the error handling, and moving to a method would be // a breaking change @@ -73,7 +73,7 @@ internal PathInfo CurrentLocation /// internal PathInfo GetNamespaceCurrentLocation(string namespaceID) { - if (namespaceID is null) + if (namespaceID == null) { throw PSTraceSource.NewArgumentNullException(nameof(namespaceID)); } @@ -91,7 +91,7 @@ internal PathInfo GetNamespaceCurrentLocation(string namespaceID) ProvidersCurrentWorkingDrive.TryGetValue(GetSingleProvider(namespaceID), out drive); } - if (drive is null) + if (drive == null) { DriveNotFoundException e = new DriveNotFoundException( @@ -234,7 +234,7 @@ internal PathInfo SetLocation(string path, CmdletProviderContext context) /// internal PathInfo SetLocation(string path, CmdletProviderContext context, bool literalPath) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -316,7 +316,7 @@ internal PathInfo SetLocation(string path, CmdletProviderContext context, bool l } } - if (context is null) + if (context == null) { context = new CmdletProviderContext(this.ExecutionContext); } @@ -634,7 +634,7 @@ internal bool IsCurrentLocationOrAncestor(string path, CmdletProviderContext con { bool result = false; - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } diff --git a/src/System.Management.Automation/engine/SessionStateNavigation.cs b/src/System.Management.Automation/engine/SessionStateNavigation.cs index cc3e7dfd840..4afb9218dd7 100644 --- a/src/System.Management.Automation/engine/SessionStateNavigation.cs +++ b/src/System.Management.Automation/engine/SessionStateNavigation.cs @@ -46,7 +46,7 @@ internal sealed partial class SessionStateInternal /// internal string GetParentPath(string path, string root) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -123,7 +123,7 @@ internal string GetParentPath( CmdletProviderContext context, bool useDefaultProvider) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -467,7 +467,7 @@ internal string GetParentPath( /// internal string NormalizeRelativePath(string path, string basePath) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -515,7 +515,7 @@ internal string NormalizeRelativePath( string basePath, CmdletProviderContext context) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -540,8 +540,8 @@ internal string NormalizeRelativePath( return null; } - if (workingPath is null || - provider is null) + if (workingPath == null || + provider == null) { // Since the provider didn't write an error, and we didn't get any // results ourselves, we need to write out our own error. @@ -814,13 +814,13 @@ internal string MakePath( { string result = null; - if (context is null) + if (context == null) { throw PSTraceSource.NewArgumentNullException(nameof(context)); } - if (parent is null && - child is null) + if (parent == null && + child == null) { throw PSTraceSource.NewArgumentException(nameof(parent)); } @@ -833,7 +833,7 @@ internal string MakePath( provider = CurrentDrive.Provider; } - if (context.Drive is null) + if (context.Drive == null) { bool isProviderQualified = LocationGlobber.IsProviderQualifiedPath(parent); bool isAbsolute = LocationGlobber.IsAbsolutePath(parent); @@ -844,7 +844,7 @@ internal string MakePath( // Ignore the result. Just using this to get the providerId and drive Globber.GetProviderPath(parent, context, out provider, out drive); - if (drive is null && isProviderQualified) + if (drive == null && isProviderQualified) { drive = provider.HiddenDrive; } @@ -1044,7 +1044,7 @@ internal string MakePath( /// internal string GetChildName(string path) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -1115,7 +1115,7 @@ internal string GetChildName( CmdletProviderContext context, bool useDefaultProvider) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -1257,7 +1257,7 @@ bool acceptNonContainerProviders NavigationCmdletProvider navigationCmdletProvider = GetNavigationProviderInstance(providerInstance, acceptNonContainerProviders); - if (navigationCmdletProvider is null) + if (navigationCmdletProvider == null) return path; try @@ -1338,7 +1338,7 @@ bool acceptNonContainerProviders /// internal Collection MoveItem(string[] paths, string destination, bool force, bool literalPath) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -1396,12 +1396,12 @@ internal void MoveItem( string destination, CmdletProviderContext context) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } - if (destination is null) + if (destination == null) { throw PSTraceSource.NewArgumentNullException(nameof(destination)); } @@ -1429,7 +1429,7 @@ internal void MoveItem( { foreach (string path in paths) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -1624,7 +1624,7 @@ internal object MoveItemDynamicParameters( string destination, CmdletProviderContext context) { - if (path is null) + if (path == null) { return null; } diff --git a/src/System.Management.Automation/engine/SessionStateProperty.cs b/src/System.Management.Automation/engine/SessionStateProperty.cs index aaaa57db794..d4568d2ebb3 100644 --- a/src/System.Management.Automation/engine/SessionStateProperty.cs +++ b/src/System.Management.Automation/engine/SessionStateProperty.cs @@ -56,7 +56,7 @@ internal Collection GetProperty( Collection providerSpecificPickList, bool literalPath) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException("path"); } @@ -114,14 +114,14 @@ internal void GetProperty( Collection providerSpecificPickList, CmdletProviderContext context) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } foreach (string path in paths) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -260,7 +260,7 @@ internal object GetPropertyDynamicParameters( Collection providerSpecificPickList, CmdletProviderContext context) { - if (path is null) + if (path == null) { return null; } @@ -414,12 +414,12 @@ private object GetPropertyDynamicParameters( /// internal Collection SetProperty(string[] paths, PSObject property, bool force, bool literalPath) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } - if (property is null) + if (property == null) { throw PSTraceSource.NewArgumentNullException("properties"); } @@ -478,19 +478,19 @@ internal void SetProperty( PSObject property, CmdletProviderContext context) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } - if (property is null) + if (property == null) { throw PSTraceSource.NewArgumentNullException(nameof(property)); } foreach (string path in paths) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -632,7 +632,7 @@ internal object SetPropertyDynamicParameters( PSObject propertyValue, CmdletProviderContext context) { - if (path is null) + if (path == null) { return null; } @@ -787,12 +787,12 @@ internal void ClearProperty( bool force, bool literalPath) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } - if (propertyToClear is null) + if (propertyToClear == null) { throw PSTraceSource.NewArgumentNullException(nameof(propertyToClear)); } @@ -843,19 +843,19 @@ internal void ClearProperty( Collection propertyToClear, CmdletProviderContext context) { - if (paths is null) + if (paths == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } - if (propertyToClear is null) + if (propertyToClear == null) { throw PSTraceSource.NewArgumentNullException(nameof(propertyToClear)); } foreach (string path in paths) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(paths)); } @@ -994,7 +994,7 @@ internal object ClearPropertyDynamicParameters( Collection propertyToClear, CmdletProviderContext context) { - if (path is null) + if (path == null) { return null; } diff --git a/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs b/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs index df1ab0f3786..f1b637a1d84 100644 --- a/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs @@ -252,7 +252,7 @@ private PSDriveInfo ValidateDriveWithProvider( /// internal Provider.CmdletProvider GetProviderInstance(string providerId) { - if (providerId is null) + if (providerId == null) { throw PSTraceSource.NewArgumentNullException(nameof(providerId)); } @@ -276,7 +276,7 @@ internal Provider.CmdletProvider GetProviderInstance(string providerId) /// internal Provider.CmdletProvider GetProviderInstance(ProviderInfo provider) { - if (provider is null) + if (provider == null) { throw PSTraceSource.NewArgumentNullException(nameof(provider)); } @@ -345,7 +345,7 @@ private static string GetPossibleMatches(Collection matchingProvid /// internal DriveCmdletProvider GetDriveProviderInstance(string providerId) { - if (providerId is null) + if (providerId == null) { throw PSTraceSource.NewArgumentNullException(nameof(providerId)); } @@ -353,7 +353,7 @@ internal DriveCmdletProvider GetDriveProviderInstance(string providerId) DriveCmdletProvider driveCmdletProvider = GetProviderInstance(providerId) as DriveCmdletProvider; - if (driveCmdletProvider is null) + if (driveCmdletProvider == null) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.DriveCmdletProvider_NotSupported); @@ -380,7 +380,7 @@ internal DriveCmdletProvider GetDriveProviderInstance(string providerId) /// internal DriveCmdletProvider GetDriveProviderInstance(ProviderInfo provider) { - if (provider is null) + if (provider == null) { throw PSTraceSource.NewArgumentNullException(nameof(provider)); } @@ -388,7 +388,7 @@ internal DriveCmdletProvider GetDriveProviderInstance(ProviderInfo provider) DriveCmdletProvider driveCmdletProvider = GetProviderInstance(provider) as DriveCmdletProvider; - if (driveCmdletProvider is null) + if (driveCmdletProvider == null) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.DriveCmdletProvider_NotSupported); @@ -415,7 +415,7 @@ internal DriveCmdletProvider GetDriveProviderInstance(ProviderInfo provider) /// private static DriveCmdletProvider GetDriveProviderInstance(CmdletProvider providerInstance) { - if (providerInstance is null) + if (providerInstance == null) { throw PSTraceSource.NewArgumentNullException(nameof(providerInstance)); } @@ -423,7 +423,7 @@ private static DriveCmdletProvider GetDriveProviderInstance(CmdletProvider provi DriveCmdletProvider driveCmdletProvider = providerInstance as DriveCmdletProvider; - if (driveCmdletProvider is null) + if (driveCmdletProvider == null) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.DriveCmdletProvider_NotSupported); @@ -453,7 +453,7 @@ private static DriveCmdletProvider GetDriveProviderInstance(CmdletProvider provi /// internal ItemCmdletProvider GetItemProviderInstance(string providerId) { - if (providerId is null) + if (providerId == null) { throw PSTraceSource.NewArgumentNullException(nameof(providerId)); } @@ -461,7 +461,7 @@ internal ItemCmdletProvider GetItemProviderInstance(string providerId) ItemCmdletProvider itemCmdletProvider = GetProviderInstance(providerId) as ItemCmdletProvider; - if (itemCmdletProvider is null) + if (itemCmdletProvider == null) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.ItemCmdletProvider_NotSupported); @@ -488,7 +488,7 @@ internal ItemCmdletProvider GetItemProviderInstance(string providerId) /// internal ItemCmdletProvider GetItemProviderInstance(ProviderInfo provider) { - if (provider is null) + if (provider == null) { throw PSTraceSource.NewArgumentNullException(nameof(provider)); } @@ -496,7 +496,7 @@ internal ItemCmdletProvider GetItemProviderInstance(ProviderInfo provider) ItemCmdletProvider itemCmdletProvider = GetProviderInstance(provider) as ItemCmdletProvider; - if (itemCmdletProvider is null) + if (itemCmdletProvider == null) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.ItemCmdletProvider_NotSupported); @@ -523,7 +523,7 @@ internal ItemCmdletProvider GetItemProviderInstance(ProviderInfo provider) /// private static ItemCmdletProvider GetItemProviderInstance(CmdletProvider providerInstance) { - if (providerInstance is null) + if (providerInstance == null) { throw PSTraceSource.NewArgumentNullException(nameof(providerInstance)); } @@ -531,7 +531,7 @@ private static ItemCmdletProvider GetItemProviderInstance(CmdletProvider provide ItemCmdletProvider itemCmdletProvider = providerInstance as ItemCmdletProvider; - if (itemCmdletProvider is null) + if (itemCmdletProvider == null) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.ItemCmdletProvider_NotSupported); @@ -561,7 +561,7 @@ private static ItemCmdletProvider GetItemProviderInstance(CmdletProvider provide /// internal ContainerCmdletProvider GetContainerProviderInstance(string providerId) { - if (providerId is null) + if (providerId == null) { throw PSTraceSource.NewArgumentNullException(nameof(providerId)); } @@ -569,7 +569,7 @@ internal ContainerCmdletProvider GetContainerProviderInstance(string providerId) ContainerCmdletProvider containerCmdletProvider = GetProviderInstance(providerId) as ContainerCmdletProvider; - if (containerCmdletProvider is null) + if (containerCmdletProvider == null) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.ContainerCmdletProvider_NotSupported); @@ -596,7 +596,7 @@ internal ContainerCmdletProvider GetContainerProviderInstance(string providerId) /// internal ContainerCmdletProvider GetContainerProviderInstance(ProviderInfo provider) { - if (provider is null) + if (provider == null) { throw PSTraceSource.NewArgumentNullException(nameof(provider)); } @@ -604,7 +604,7 @@ internal ContainerCmdletProvider GetContainerProviderInstance(ProviderInfo provi ContainerCmdletProvider containerCmdletProvider = GetProviderInstance(provider) as ContainerCmdletProvider; - if (containerCmdletProvider is null) + if (containerCmdletProvider == null) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.ContainerCmdletProvider_NotSupported); @@ -631,7 +631,7 @@ internal ContainerCmdletProvider GetContainerProviderInstance(ProviderInfo provi /// private static ContainerCmdletProvider GetContainerProviderInstance(CmdletProvider providerInstance) { - if (providerInstance is null) + if (providerInstance == null) { throw PSTraceSource.NewArgumentNullException(nameof(providerInstance)); } @@ -639,7 +639,7 @@ private static ContainerCmdletProvider GetContainerProviderInstance(CmdletProvid ContainerCmdletProvider containerCmdletProvider = providerInstance as ContainerCmdletProvider; - if (containerCmdletProvider is null) + if (containerCmdletProvider == null) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.ContainerCmdletProvider_NotSupported); @@ -666,7 +666,7 @@ private static ContainerCmdletProvider GetContainerProviderInstance(CmdletProvid /// internal NavigationCmdletProvider GetNavigationProviderInstance(ProviderInfo provider) { - if (provider is null) + if (provider == null) { throw PSTraceSource.NewArgumentNullException(nameof(provider)); } @@ -674,7 +674,7 @@ internal NavigationCmdletProvider GetNavigationProviderInstance(ProviderInfo pro NavigationCmdletProvider navigationCmdletProvider = GetProviderInstance(provider) as NavigationCmdletProvider; - if (navigationCmdletProvider is null) + if (navigationCmdletProvider == null) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.NavigationCmdletProvider_NotSupported); @@ -705,7 +705,7 @@ internal NavigationCmdletProvider GetNavigationProviderInstance(ProviderInfo pro /// private static NavigationCmdletProvider GetNavigationProviderInstance(CmdletProvider providerInstance, bool acceptNonContainerProviders) { - if (providerInstance is null) + if (providerInstance == null) { throw PSTraceSource.NewArgumentNullException(nameof(providerInstance)); } @@ -713,7 +713,7 @@ private static NavigationCmdletProvider GetNavigationProviderInstance(CmdletProv NavigationCmdletProvider navigationCmdletProvider = providerInstance as NavigationCmdletProvider; - if ((navigationCmdletProvider is null) && (!acceptNonContainerProviders)) + if ((navigationCmdletProvider == null) && (!acceptNonContainerProviders)) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.NavigationCmdletProvider_NotSupported); @@ -785,7 +785,7 @@ internal Collection GetProvider(string name) PSSnapinQualifiedName providerName = PSSnapinQualifiedName.GetInstance(name); - if (providerName is null) + if (providerName == null) { ProviderNotFoundException e = new ProviderNotFoundException( @@ -848,7 +848,7 @@ internal Collection GetProvider(PSSnapinQualifiedName providerName { Collection result = new Collection(); - if (providerName is null) + if (providerName == null) { ProviderNotFoundException e = new ProviderNotFoundException( @@ -939,7 +939,7 @@ internal IEnumerable ProviderList /// The session state instance to copy from... internal void CopyProviders(SessionStateInternal ss) { - if (ss is null || ss.Providers is null) + if (ss == null || ss.Providers == null) return; // private Dictionary> providers; @@ -985,12 +985,12 @@ internal void InitializeProvider( ProviderInfo provider, CmdletProviderContext context) { - if (provider is null) + if (provider == null) { throw PSTraceSource.NewArgumentNullException(nameof(provider)); } - if (context is null) + if (context == null) { context = new CmdletProviderContext(this.ExecutionContext); } @@ -1050,7 +1050,7 @@ internal void InitializeProvider( foreach (PSDriveInfo newDrive in newDrives) { - if (newDrive is null) + if (newDrive == null) { continue; } @@ -1103,7 +1103,7 @@ internal void InitializeProvider( /// internal ProviderInfo NewProvider(ProviderInfo provider) { - if (provider is null) + if (provider == null) { throw PSTraceSource.NewArgumentNullException(nameof(provider)); } @@ -1178,7 +1178,7 @@ internal ProviderInfo NewProvider(ProviderInfo provider) context.ThrowFirstErrorOrDoNothing(true); - if (newProviderInfo is null) + if (newProviderInfo == null) { throw PSTraceSource.NewInvalidOperationException( @@ -1392,7 +1392,7 @@ internal void RemoveProvider( bool force, CmdletProviderContext context) { - if (context is null) + if (context == null) { throw PSTraceSource.NewArgumentNullException(nameof(context)); } @@ -1420,7 +1420,7 @@ internal void RemoveProvider( // First get an instance of the provider to make sure it exists Provider.CmdletProvider providerBase = GetProviderInstance(provider); - if (providerBase is null) + if (providerBase == null) { ProviderNotFoundException e = new ProviderNotFoundException( providerName, diff --git a/src/System.Management.Automation/engine/SessionStatePublic.cs b/src/System.Management.Automation/engine/SessionStatePublic.cs index a8894e1dfe5..0dca57054db 100644 --- a/src/System.Management.Automation/engine/SessionStatePublic.cs +++ b/src/System.Management.Automation/engine/SessionStatePublic.cs @@ -26,7 +26,7 @@ public sealed class SessionState /// internal SessionState(SessionStateInternal sessionState) { - if (sessionState is null) + if (sessionState == null) { throw PSTraceSource.NewArgumentNullException(nameof(sessionState)); } @@ -51,7 +51,7 @@ internal SessionState(SessionStateInternal sessionState) /// internal SessionState(ExecutionContext context, bool createAsChild, bool linkToGlobal) { - if (context is null) + if (context == null) throw new InvalidOperationException("ExecutionContext"); if (createAsChild) @@ -72,7 +72,7 @@ internal SessionState(ExecutionContext context, bool createAsChild, bool linkToG public SessionState() { ExecutionContext ecFromTLS = LocalPipeline.GetExecutionContextFromTLS(); - if (ecFromTLS is null) + if (ecFromTLS == null) throw new InvalidOperationException("ExecutionContext"); _sessionState = new SessionStateInternal(ecFromTLS); @@ -271,7 +271,7 @@ public static bool IsVisible(CommandOrigin origin, PSVariable variable) { if (origin == CommandOrigin.Internal) return true; - if (variable is null) + if (variable == null) { throw PSTraceSource.NewArgumentNullException(nameof(variable)); } @@ -288,7 +288,7 @@ public static bool IsVisible(CommandOrigin origin, CommandInfo commandInfo) { if (origin == CommandOrigin.Internal) return true; - if (commandInfo is null) + if (commandInfo == null) { throw PSTraceSource.NewArgumentNullException(nameof(commandInfo)); } diff --git a/src/System.Management.Automation/engine/SessionStateScope.cs b/src/System.Management.Automation/engine/SessionStateScope.cs index 77ee2e62027..54b7a40e1f2 100644 --- a/src/System.Management.Automation/engine/SessionStateScope.cs +++ b/src/System.Management.Automation/engine/SessionStateScope.cs @@ -118,7 +118,7 @@ internal SessionStateScope ScriptScope /// internal void NewDrive(PSDriveInfo newDrive) { - if (newDrive is null) + if (newDrive == null) { throw PSTraceSource.NewArgumentNullException(nameof(newDrive)); } @@ -169,12 +169,12 @@ internal void NewDrive(PSDriveInfo newDrive) /// internal void RemoveDrive(PSDriveInfo drive) { - if (drive is null) + if (drive == null) { throw PSTraceSource.NewArgumentNullException(nameof(drive)); } - if (_drives is null) + if (_drives == null) return; var driveInfos = GetDrives(); @@ -220,7 +220,7 @@ internal void RemoveAllDrives() /// internal PSDriveInfo GetDrive(string name) { - if (name is null) + if (name == null) { throw PSTraceSource.NewArgumentNullException(nameof(name)); } @@ -418,7 +418,7 @@ internal PSVariable SetVariable(string name, object value, bool asValue, bool fo bool varExists = TryGetVariable(name, origin, true, out variable); // Initialize the private variable dictionary if it's not yet - if (_variables is null) { GetPrivateVariables(); } + if (_variables == null) { GetPrivateVariables(); } if (!asValue && variableToSet != null) { @@ -427,7 +427,7 @@ internal PSVariable SetVariable(string name, object value, bool asValue, bool fo // First check the variable to ensure that it // is not constant or readonly - if (variable is null || variable.IsConstant || (!force && variable.IsReadOnly)) + if (variable == null || variable.IsConstant || (!force && variable.IsReadOnly)) { SessionStateUnauthorizedAccessException e = new SessionStateUnauthorizedAccessException( @@ -548,7 +548,7 @@ internal PSVariable NewVariable(PSVariable newVariable, bool force, SessionState // First check the variable to ensure that it // is not constant or readonly - if (variable is null || variable.IsConstant || (!force && variable.IsReadOnly)) + if (variable == null || variable.IsConstant || (!force && variable.IsReadOnly)) { SessionStateUnauthorizedAccessException e = new SessionStateUnauthorizedAccessException( @@ -1622,7 +1622,7 @@ internal Language.TypeResolutionState TypeResolutionState internal void AddType(string name, Type type) { - if (TypeTable is null) + if (TypeTable == null) { TypeTable = new Dictionary(StringComparer.OrdinalIgnoreCase); } @@ -1632,7 +1632,7 @@ internal void AddType(string name, Type type) internal Type LookupType(string name) { - if (TypeTable is null) return null; + if (TypeTable == null) return null; Type result; TypeTable.TryGetValue(name, out result); return result; @@ -1714,7 +1714,7 @@ private Dictionary GetAutomountedDrives() private Dictionary GetPrivateVariables() { - if (_variables is null) + if (_variables == null) { // Create the variables collection with the default parameters _variables = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -1734,7 +1734,7 @@ private Dictionary GetPrivateVariables() /// internal void AddSessionStateScopeDefaultVariables() { - if (Parent is null) + if (Parent == null) { // Create the default variables that are in every scope // These variables will automatically propagate to new @@ -1762,7 +1762,7 @@ internal void AddSessionStateScopeDefaultVariables() // performance degradation, so we use lazy initialization for all of them. private Dictionary GetAliases() { - if (_alias is null) + if (_alias == null) { // Create the alias table _alias = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -1792,7 +1792,7 @@ private Dictionary GetAliases() // performance degradation, so we use lazy initialization for all of them. private Dictionary GetFunctions() { - if (_functions is null) + if (_functions == null) { // Create the functions table _functions = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -1821,7 +1821,7 @@ private Dictionary GetFunctions() // performance degradation, so we use lazy initialization for all of them. private Dictionary GetAllScopeFunctions() { - if (_allScopeFunctions is null) + if (_allScopeFunctions == null) { if (Parent != null && Parent._allScopeFunctions != null) { diff --git a/src/System.Management.Automation/engine/SessionStateScopeAPIs.cs b/src/System.Management.Automation/engine/SessionStateScopeAPIs.cs index 6271adf387b..9dbcfb9c519 100644 --- a/src/System.Management.Automation/engine/SessionStateScopeAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateScopeAPIs.cs @@ -136,7 +136,7 @@ internal SessionStateScope GetScopeByID(int scopeID) scopeID--; } - if (processingScope is null && scopeID >= 0) + if (processingScope == null && scopeID >= 0) { ArgumentOutOfRangeException outOfRange = PSTraceSource.NewArgumentOutOfRangeException( @@ -275,7 +275,7 @@ internal void RemoveScope(SessionStateScope scope) foreach (PSDriveInfo drive in scope.Drives) { - if (drive is null) + if (drive == null) { continue; } diff --git a/src/System.Management.Automation/engine/SessionStateScopeEnumerator.cs b/src/System.Management.Automation/engine/SessionStateScopeEnumerator.cs index e807c92131c..c3b643e4f31 100644 --- a/src/System.Management.Automation/engine/SessionStateScopeEnumerator.cs +++ b/src/System.Management.Automation/engine/SessionStateScopeEnumerator.cs @@ -33,7 +33,7 @@ public bool MoveNext() // the first scope in the lookup and then advance to the first // scope in the lookup - _currentEnumeratedScope = _currentEnumeratedScope is null ? _initialScope : _currentEnumeratedScope.Parent; + _currentEnumeratedScope = _currentEnumeratedScope == null ? _initialScope : _currentEnumeratedScope.Parent; // If the current scope is the global scope there is nowhere else // to do the lookup, so return false. @@ -59,7 +59,7 @@ SessionStateScope IEnumerator.Current { get { - if (_currentEnumeratedScope is null) + if (_currentEnumeratedScope == null) { throw PSTraceSource.NewInvalidOperationException(); } diff --git a/src/System.Management.Automation/engine/SessionStateSecurityDescriptorInterface.cs b/src/System.Management.Automation/engine/SessionStateSecurityDescriptorInterface.cs index 692d99127b3..73cf89cebdf 100644 --- a/src/System.Management.Automation/engine/SessionStateSecurityDescriptorInterface.cs +++ b/src/System.Management.Automation/engine/SessionStateSecurityDescriptorInterface.cs @@ -30,7 +30,7 @@ internal sealed partial class SessionStateInternal /// internal static ISecurityDescriptorCmdletProvider GetPermissionProviderInstance(CmdletProvider providerInstance) { - if (providerInstance is null) + if (providerInstance == null) { throw PSTraceSource.NewArgumentNullException(nameof(providerInstance)); } @@ -38,7 +38,7 @@ internal static ISecurityDescriptorCmdletProvider GetPermissionProviderInstance( ISecurityDescriptorCmdletProvider permissionCmdletProvider = providerInstance as ISecurityDescriptorCmdletProvider; - if (permissionCmdletProvider is null) + if (permissionCmdletProvider == null) { throw PSTraceSource.NewNotSupportedException( @@ -67,7 +67,7 @@ internal static ISecurityDescriptorCmdletProvider GetPermissionProviderInstance( internal Collection GetSecurityDescriptor(string path, AccessControlSections sections) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -108,7 +108,7 @@ internal void GetSecurityDescriptor( AccessControlSections sections, CmdletProviderContext context) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -198,12 +198,12 @@ private void GetSecurityDescriptor( /// internal Collection SetSecurityDescriptor(string path, ObjectSecurity securityDescriptor) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } - if (securityDescriptor is null) + if (securityDescriptor == null) { throw PSTraceSource.NewArgumentNullException(nameof(securityDescriptor)); } @@ -245,12 +245,12 @@ internal void SetSecurityDescriptor( ObjectSecurity securityDescriptor, CmdletProviderContext context) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } - if (securityDescriptor is null) + if (securityDescriptor == null) { throw PSTraceSource.NewArgumentNullException(nameof(securityDescriptor)); } @@ -392,7 +392,7 @@ internal ObjectSecurity NewSecurityDescriptorFromPath( { ObjectSecurity sd = null; - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -531,12 +531,12 @@ internal ObjectSecurity NewSecurityDescriptorOfType( { ObjectSecurity sd = null; - if (type is null) + if (type == null) { throw PSTraceSource.NewArgumentNullException(nameof(type)); } - if (providerInstance is null) + if (providerInstance == null) { throw PSTraceSource.NewArgumentNullException(nameof(providerInstance)); } diff --git a/src/System.Management.Automation/engine/SessionStateUtils.cs b/src/System.Management.Automation/engine/SessionStateUtils.cs index 7b8b8466760..7c684abd1c3 100644 --- a/src/System.Management.Automation/engine/SessionStateUtils.cs +++ b/src/System.Management.Automation/engine/SessionStateUtils.cs @@ -151,7 +151,7 @@ internal static Collection ConvertArrayToCollection(T[] array) /// internal static bool CollectionContainsValue(IEnumerable collection, object value, IComparer comparer) { - if (collection is null) + if (collection == null) { throw new ArgumentNullException(nameof(collection)); } diff --git a/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs b/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs index d99c5de2daa..9b4028314b8 100644 --- a/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs @@ -52,7 +52,7 @@ internal void AddSessionStateEntry(SessionStateVariableEntry entry) /// internal PSVariable GetVariable(string name, CommandOrigin origin) { - if (name is null) + if (name == null) { throw PSTraceSource.NewArgumentNullException(nameof(name)); } @@ -112,7 +112,7 @@ internal PSVariable GetVariable(string name) /// internal object GetVariableValue(string name) { - if (name is null) + if (name == null) { throw PSTraceSource.NewArgumentNullException(nameof(name)); } @@ -285,7 +285,7 @@ internal object GetVariableValueFromProvider( { scope = null; - if (variablePath is null) + if (variablePath == null) { throw PSTraceSource.NewArgumentNullException(nameof(variablePath)); } @@ -312,7 +312,7 @@ internal object GetVariableValueFromProvider( PSDriveInfo drive = ((IEnumerator)searcher).Current; - if (drive is null) + if (drive == null) { break; } @@ -380,7 +380,7 @@ internal object GetVariableValueFromProvider( false); } - if (readers is null || readers.Count == 0) + if (readers == null || readers.Count == 0) { // The drive was found but the path was wrong or something so return null. // We don't want to continue searching if the provider didn't support content @@ -540,7 +540,7 @@ internal PSVariable GetVariableItem( { scope = null; - if (variablePath is null) + if (variablePath == null) { throw PSTraceSource.NewArgumentNullException(nameof(variablePath)); } @@ -619,7 +619,7 @@ internal PSVariable GetVariableItem( /// internal PSVariable GetVariableAtScope(string name, string scopeID) { - if (name is null) + if (name == null) { throw PSTraceSource.NewArgumentNullException(nameof(name)); } @@ -683,7 +683,7 @@ internal PSVariable GetVariableAtScope(string name, string scopeID) /// internal object GetVariableValueAtScope(string name, string scopeID) { - if (name is null) + if (name == null) { throw PSTraceSource.NewArgumentNullException(nameof(name)); } @@ -769,7 +769,7 @@ internal object GetVariableValueAtScope(string name, string scopeID) false); } - if (readers is null || readers.Count == 0) + if (readers == null || readers.Count == 0) { // The drive was found but the path was wrong or something so return null. // We don't want to continue searching if the provider didn't support content @@ -954,7 +954,7 @@ internal object GetAutomaticVariableValue(AutomaticVariable variable) /// internal void SetVariableValue(string name, object newValue, CommandOrigin origin) { - if (name is null) + if (name == null) { throw PSTraceSource.NewArgumentNullException(nameof(name)); } @@ -1028,7 +1028,7 @@ internal void SetVariableValue(string name, object newValue) /// internal object SetVariable(PSVariable variable, bool force, CommandOrigin origin) { - if (variable is null || string.IsNullOrEmpty(variable.Name)) + if (variable == null || string.IsNullOrEmpty(variable.Name)) { throw PSTraceSource.NewArgumentException(nameof(variable)); } @@ -1136,7 +1136,7 @@ internal object SetVariable( CommandOrigin origin) { object result = null; - if (variablePath is null) + if (variablePath == null) { throw PSTraceSource.NewArgumentNullException(nameof(variablePath)); } @@ -1273,7 +1273,7 @@ internal object SetVariable( false); } - if (writers is null || writers.Count == 0) + if (writers == null || writers.Count == 0) { ItemNotFoundException itemNotFound = new ItemNotFoundException( @@ -1403,7 +1403,7 @@ internal object SetVariable( /// internal object SetVariableAtScope(PSVariable variable, string scopeID, bool force, CommandOrigin origin) { - if (variable is null || string.IsNullOrEmpty(variable.Name)) + if (variable == null || string.IsNullOrEmpty(variable.Name)) { throw PSTraceSource.NewArgumentException(nameof(variable)); } @@ -1439,7 +1439,7 @@ internal object SetVariableAtScope(PSVariable variable, string scopeID, bool for /// internal object NewVariable(PSVariable variable, bool force) { - if (variable is null || string.IsNullOrEmpty(variable.Name)) + if (variable == null || string.IsNullOrEmpty(variable.Name)) { throw PSTraceSource.NewArgumentException(nameof(variable)); } @@ -1483,7 +1483,7 @@ internal object NewVariable(PSVariable variable, bool force) /// internal object NewVariableAtScope(PSVariable variable, string scopeID, bool force) { - if (variable is null || string.IsNullOrEmpty(variable.Name)) + if (variable == null || string.IsNullOrEmpty(variable.Name)) { throw PSTraceSource.NewArgumentException(nameof(variable)); } @@ -1562,7 +1562,7 @@ internal void RemoveVariable(string name) /// internal void RemoveVariable(string name, bool force) { - if (name is null) + if (name == null) { throw PSTraceSource.NewArgumentNullException(nameof(name)); } @@ -1621,7 +1621,7 @@ internal void RemoveVariable(PSVariable variable) /// internal void RemoveVariable(PSVariable variable, bool force) { - if (variable is null) + if (variable == null) { throw PSTraceSource.NewArgumentNullException(nameof(variable)); } @@ -1778,7 +1778,7 @@ internal void RemoveVariableAtScope(PSVariable variable, string scopeID) /// internal void RemoveVariableAtScope(PSVariable variable, string scopeID, bool force) { - if (variable is null) + if (variable == null) { throw PSTraceSource.NewArgumentNullException(nameof(variable)); } diff --git a/src/System.Management.Automation/engine/ShellVariable.cs b/src/System.Management.Automation/engine/ShellVariable.cs index 96b5ead20c1..4be5a96f52b 100644 --- a/src/System.Management.Automation/engine/ShellVariable.cs +++ b/src/System.Management.Automation/engine/ShellVariable.cs @@ -714,7 +714,7 @@ internal void WrapValue() // make a copy if it is... private static object PreserveValueType(object value) { - if (value is null) + if (value == null) return null; // Primitive types are immutable so just return them... diff --git a/src/System.Management.Automation/engine/ThirdPartyAdapter.cs b/src/System.Management.Automation/engine/ThirdPartyAdapter.cs index 757fdaae99e..9840aaa0555 100644 --- a/src/System.Management.Automation/engine/ThirdPartyAdapter.cs +++ b/src/System.Management.Automation/engine/ThirdPartyAdapter.cs @@ -53,7 +53,7 @@ protected override IEnumerable GetTypeNameHierarchy(object obj) ExtendedTypeSystem.GetTypeNameHierarchyError, obj.ToString()); } - if (typeNameHierarchy is null) + if (typeNameHierarchy == null) { throw new ExtendedTypeSystemException( "PSPropertyAdapter.NullReturnValueError", @@ -83,7 +83,7 @@ protected override void DoAddAllProperties(object obj, PSMemberInfoInternalCo ExtendedTypeSystem.GetProperties, obj.ToString()); } - if (properties is null) + if (properties == null) { throw new ExtendedTypeSystemException( "PSPropertyAdapter.NullReturnValueError", @@ -157,7 +157,7 @@ protected override PSProperty DoGetFirstPropertyOrDefault(object obj, MemberName /// private void InitializeProperty(PSAdaptedProperty property, object baseObject) { - if (property.adapter is null) + if (property.adapter == null) { property.adapter = this; property.baseObject = baseObject; @@ -296,7 +296,7 @@ public abstract class PSPropertyAdapter [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "object")] public virtual Collection GetTypeNameHierarchy(object baseObject) { - if (baseObject is null) + if (baseObject == null) { throw new ArgumentNullException(nameof(baseObject)); } diff --git a/src/System.Management.Automation/engine/TypeMetadata.cs b/src/System.Management.Automation/engine/TypeMetadata.cs index cb6ea928162..192042a3def 100644 --- a/src/System.Management.Automation/engine/TypeMetadata.cs +++ b/src/System.Management.Automation/engine/TypeMetadata.cs @@ -49,7 +49,7 @@ internal ParameterSetMetadata(ParameterSetSpecificMetadata psMD) /// Object to copy. internal ParameterSetMetadata(ParameterSetMetadata other) { - if (other is null) + if (other == null) { throw PSTraceSource.NewArgumentNullException(nameof(other)); } @@ -429,7 +429,7 @@ public ParameterMetadata(string name, Type parameterType) /// Object to copy. public ParameterMetadata(ParameterMetadata other) { - if (other is null) + if (other == null) { throw PSTraceSource.NewArgumentNullException(nameof(other)); } @@ -446,7 +446,7 @@ public ParameterMetadata(ParameterMetadata other) } // deep copy of the collection, collection items (Attributes) copied by reference - if (other._attributes is null) + if (other._attributes == null) { _attributes = null; } @@ -461,7 +461,7 @@ public ParameterMetadata(ParameterMetadata other) // deep copy _parameterSets = null; - if (other._parameterSets is null) + if (other._parameterSets == null) { _parameterSets = null; } @@ -623,7 +623,7 @@ public bool SwitchParameter /// public static Dictionary GetParameterMetadata(Type type) { - if (type is null) + if (type == null) { throw PSTraceSource.NewArgumentNullException(nameof(type)); } @@ -1130,7 +1130,7 @@ internal static InternalParameterMetadata Get(RuntimeDefinedParameterDictionary bool processingDynamicParameters, bool checkNames) { - if (runtimeDefinedParameters is null) + if (runtimeDefinedParameters == null) { throw PSTraceSource.NewArgumentNullException("runtimeDefinedParameter"); } @@ -1163,13 +1163,13 @@ internal static InternalParameterMetadata Get(RuntimeDefinedParameterDictionary /// internal static InternalParameterMetadata Get(Type type, ExecutionContext context, bool processingDynamicParameters) { - if (type is null) + if (type == null) { throw PSTraceSource.NewArgumentNullException(nameof(type)); } InternalParameterMetadata result; - if (context is null || !s_parameterMetadataCache.TryGetValue(type.AssemblyQualifiedName, out result)) + if (context == null || !s_parameterMetadataCache.TryGetValue(type.AssemblyQualifiedName, out result)) { result = new InternalParameterMetadata(type, processingDynamicParameters); @@ -1206,7 +1206,7 @@ internal static InternalParameterMetadata Get(Type type, ExecutionContext contex /// internal InternalParameterMetadata(RuntimeDefinedParameterDictionary runtimeDefinedParameters, bool processingDynamicParameters, bool checkNames) { - if (runtimeDefinedParameters is null) + if (runtimeDefinedParameters == null) { throw PSTraceSource.NewArgumentNullException(nameof(runtimeDefinedParameters)); } @@ -1234,7 +1234,7 @@ internal InternalParameterMetadata(RuntimeDefinedParameterDictionary runtimeDefi /// internal InternalParameterMetadata(Type type, bool processingDynamicParameters) { - if (type is null) + if (type == null) { throw PSTraceSource.NewArgumentNullException(nameof(type)); } @@ -1315,7 +1315,7 @@ private void ConstructCompiledParametersUsingRuntimeDefinedParameters( { // When processing dynamic parameters, parameter definitions come from the user, // Invalid data could be passed in, or the parameter could be actually disabled. - if (parameterDefinition is null || parameterDefinition.IsDisabled()) { continue; } + if (parameterDefinition == null || parameterDefinition.IsDisabled()) { continue; } } CompiledCommandParameter parameter = new CompiledCommandParameter(parameterDefinition, processingDynamicParameters); @@ -1403,7 +1403,7 @@ private void AddParameter(MemberInfo member, bool processingDynamicParameters) Type existingParamDeclaringType = existingParameter.DeclaringType; - if (existingParamDeclaringType is null) + if (existingParamDeclaringType == null) { error = true; break; diff --git a/src/System.Management.Automation/engine/TypeTable.cs b/src/System.Management.Automation/engine/TypeTable.cs index ad9700f69e1..c5b889b2586 100644 --- a/src/System.Management.Automation/engine/TypeTable.cs +++ b/src/System.Management.Automation/engine/TypeTable.cs @@ -170,7 +170,7 @@ private void NodeNotFound(int lineNumber, string node, string parent) private ScriptBlock GetScriptBlock(string text, int initialLine) { - if (text is null) + if (text == null) { return null; } @@ -207,7 +207,7 @@ private Type ResolveType(string typeName, int line) { _context.AddError(line, exception.Message); } - else if (type is null) + else if (type == null) { _context.AddError(line, ParserStrings.TypeNotFound, typeName); } @@ -303,7 +303,7 @@ public IEnumerable Read() } } - if (result is null) + if (result == null) NodeNotFound(0, _idTypes, "Document"); return result; @@ -431,7 +431,7 @@ private TypeData Read_Type() { NodeNotFound(lineNumber, _idName, _idType); } - else if (members is null && typeConverter is null && typeAdapter is null) + else if (members == null && typeConverter == null && typeAdapter == null) { _context.AddError(name, lineNumber, TypesXmlStrings.TypeNodeShouldHaveMembersOrTypeConverters); } @@ -771,7 +771,7 @@ private MemberSetData Read_MemberSet() } // Somewhat pointlessly (backcompat), we allow a missing Member node - if (members is null) + if (members == null) { members = new Collection(); } @@ -841,7 +841,7 @@ private PropertySetData Read_PropertySet() { if ((object)_reader.LocalName == (object)_idName) { - if (referencedProperties is null) + if (referencedProperties == null) { referencedProperties = new List(8); } @@ -882,7 +882,7 @@ private PropertySetData Read_PropertySet() if (string.IsNullOrWhiteSpace(name)) NodeNotFound(lineNumber, _idName, _idPropertySet); - if (referencedProperties is null) + if (referencedProperties == null) NodeNotFound(lineNumber, _idReferencedProperties, _idPropertySet); if (_context.errors.Count != errorCount) @@ -938,7 +938,7 @@ private CodeMethodData Read_CodeMethod() methodLineNumber = _readerLineInfo.LineNumber; codeReference = Read_CodeReference(); - if (codeReference is null) + if (codeReference == null) _context.AddError(methodLineNumber, ExtendedTypeSystem.CodeMethodMethodFormat); } else @@ -959,7 +959,7 @@ private CodeMethodData Read_CodeMethod() if (string.IsNullOrWhiteSpace(name)) NodeNotFound(lineNumber, _idName, _idCodeMethod); - if (codeReference is null && methodLineNumber == 0) + if (codeReference == null && methodLineNumber == 0) NodeNotFound(lineNumber, _idCodeReference, _idCodeMethod); if (codeReference != null && !PSCodeMethod.CheckMethodInfo(codeReference)) _context.AddError(methodLineNumber, ExtendedTypeSystem.CodeMethodMethodFormat); @@ -1180,7 +1180,7 @@ private CodePropertyData Read_CodeProperty() getterLineNumber = _readerLineInfo.LineNumber; getter = Read_CodeReference(); - if (getter is null) + if (getter == null) { _context.AddError(getterLineNumber, ExtendedTypeSystem.CodePropertyGetterAndSetterNull); } @@ -1194,7 +1194,7 @@ private CodePropertyData Read_CodeProperty() setterLineNumber = _readerLineInfo.LineNumber; setter = Read_CodeReference(); - if (setter is null) + if (setter == null) { _context.AddError(setterLineNumber, ExtendedTypeSystem.CodePropertyGetterAndSetterNull); } @@ -1220,7 +1220,7 @@ private CodePropertyData Read_CodeProperty() NodeNotFound(lineNumber, _idName, _idCodeProperty); } - if (getter is null && setter is null && getterLineNumber == 0 && setterLineNumber == 0) + if (getter == null && setter == null && getterLineNumber == 0 && setterLineNumber == 0) { _context.AddError(lineNumber, TypesXmlStrings.CodePropertyShouldHaveGetterOrSetter); } @@ -1814,7 +1814,7 @@ internal TypeTableLoadException(ConcurrentBag loadErrors) protected TypeTableLoadException(SerializationInfo info, StreamingContext context) : base(info, context) { - if (info is null) + if (info == null) { throw new PSArgumentNullException(nameof(info)); } @@ -1841,7 +1841,7 @@ protected TypeTableLoadException(SerializationInfo info, StreamingContext contex [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) { throw new PSArgumentNullException(nameof(info)); } @@ -1928,7 +1928,7 @@ internal TypeData(string typeName, bool typesXml) : this() /// public TypeData(Type type) : this() { - if (type is null) + if (type == null) { throw PSTraceSource.NewArgumentNullException(nameof(type)); } @@ -1981,7 +1981,7 @@ public string SerializationMethod set { _serializationMethod = value; - if (_serializationMethod is null) + if (_serializationMethod == null) { StandardMembers.Remove(TypeTable.SerializationMethodNode); return; @@ -2013,7 +2013,7 @@ public Type TargetTypeForDeserialization set { _targetTypeForDeserialization = value; - if (_targetTypeForDeserialization is null) + if (_targetTypeForDeserialization == null) { StandardMembers.Remove(TypeTable.TargetTypeForDeserialization); return; @@ -2072,7 +2072,7 @@ public string DefaultDisplayProperty set { _defaultDisplayProperty = value; - if (_defaultDisplayProperty is null) + if (_defaultDisplayProperty == null) { StandardMembers.Remove(TypeTable.DefaultDisplayProperty); return; @@ -2129,7 +2129,7 @@ public string StringSerializationSource set { - if (value is null) + if (value == null) { // If we set the standard member via StringSerializationSourceProperty, we // don't want to remove it, so only remove the member if our previous @@ -2177,7 +2177,7 @@ public TypeMemberData StringSerializationSourceProperty set { - if (value is null) + if (value == null) { // If we set the standard member via StringSerializationSource, we // don't want to remove it, so only remove the member if our previous @@ -2333,13 +2333,13 @@ public TypeData Copy() } } - newTypeData.DefaultDisplayPropertySet = this.DefaultDisplayPropertySet is null + newTypeData.DefaultDisplayPropertySet = this.DefaultDisplayPropertySet == null ? null : (PropertySetData)this.DefaultDisplayPropertySet.Copy(); - newTypeData.DefaultKeyPropertySet = this.DefaultKeyPropertySet is null + newTypeData.DefaultKeyPropertySet = this.DefaultKeyPropertySet == null ? null : (PropertySetData)this.DefaultKeyPropertySet.Copy(); - newTypeData.PropertySerializationSet = this.PropertySerializationSet is null + newTypeData.PropertySerializationSet = this.PropertySerializationSet == null ? null : (PropertySetData)this.PropertySerializationSet.Copy(); @@ -2714,7 +2714,7 @@ public sealed class PropertySetData : TypeMemberData /// public PropertySetData(IEnumerable referencedProperties) { - if (referencedProperties is null) + if (referencedProperties == null) { throw PSTraceSource.NewArgumentNullException(nameof(referencedProperties)); } @@ -2930,7 +2930,7 @@ private static void AddMember(ConcurrentBag errors, string typeName, PSM member.IsInstance = false; - if (membersCollection[member.name] is null) + if (membersCollection[member.name] == null) { membersCollection.Add(member); } @@ -2954,13 +2954,13 @@ private static bool GetCheckNote(ConcurrentBag errors, string typeName, } } - if (noteAsMemberInfo is null) + if (noteAsMemberInfo == null) { return true; } note = noteAsMemberInfo as PSNoteProperty; - if (note is null) + if (note == null) { AddError(errors, typeName, TypesXmlStrings.MemberShouldBeNote, noteAsMemberInfo.Name); return false; @@ -3025,7 +3025,7 @@ private static bool GetCheckMemberType(ConcurrentBag errors, string type } } - if (member is null) + if (member == null) { return true; } @@ -3139,7 +3139,7 @@ private static bool CheckStandardMembers(ConcurrentBag errors, string ty break; } - if (inheritPropertiesNote != null && inheritPropertiesNote.Value.Equals(false) && propertySerializationSet is null) + if (inheritPropertiesNote != null && inheritPropertiesNote.Value.Equals(false) && propertySerializationSet == null) { AddError( errors, @@ -3327,7 +3327,7 @@ internal static void ProcessScriptPropertyData(ConcurrentBag errors, str ScriptBlock getter = scriptPropertyData.GetScriptBlock; ScriptBlock setter = scriptPropertyData.SetScriptBlock; - if (setter is null && getter is null) + if (setter == null && getter == null) { AddError(errors, typeName, TypesXmlStrings.ScriptPropertyShouldHaveGetterOrSetter); return; @@ -3342,7 +3342,7 @@ internal static void ProcessScriptPropertyData(ConcurrentBag errors, str internal static void ProcessCodePropertyData(ConcurrentBag errors, string typeName, CodePropertyData codePropertyData, PSMemberInfoInternalCollection membersCollection, bool isOverride) { - if ((codePropertyData.GetCodeReference is null) && (codePropertyData.SetCodeReference is null)) + if ((codePropertyData.GetCodeReference == null) && (codePropertyData.SetCodeReference == null)) { AddError(errors, typeName, TypesXmlStrings.CodePropertyShouldHaveGetterOrSetter); return; @@ -3365,7 +3365,7 @@ internal static void ProcessCodePropertyData(ConcurrentBag errors, strin internal static void ProcessScriptMethodData(ConcurrentBag errors, string typeName, ScriptMethodData scriptMethodData, PSMemberInfoInternalCollection membersCollection, bool isOverride) { - if (scriptMethodData.Script is null) + if (scriptMethodData.Script == null) { AddError(errors, typeName, TypesXmlStrings.TypeDataShouldHaveValue, "ScriptMethodData", "Script"); return; @@ -3377,7 +3377,7 @@ internal static void ProcessScriptMethodData(ConcurrentBag errors, strin internal static void ProcessCodeMethodData(ConcurrentBag errors, string typeName, CodeMethodData codeMethodData, PSMemberInfoInternalCollection membersCollection, bool isOverride) { - if (codeMethodData.CodeReference is null) + if (codeMethodData.CodeReference == null) { AddError(errors, typeName, TypesXmlStrings.TypeDataShouldHaveValue, "CodeMethodData", "CodeReference"); return; @@ -3399,7 +3399,7 @@ internal static void ProcessCodeMethodData(ConcurrentBag errors, string internal static void ProcessPropertySetData(ConcurrentBag errors, string typeName, PropertySetData propertySetData, PSMemberInfoInternalCollection membersCollection, bool isOverride) { - if (propertySetData.ReferencedProperties is null || propertySetData.ReferencedProperties.Count == 0) + if (propertySetData.ReferencedProperties == null || propertySetData.ReferencedProperties.Count == 0) { AddError(errors, typeName, TypesXmlStrings.TypeDataShouldHaveValue, "PropertySetData", "ReferencedProperties"); return; @@ -3457,7 +3457,7 @@ private static void ProcessStandardMembers( int newMemberCount = standardMembers.Count() + propertySets.Count(); // If StandardMembers do not exists, we follow the original logic to create the StandardMembers - if (membersCollection[PSStandardMembers] is null) + if (membersCollection[PSStandardMembers] == null) { var memberSetMembers = new PSMemberInfoInternalCollection(newMemberCount); @@ -3515,7 +3515,7 @@ private static void ProcessStandardMembers( // into the original member collection. Replace the old StandardMembers with the new one foreach (PSMemberInfo member in existingMembers) { - if (oldMembersCopy[member.name] is null) + if (oldMembersCopy[member.name] == null) { oldMembersCopy.Add(member); } @@ -3539,7 +3539,7 @@ private static void ProcessStandardMembers( bool isOverride) { // If StandardMembers do not exists, we follow the original logic to create the StandardMembers - if (typeMemberCollection[PSStandardMembers] is null) + if (typeMemberCollection[PSStandardMembers] == null) { CheckStandardMembers(errors, typeName, memberSetMembers); PSMemberSet standardMemberSet = new PSMemberSet(PSStandardMembers, memberSetMembers) @@ -3588,7 +3588,7 @@ private static void ProcessStandardMembers( // into the original member collection. Replace the old StandardMembers with the new one foreach (PSMemberInfo member in existingMembers) { - if (oldMembersCopy[member.name] is null) + if (oldMembersCopy[member.name] == null) { oldMembersCopy.Add(member); } @@ -3646,7 +3646,7 @@ private static void ProcessTypeAdapter( { PSPropertyAdapter psPropertyAdapter = instance as PSPropertyAdapter; - if (psPropertyAdapter is null) + if (psPropertyAdapter == null) { AddError(errors, typeName, TypesXmlStrings.TypeIsNotTypeAdapter, adapterType.FullName); } @@ -3696,7 +3696,7 @@ private void ProcessTypeDataToAdd(ConcurrentBag errors, TypeData typeDat } if (typeData.Members.Count == 0 && typeData.StandardMembers.Count == 0 - && typeData.TypeConverter is null && typeData.TypeAdapter is null + && typeData.TypeConverter == null && typeData.TypeAdapter == null && propertySets.Count == 0 && !typeData.fromTypesXmlFile) { AddError(errors, typeName, TypesXmlStrings.TypeDataShouldNotBeEmpty); @@ -3720,7 +3720,7 @@ private void ProcessTypeDataToAdd(ConcurrentBag errors, TypeData typeDat if (hasStandardMembers) { - if (typeMembers is null) + if (typeMembers == null) { typeMembers = _extendedMembers.GetOrAdd(typeName, GetValueFactoryBasedOnInitCapacity(capacity: 1)); } @@ -3920,7 +3920,7 @@ public static List GetDefaultTypeFiles() /// internal TypeTable(IEnumerable typeFiles, AuthorizationManager authorizationManager, PSHost host) : this(isShared: true) { - if (typeFiles is null) + if (typeFiles == null) { throw PSTraceSource.NewArgumentNullException(nameof(typeFiles)); } @@ -3955,7 +3955,7 @@ internal TypeTable(IEnumerable typeFiles, AuthorizationManager authoriza /// Null if this should not be serialized with SpecificProperties. internal Collection GetSpecificProperties(ConsolidatedString types) { - if (types is null || string.IsNullOrEmpty(types.Key)) + if (types == null || string.IsNullOrEmpty(types.Key)) { return new Collection(); } @@ -3972,7 +3972,7 @@ internal Collection GetSpecificProperties(ConsolidatedString types) PSMemberSet settings = typeMembers[PSStandardMembers] as PSMemberSet; PSPropertySet typeProperties = settings?.Members[PropertySerializationSet] as PSPropertySet; - if (typeProperties is null) + if (typeProperties == null) { continue; } @@ -4024,7 +4024,7 @@ internal T GetFirstMemberOrDefault(ConsolidatedString types, MemberNamePredic internal PSMemberInfoInternalCollection GetMembers(ConsolidatedString types) { - if ((types is null) || string.IsNullOrEmpty(types.Key)) + if ((types == null) || string.IsNullOrEmpty(types.Key)) { return new PSMemberInfoInternalCollection(); } @@ -4047,7 +4047,7 @@ private PSMemberInfoInternalCollection MemberFactory(string k, Con PSMemberInfo currentMember = retValue[typeMember.Name]; // If the member was not present, we add it - if (currentMember is null) + if (currentMember == null) { retValue.Add(typeMember.Copy()); continue; @@ -4059,7 +4059,7 @@ private PSMemberInfoInternalCollection MemberFactory(string k, Con // if we are not in a memberset inherit members situation we just replace // the current member with the new more specific member - if (currentMemberAsMemberSet is null || typeMemberAsMemberSet is null || + if (currentMemberAsMemberSet == null || typeMemberAsMemberSet == null || !typeMemberAsMemberSet.InheritMembers) { retValue.Remove(typeMember.Name); @@ -4071,7 +4071,7 @@ private PSMemberInfoInternalCollection MemberFactory(string k, Con // typeMembers to the existing memberset. foreach (PSMemberInfo typeMemberAsMemberSetMember in typeMemberAsMemberSet.Members) { - if (currentMemberAsMemberSet.Members[typeMemberAsMemberSetMember.Name] is null) + if (currentMemberAsMemberSet.Members[typeMemberAsMemberSetMember.Name] == null) { ((PSMemberInfoIntegratingCollection)currentMemberAsMemberSet.Members) .AddToTypesXmlCache(typeMemberAsMemberSetMember, false); @@ -4113,7 +4113,7 @@ internal object GetTypeConverter(string typeName) /// The type adapter or null, if there is no adapter. internal PSObject.AdapterSet GetTypeAdapter(Type type) { - if (type is null) + if (type == null) { return null; } @@ -4553,7 +4553,7 @@ internal void Initialize( bool isProductCode; string fileContents = GetModuleContents(snapinName, fileToLoad, errors, authorizationManager, host, out isFullyTrusted, out failToLoadFile, out isProductCode); - if (fileContents is null) + if (fileContents == null) { return; } @@ -4667,7 +4667,7 @@ private void UpdateWithModuleContents( /// A TypeData instance to update the TypeTable. public void AddType(TypeData typeData) { - if (typeData is null) + if (typeData == null) throw PSTraceSource.NewArgumentNullException(nameof(typeData)); Dbg.Assert(isShared, "This method should only be called by the developer user. It should not be used internally."); @@ -4739,12 +4739,12 @@ internal void Update( PSHost host, out bool failToLoadFile) { - if (filePath is null) + if (filePath == null) { throw new ArgumentNullException(nameof(filePath)); } - if (errors is null) + if (errors == null) { throw new ArgumentNullException(nameof(errors)); } @@ -4817,9 +4817,9 @@ internal void Update( ConcurrentBag errors, bool isRemove) { - if (type is null) + if (type == null) throw new ArgumentNullException(nameof(type)); - if (errors is null) + if (errors == null) throw new ArgumentNullException(nameof(errors)); if (isShared) diff --git a/src/System.Management.Automation/engine/TypeTable_Types_Ps1Xml.cs b/src/System.Management.Automation/engine/TypeTable_Types_Ps1Xml.cs index a2f7f244ce7..aad2f70246e 100644 --- a/src/System.Management.Automation/engine/TypeTable_Types_Ps1Xml.cs +++ b/src/System.Management.Automation/engine/TypeTable_Types_Ps1Xml.cs @@ -28,7 +28,7 @@ private static Func> GetVal } int cacheIndex = capacity - 1; - if (s_valueFactoryCache[cacheIndex] is null) + if (s_valueFactoryCache[cacheIndex] == null) { Interlocked.CompareExchange( ref s_valueFactoryCache[cacheIndex], diff --git a/src/System.Management.Automation/engine/UserFeedbackParameters.cs b/src/System.Management.Automation/engine/UserFeedbackParameters.cs index bc0d4639f6c..feb1464d922 100644 --- a/src/System.Management.Automation/engine/UserFeedbackParameters.cs +++ b/src/System.Management.Automation/engine/UserFeedbackParameters.cs @@ -16,7 +16,7 @@ public sealed class PagingParameters internal PagingParameters(MshCommandRuntime commandRuntime) { - if (commandRuntime is null) + if (commandRuntime == null) { throw PSTraceSource.NewArgumentNullException(nameof(commandRuntime)); } @@ -114,7 +114,7 @@ public sealed class ShouldProcessParameters /// internal ShouldProcessParameters(MshCommandRuntime commandRuntime) { - if (commandRuntime is null) + if (commandRuntime == null) { throw PSTraceSource.NewArgumentNullException(nameof(commandRuntime)); } diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index aeb6abe527a..b3d62c4b06f 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -312,7 +312,7 @@ internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int /// Does not return a value. internal static void CheckKeyArg(byte[] arg, string argName) { - if (arg is null) + if (arg == null) { throw PSTraceSource.NewArgumentNullException(argName); } @@ -339,7 +339,7 @@ internal static void CheckKeyArg(byte[] arg, string argName) /// Does not return a value. internal static void CheckArgForNullOrEmpty(string arg, string argName) { - if (arg is null) + if (arg == null) { throw PSTraceSource.NewArgumentNullException(argName); } @@ -358,7 +358,7 @@ internal static void CheckArgForNullOrEmpty(string arg, string argName) /// Does not return a value. internal static void CheckArgForNull(object arg, string argName) { - if (arg is null) + if (arg == null) { throw PSTraceSource.NewArgumentNullException(argName); } @@ -372,7 +372,7 @@ internal static void CheckArgForNull(object arg, string argName) /// Does not return a value. internal static void CheckSecureStringArg(SecureString arg, string argName) { - if (arg is null) + if (arg == null) { throw PSTraceSource.NewArgumentNullException(argName); } @@ -409,7 +409,7 @@ internal static string GetStringFromSecureString(SecureString ss) internal static TypeTable GetTypeTableFromExecutionContextTLS() { ExecutionContext ecFromTLS = Runspaces.LocalPipeline.GetExecutionContextFromTLS(); - if (ecFromTLS is null) + if (ecFromTLS == null) { return null; } @@ -497,7 +497,7 @@ internal static string GetApplicationBase(string shellId) private static string[] GetProductFolderDirectories() { - if (s_productFolderDirectories is null) + if (s_productFolderDirectories == null) { List baseDirectories = new List(); @@ -666,7 +666,7 @@ internal static bool IsPSVersionSupported(string ver) /// True if supported, false otherwise. internal static bool IsPSVersionSupported(Version checkVersion) { - if (checkVersion is null) + if (checkVersion == null) { return false; } @@ -966,7 +966,7 @@ private static bool TrySetPolicySettingsFromRegistryKey(object instance, Type in using (RegistryKey gpoKey = rootKey.OpenSubKey(gpoKeyPath)) { // If the corresponding GPO key doesn't exist, return null - if (gpoKey is null) { return null; } + if (gpoKey == null) { return null; } // The corresponding GPO key exists, then create an instance of T // and populate its properties with the settings @@ -986,7 +986,7 @@ private static bool TrySetPolicySettingsFromRegistryKey(object instance, Type in using (RegistryKey winPowershellGpoKey = rootKey.OpenSubKey(winPowershellGpoKeyPath)) { // If the corresponding Windows PS GPO key doesn't exist, return null - if (winPowershellGpoKey is null) { return null; } + if (winPowershellGpoKey == null) { return null; } isAnyPropertySet = TrySetPolicySettingsFromRegistryKey(tInstance, tType, winPowershellGpoKey); } } @@ -1037,7 +1037,7 @@ internal static void EnsureModuleLoaded(string module, ExecutionContext context) { List loadedModules = context.Modules.GetModules(new string[] { module }, false); - if ((loadedModules is null) || (loadedModules.Count == 0)) + if ((loadedModules == null) || (loadedModules.Count == 0)) { CommandInfo commandInfo = new CmdletInfo("Import-Module", typeof(Microsoft.PowerShell.Commands.ImportModuleCommand), null, null, context); @@ -1113,7 +1113,7 @@ internal static List GetModules(string module, ExecutionContext co Collection gmoOutPut = ps.Invoke(); if (gmoOutPut != null) { - if (result is null) + if (result == null) { result = gmoOutPut.ToList(); } @@ -1173,7 +1173,7 @@ internal static List GetModules(ModuleSpecification fullyQualified Collection gmoOutput = ps.Invoke(); if (gmoOutput != null) { - if (result is null) + if (result == null) { result = gmoOutput.ToList(); } @@ -1675,7 +1675,7 @@ internal static bool TryRunAsImplicitBatch(string command, Runspace runspace) { var scriptBlock = ScriptBlock.Create(command); var scriptBlockAst = scriptBlock.Ast as ScriptBlockAst; - if (scriptBlockAst is null) + if (scriptBlockAst == null) { return false; } @@ -1721,7 +1721,7 @@ internal static bool TryRunAsImplicitBatch(string command, Runspace runspace) } // Commands must be from implicit remoting module - if (cmdInfo.Module is null || string.IsNullOrEmpty(cmdInfo.ModuleName)) + if (cmdInfo.Module == null || string.IsNullOrEmpty(cmdInfo.ModuleName)) { WriteVerbose(ps, string.Format(CultureInfo.CurrentCulture, ParserStrings.ImplicitRemotingPipelineBatchingNotImplicitCommand, cmdInfo.Name)); success = false; @@ -1780,7 +1780,7 @@ internal static bool TryRunAsImplicitBatch(string command, Runspace runspace) ps.Commands.Clear(); ps.Commands.AddCommand("Get-PSSession").AddParameter("InstanceId", psSessionId); var psSession = ps.Invoke().FirstOrDefault(); - if (psSession is null || (ps.Streams.Error.Count > 0) || (psSession.Availability != RunspaceAvailability.Available)) + if (psSession == null || (ps.Streams.Error.Count > 0) || (psSession.Availability != RunspaceAvailability.Available)) { WriteVerbose(ps, ParserStrings.ImplicitRemotingPipelineBatchingNoPSSession); return false; @@ -1862,7 +1862,7 @@ private static bool TryGetCommandInfoList(PowerShell ps, HashSet command if (specialCaseWhereCommandAlias) { var cmdInfo = ps.Runspace.ExecutionContext.SessionState.InvokeCommand.GetCommand(WhereObjectCommandAlias, CommandTypes.Alias); - if (cmdInfo is null) + if (cmdInfo == null) { return false; } @@ -1923,7 +1923,7 @@ public override AstVisitAction VisitPipeline(PipelineAst pipelineAst) // know that we have at least: // * a NamedBlockAst (the end block) // * a ScriptBlockAst (the ast we're comparing to) - if (pipelineAst.GetPureExpression() is null || pipelineAst.Parent.Parent == ScriptBeingConverted) + if (pipelineAst.GetPureExpression() == null || pipelineAst.Parent.Parent == ScriptBeingConverted) { ThrowError( new ImplicitRemotingBatchingNotSupportedException( @@ -2214,7 +2214,7 @@ internal void Push(T item) /// internal T Pop() { - if (this.First is null) + if (this.First == null) { throw new InvalidOperationException(SessionStateStrings.BoundedStackIsEmpty); } @@ -2245,7 +2245,7 @@ internal sealed class ReadOnlyBag : IEnumerable /// internal ReadOnlyBag(HashSet hashset) { - if (hashset is null) + if (hashset == null) { throw new ArgumentNullException(nameof(hashset)); } diff --git a/src/System.Management.Automation/engine/VariableAttributeCollection.cs b/src/System.Management.Automation/engine/VariableAttributeCollection.cs index 0e8fe3c1d10..f41bb3380ba 100644 --- a/src/System.Management.Automation/engine/VariableAttributeCollection.cs +++ b/src/System.Management.Automation/engine/VariableAttributeCollection.cs @@ -28,7 +28,7 @@ internal class PSVariableAttributeCollection : Collection /// internal PSVariableAttributeCollection(PSVariable variable) { - if (variable is null) + if (variable == null) { throw PSTraceSource.NewArgumentNullException(nameof(variable)); } diff --git a/src/System.Management.Automation/engine/VariableInterfaces.cs b/src/System.Management.Automation/engine/VariableInterfaces.cs index d3af0300456..90411860b6d 100644 --- a/src/System.Management.Automation/engine/VariableInterfaces.cs +++ b/src/System.Management.Automation/engine/VariableInterfaces.cs @@ -33,7 +33,7 @@ private PSVariableIntrinsics() /// internal PSVariableIntrinsics(SessionStateInternal sessionState) { - if (sessionState is null) + if (sessionState == null) { throw PSTraceSource.NewArgumentException(nameof(sessionState)); } diff --git a/src/System.Management.Automation/engine/cmdlet.cs b/src/System.Management.Automation/engine/cmdlet.cs index 70436fb40fe..b676337531e 100644 --- a/src/System.Management.Automation/engine/cmdlet.cs +++ b/src/System.Management.Automation/engine/cmdlet.cs @@ -269,7 +269,7 @@ public virtual string GetResourceString(string baseName, string resourceId) throw PSTraceSource.NewArgumentException(nameof(baseName), GetErrorText.ResourceBaseNameFailure, baseName); } - if (retValue is null) + if (retValue == null) { throw PSTraceSource.NewArgumentException(nameof(resourceId), GetErrorText.ResourceIdFailure, resourceId); } @@ -1597,7 +1597,7 @@ internal List GetResults() } var result = new List(); - if (this.commandRuntime is null) + if (this.commandRuntime == null) { this.CommandRuntime = new DefaultCommandRuntime(result); } @@ -1718,7 +1718,7 @@ public void ThrowTerminatingError(ErrorRecord errorRecord) { using (PSTransactionManager.GetEngineProtectionScope()) { - if (errorRecord is null) + if (errorRecord == null) throw new ArgumentNullException(nameof(errorRecord)); if (commandRuntime != null) diff --git a/src/System.Management.Automation/engine/debugger/Breakpoint.cs b/src/System.Management.Automation/engine/debugger/Breakpoint.cs index 4fca64dc5d6..f9f550da7fa 100644 --- a/src/System.Management.Automation/engine/debugger/Breakpoint.cs +++ b/src/System.Management.Automation/engine/debugger/Breakpoint.cs @@ -104,7 +104,7 @@ protected Breakpoint(string script, ScriptBlock action, int id) internal BreakpointAction Trigger() { ++HitCount; - if (Action is null) + if (Action == null) { return BreakpointAction.Break; } @@ -211,7 +211,7 @@ internal override bool RemoveSelf(ScriptDebugger debugger) => private bool CommandInfoMatches(CommandInfo commandInfo) { - if (commandInfo is null) + if (commandInfo == null) return false; if (CommandPattern.IsMatch(commandInfo.Name)) @@ -244,7 +244,7 @@ internal bool Trigger(InvocationInfo invocationInfo) // invocationInfo.MyCommand can be null when invoked via ScriptBlock.Invoke() if (CommandPattern.IsMatch(invocationInfo.InvocationName) || CommandInfoMatches(invocationInfo.MyCommand)) { - return (Script is null || Script.Equals(invocationInfo.ScriptName, StringComparison.OrdinalIgnoreCase)); + return (Script == null || Script.Equals(invocationInfo.ScriptName, StringComparison.OrdinalIgnoreCase)); } return false; @@ -338,7 +338,7 @@ internal bool Trigger(string currentScriptFile, bool read) if (AccessMode != VariableAccessMode.ReadWrite && AccessMode != (read ? VariableAccessMode.Read : VariableAccessMode.Write)) return false; - if (Script is null || Script.Equals(currentScriptFile, StringComparison.OrdinalIgnoreCase)) + if (Script == null || Script.Equals(currentScriptFile, StringComparison.OrdinalIgnoreCase)) { return Trigger() == BreakpointAction.Break; } @@ -534,10 +534,10 @@ internal bool TrySetBreakpoint(string scriptFile, FunctionContext functionContex { var ast = scriptBlock.Ast; var bodyAst = ((IParameterMetadataProvider)ast).Body; - if ((bodyAst.DynamicParamBlock is null || bodyAst.DynamicParamBlock.Extent.IsAfter(Line, Column)) && - (bodyAst.BeginBlock is null || bodyAst.BeginBlock.Extent.IsAfter(Line, Column)) && - (bodyAst.ProcessBlock is null || bodyAst.ProcessBlock.Extent.IsAfter(Line, Column)) && - (bodyAst.EndBlock is null || bodyAst.EndBlock.Extent.IsAfter(Line, Column))) + if ((bodyAst.DynamicParamBlock == null || bodyAst.DynamicParamBlock.Extent.IsAfter(Line, Column)) && + (bodyAst.BeginBlock == null || bodyAst.BeginBlock.Extent.IsAfter(Line, Column)) && + (bodyAst.ProcessBlock == null || bodyAst.ProcessBlock.Extent.IsAfter(Line, Column)) && + (bodyAst.EndBlock == null || bodyAst.EndBlock.Extent.IsAfter(Line, Column))) { SetBreakpoint(functionContext, 0); return true; diff --git a/src/System.Management.Automation/engine/debugger/debugger.cs b/src/System.Management.Automation/engine/debugger/debugger.cs index 07c5f179210..d19815ac303 100644 --- a/src/System.Management.Automation/engine/debugger/debugger.cs +++ b/src/System.Management.Automation/engine/debugger/debugger.cs @@ -248,7 +248,7 @@ public bool UseDefaultProcessing /// public StartRunspaceDebugProcessingEventArgs(Runspace runspace) { - if (runspace is null) { throw new PSArgumentNullException(nameof(runspace)); } + if (runspace == null) { throw new PSArgumentNullException(nameof(runspace)); } Runspace = runspace; } @@ -274,7 +274,7 @@ public Runspace Runspace /// public ProcessRunspaceDebugEndEventArgs(Runspace runspace) { - if (runspace is null) { throw new PSArgumentNullException(nameof(runspace)); } + if (runspace == null) { throw new PSArgumentNullException(nameof(runspace)); } Runspace = runspace; } @@ -525,7 +525,7 @@ protected bool IsDebuggerBreakpointUpdatedEventSubscribed() /// protected void RaiseStartRunspaceDebugProcessingEvent(StartRunspaceDebugProcessingEventArgs args) { - if (args is null) { throw new PSArgumentNullException(nameof(args)); } + if (args == null) { throw new PSArgumentNullException(nameof(args)); } StartRunspaceDebugProcessing.SafeInvoke(this, args); } @@ -533,7 +533,7 @@ protected void RaiseStartRunspaceDebugProcessingEvent(StartRunspaceDebugProcessi /// protected void RaiseRunspaceProcessingCompletedEvent(ProcessRunspaceDebugEndEventArgs args) { - if (args is null) { throw new PSArgumentNullException(nameof(args)); } + if (args == null) { throw new PSArgumentNullException(nameof(args)); } RunspaceDebugProcessingCompleted.SafeInvoke(this, args); } @@ -1077,7 +1077,7 @@ private bool IsLocalSession { get { - if (_isLocalSession is null) + if (_isLocalSession == null) { // Remote debug sessions always have a ServerRemoteHost. Otherwise it is a local session. _isLocalSession = !(((_context.InternalHost.ExternalHost != null) && @@ -1176,7 +1176,7 @@ internal void EnterScriptFunction(FunctionContext functionContext) bool checkLineBp = CheckCommand(invocationInfo); SetupBreakpoints(functionContext); - if (functionContext._debuggerStepThrough && _overOrOutFrame is null && _steppingMode == SteppingMode.StepIn) + if (functionContext._debuggerStepThrough && _overOrOutFrame == null && _steppingMode == SteppingMode.StepIn) { // Treat like step out, but only if we're not already stepping out ResumeExecution(DebuggerResumeAction.StepOut); @@ -1244,7 +1244,7 @@ internal void RegisterScriptFile(string path, string scriptContents) // If script contents have changed, or if the file got collected, we must rebind the breakpoints. string oldScriptContents; boundBreakpoints.Item1.TryGetTarget(out oldScriptContents); - if (oldScriptContents is null || !oldScriptContents.Equals(scriptContents, StringComparison.Ordinal)) + if (oldScriptContents == null || !oldScriptContents.Equals(scriptContents, StringComparison.Ordinal)) { UnbindBoundBreakpoints(boundBreakpoints.Item2.Values.ToList()); _boundBreakpoints[path] = Tuple.Create(new WeakReference(scriptContents), new ConcurrentDictionary()); @@ -1320,7 +1320,7 @@ internal VariableBreakpoint AddVariableBreakpoint(VariableBreakpoint breakpoint) private void UpdateBreakpoints(FunctionContext functionContext) { - if (functionContext._breakPoints is null) + if (functionContext._breakPoints == null) { // This should be rare - setting a breakpoint inside a script, but debugger hadn't started. SetupBreakpoints(functionContext); @@ -1463,7 +1463,7 @@ private List GetVariableBreakpointsToTrigger(string variable } } - if (breakpoints is null) + if (breakpoints == null) return null; var callStackInfo = _callStack.Last(); @@ -1556,14 +1556,14 @@ internal void OnSequencePointHit(FunctionContext functionContext) UpdateBreakpoints(functionContext); if (_steppingMode == SteppingMode.StepIn && - (_overOrOutFrame is null || _callStack.Last() == _overOrOutFrame)) + (_overOrOutFrame == null || _callStack.Last() == _overOrOutFrame)) { if (!_callStack.Last().IsFrameHidden) { _overOrOutFrame = null; StopOnSequencePoint(functionContext, s_emptyBreakpointList); } - else if (_overOrOutFrame is null) + else if (_overOrOutFrame == null) { // Treat like step out, but only if we're not already stepping out ResumeExecution(DebuggerResumeAction.StepOut); @@ -1965,7 +1965,7 @@ private bool WaitForDebugStopSubscriber() if (_preserveUnhandledDebugStopEvent) { // Lazily create the event object. - if (_preserveDebugStopEvent is null) + if (_preserveDebugStopEvent == null) { _preserveDebugStopEvent = new ManualResetEventSlim(true); } @@ -2027,7 +2027,7 @@ private void SetPendingBreakpoints(FunctionContext functionContext) var currentScriptFile = functionContext._file; // If we're not in a file, we can't have any line breakpoints. - if (currentScriptFile is null) + if (currentScriptFile == null) return; // Normally we register a script file when the script is run or the module is imported, @@ -2164,11 +2164,11 @@ private bool IsSystemLockedDown { get { - if (_isSystemLockedDown is null) + if (_isSystemLockedDown == null) { lock (_syncObject) { - if (_isSystemLockedDown is null) + if (_isSystemLockedDown == null) { _isSystemLockedDown = (System.Management.Automation.Security.SystemPolicy.GetSystemLockdownPolicy() == System.Management.Automation.Security.SystemEnforcementMode.Enforce); @@ -2307,12 +2307,12 @@ public override DebuggerStopEventArgs GetDebuggerStopArgs() /// DebuggerCommandResults. public override DebuggerCommandResults ProcessCommand(PSCommand command, PSDataCollection output) { - if (command is null) + if (command == null) { throw new PSArgumentNullException(nameof(command)); } - if (output is null) + if (output == null) { throw new PSArgumentNullException(nameof(output)); } @@ -2340,7 +2340,7 @@ public override DebuggerCommandResults ProcessCommand(PSCommand command, PSDataC // Otherwise let root script debugger handle it. // LocalRunspace localRunspace = _context.CurrentRunspace as LocalRunspace; - if (localRunspace is null) + if (localRunspace == null) { throw new PSInvalidOperationException( DebuggerStrings.CannotProcessDebuggerCommandNotStopped, @@ -2371,7 +2371,7 @@ public override DebuggerCommandResults ProcessCommand(PSCommand command, PSDataC { foreach (var item in internalOutput.ReadAll()) { - if (item is null) { continue; } + if (item == null) { continue; } DebuggerCommand dbgCmd = item.BaseObject as DebuggerCommand; if (dbgCmd != null) @@ -2581,7 +2581,7 @@ internal override DebuggerCommand InternalProcessCommand(string command, IList

True if source listed successfully. internal override bool InternalProcessListCommand(int lineNum, IList output) { - if (!DebuggerStopped || (_currentInvocationInfo is null)) { return false; } + if (!DebuggerStopped || (_currentInvocationInfo == null)) { return false; } // Create an Invocation object that has full source script from script debugger plus // line information provided from caller. @@ -2918,7 +2918,7 @@ private Debugger GetRunspaceDebugger(int runspaceId) /// internal override void DebugJob(Job job, bool breakAll) { - if (job is null) { throw new PSArgumentNullException(nameof(job)); } + if (job == null) { throw new PSArgumentNullException(nameof(job)); } lock (_syncObject) { @@ -2992,7 +2992,7 @@ private bool TryAddDebugJob(Job job, bool breakAll) internal override void StopDebugJob(Job job) { // Parameter validation. - if (job is null) { throw new PSArgumentNullException(nameof(job)); } + if (job == null) { throw new PSArgumentNullException(nameof(job)); } SetInternalDebugMode(InternalDebugMode.Disabled); @@ -3037,7 +3037,7 @@ internal static void SetDebugJobAsync(IJobDebugger debuggableJob, bool isAsync) /// internal override void DebugRunspace(Runspace runspace, bool breakAll) { - if (runspace is null) + if (runspace == null) { throw new PSArgumentNullException(nameof(runspace)); } @@ -3057,7 +3057,7 @@ internal override void DebugRunspace(Runspace runspace, bool breakAll) } } - if (runspace.Debugger is null) + if (runspace.Debugger == null) { throw new PSInvalidOperationException( string.Format(CultureInfo.InvariantCulture, DebuggerStrings.RunspaceDebuggingNoRunspaceDebugger, runspace.Name)); @@ -3082,7 +3082,7 @@ internal override void DebugRunspace(Runspace runspace, bool breakAll) /// Runspace. internal override void StopDebugRunspace(Runspace runspace) { - if (runspace is null) { throw new PSArgumentNullException(nameof(runspace)); } + if (runspace == null) { throw new PSArgumentNullException(nameof(runspace)); } SetInternalDebugMode(InternalDebugMode.Disabled); @@ -3623,7 +3623,7 @@ private bool StopCommandForActiveDebugger() internal override void StartMonitoringRunspace(PSMonitorRunspaceInfo runspaceInfo) { - if (runspaceInfo is null || runspaceInfo.Runspace is null) { return; } + if (runspaceInfo == null || runspaceInfo.Runspace == null) { return; } if ((runspaceInfo.Runspace.Debugger != null) && runspaceInfo.Runspace.Debugger.Equals(this)) @@ -3640,7 +3640,7 @@ internal override void StartMonitoringRunspace(PSMonitorRunspaceInfo runspaceInf internal override void EndMonitoringRunspace(PSMonitorRunspaceInfo runspaceInfo) { - if (runspaceInfo is null || runspaceInfo.Runspace is null) { return; } + if (runspaceInfo == null || runspaceInfo.Runspace == null) { return; } RemoveFromRunningRunspaceList(runspaceInfo.Runspace); } @@ -3768,7 +3768,7 @@ private void HandleRunspaceStateChanged(object sender, RunspaceStateEventArgs e) private void HandleMonitorRunningRSDebuggerStop(object sender, DebuggerStopEventArgs args) { - if (sender is null || args is null) { return; } + if (sender == null || args == null) { return; } Debugger senderDebugger = sender as Debugger; bool pushSucceeded = false; @@ -3786,7 +3786,7 @@ private void HandleMonitorRunningRSDebuggerStop(object sender, DebuggerStopEvent // Get nested debugger runspace info. NestedRunspaceDebugger nestedDebugger = senderDebugger as NestedRunspaceDebugger; - if (nestedDebugger is null) { return; } + if (nestedDebugger == null) { return; } PSMonitorRunspaceType runspaceType = nestedDebugger.RunspaceType; @@ -3862,7 +3862,7 @@ private bool SetUpDebuggerOnRunspace(Runspace runspace) // the runspace debugger is available. if ((runspace.Debugger != null) && (runspaceInfo != null) && - (runspaceInfo.NestedDebugger is null)) + (runspaceInfo.NestedDebugger == null)) { try { @@ -4000,7 +4000,7 @@ private bool IsDebuggerReady() private void WaitForDebugComplete() { - if (_runspaceDebugCompleteEvent is null) + if (_runspaceDebugCompleteEvent == null) { _runspaceDebugCompleteEvent = new ManualResetEventSlim(false); } @@ -4061,7 +4061,7 @@ public void Dispose() internal void EnableTracing(int traceLevel, bool? step) { // Enable might actually be disabling depending on the arguments. - if (traceLevel < 1 && (step is null || !(bool)step)) + if (traceLevel < 1 && (step == null || !(bool)step)) { DisableTracing(); return; @@ -4097,7 +4097,7 @@ internal void Trace(string messageId, string resourceString, params object[] arg ActionPreference pref = ActionPreference.Continue; string message; - if (args is null || args.Length == 0) + if (args == null || args.Length == 0) { // Don't format in case the string contains literal curly braces message = resourceString; @@ -4226,7 +4226,7 @@ public NestedRunspaceDebugger( PSMonitorRunspaceType runspaceType, Guid parentDebuggerId) { - if (runspace is null || runspace.Debugger is null) + if (runspace == null || runspace.Debugger == null) { throw new PSArgumentNullException(nameof(runspace)); } @@ -4651,7 +4651,7 @@ private object DrainAndBlockRemoteOutput() { // We do this only for remote runspaces. RemoteRunspace remoteRunspace = _runspace as RemoteRunspace; - if (remoteRunspace is null) { return null; } + if (remoteRunspace == null) { return null; } var runningPowerShell = remoteRunspace.GetCurrentBasePowerShell(); if (runningPowerShell != null) @@ -4676,7 +4676,7 @@ private object DrainAndBlockRemoteOutput() private void RestoreRemoteOutput(object runningCmd) { - if (runningCmd is null) { return; } + if (runningCmd == null) { return; } var runningPowerShell = runningCmd as PowerShell; if (runningPowerShell != null) @@ -4726,7 +4726,7 @@ public EmbeddedRunspaceDebugger( Guid parentDebuggerId) : base(runspace, runspaceType, parentDebuggerId) { - if (rootDebugger is null) + if (rootDebugger == null) { throw new PSArgumentNullException(nameof(rootDebugger)); } @@ -4810,7 +4810,7 @@ protected override bool HandleListCommand(PSDataCollection output) /// InvocationInfo. internal override InvocationInfo FixupInvocationInfo(InvocationInfo debugStopInvocationInfo) { - if (debugStopInvocationInfo is null) { return null; } + if (debugStopInvocationInfo == null) { return null; } // Check to see if this nested debug stop is called from within // a known parent source. @@ -4867,11 +4867,11 @@ private InvocationInfo CreateInvocationInfoFromParent( int debugStartColNumber, int debugEndColNumber) { - if (parentStackFrame is null) { return null; } + if (parentStackFrame == null) { return null; } // Attempt to find parent script file create script block with Ast to // find correct line and offset adjustments. - if ((_parentScriptBlockAst is null) && + if ((_parentScriptBlockAst == null) && !string.IsNullOrEmpty(parentStackFrame.ScriptName) && System.IO.File.Exists(parentStackFrame.ScriptName)) { @@ -4974,7 +4974,7 @@ private object DrainAndBlockRemoteOutput() private void RestoreRemoteOutput(object runningCmd) { - if (runningCmd is null) { return; } + if (runningCmd == null) { return; } PowerShell command = runningCmd as PowerShell; if (command != null) @@ -5267,12 +5267,12 @@ private void DisplayHelp(PSHost host, IList output) ///

private void DisplayScript(PSHost host, IList output, InvocationInfo invocationInfo, Match match) { - if (invocationInfo is null) { return; } + if (invocationInfo == null) { return; } // // Get the source code for the script // - if (_lines is null) + if (_lines == null) { string scriptText = invocationInfo.GetFullScript(); if (string.IsNullOrEmpty(scriptText)) @@ -5475,7 +5475,7 @@ public PSDebugContext(InvocationInfo invocationInfo, List breakpoint /// The object that caused the script to break in the debugger. public PSDebugContext(InvocationInfo invocationInfo, List breakpoints, object triggerObject) { - if (breakpoints is null) + if (breakpoints == null) { throw new PSArgumentNullException(nameof(breakpoints)); } @@ -5527,7 +5527,7 @@ public CallStackFrame(InvocationInfo invocationInfo) /// Invocation Info. internal CallStackFrame(FunctionContext functionContext, InvocationInfo invocationInfo) { - if (invocationInfo is null) + if (invocationInfo == null) { throw new PSArgumentNullException(nameof(invocationInfo)); } @@ -5604,7 +5604,7 @@ public Dictionary GetFrameVariables() { var result = new Dictionary(StringComparer.OrdinalIgnoreCase); - if (FunctionContext._executionContext is null) { return result; } + if (FunctionContext._executionContext == null) { return result; } var scope = FunctionContext._executionContext.EngineSessionState.CurrentScope; while (scope != null) @@ -5683,7 +5683,7 @@ public static class DebuggerUtils /// True if command can be added to history. public static bool ShouldAddCommandToHistory(string command) { - if (command is null) + if (command == null) { throw new PSArgumentNullException(nameof(command)); } @@ -5701,12 +5701,12 @@ public static bool ShouldAddCommandToHistory(string command) /// PSMonitorRunspaceInfo. public static void StartMonitoringRunspace(Debugger debugger, PSMonitorRunspaceInfo runspaceInfo) { - if (debugger is null) + if (debugger == null) { throw new PSArgumentNullException(nameof(debugger)); } - if (runspaceInfo is null) + if (runspaceInfo == null) { throw new PSArgumentNullException(nameof(runspaceInfo)); } @@ -5721,12 +5721,12 @@ public static void StartMonitoringRunspace(Debugger debugger, PSMonitorRunspaceI /// PSMonitorRunspaceInfo. public static void EndMonitoringRunspace(Debugger debugger, PSMonitorRunspaceInfo runspaceInfo) { - if (debugger is null) + if (debugger == null) { throw new PSArgumentNullException(nameof(debugger)); } - if (runspaceInfo is null) + if (runspaceInfo == null) { throw new PSArgumentNullException(nameof(runspaceInfo)); } @@ -5792,7 +5792,7 @@ protected PSMonitorRunspaceInfo( Runspace runspace, PSMonitorRunspaceType runspaceType) { - if (runspace is null) + if (runspace == null) { throw new PSArgumentNullException(nameof(runspace)); } diff --git a/src/System.Management.Automation/engine/hostifaces/AsyncResult.cs b/src/System.Management.Automation/engine/hostifaces/AsyncResult.cs index 745556b78bd..8a0101ae802 100644 --- a/src/System.Management.Automation/engine/hostifaces/AsyncResult.cs +++ b/src/System.Management.Automation/engine/hostifaces/AsyncResult.cs @@ -81,11 +81,11 @@ public WaitHandle AsyncWaitHandle { get { - if (_completedWaitHandle is null) + if (_completedWaitHandle == null) { lock (SyncObject) { - if (_completedWaitHandle is null) + if (_completedWaitHandle == null) { _completedWaitHandle = new ManualResetEvent(IsCompleted); } @@ -239,7 +239,7 @@ internal void EndInvoke() /// Callback state. internal bool InvokeCallbackOnThread(WaitCallback callback, object state) { - if (callback is null) + if (callback == null) { throw new PSArgumentNullException(nameof(callback)); } diff --git a/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs b/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs index a94fffe5946..9fca84d4a33 100644 --- a/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs +++ b/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs @@ -71,7 +71,7 @@ class ChoiceDescription throw PSTraceSource.NewArgumentException(nameof(label), DescriptionsStrings.NullOrEmptyErrorTemplate, "label"); } - if (helpMessage is null) + if (helpMessage == null) { // "helpMessage" is not localizable throw PSTraceSource.NewArgumentNullException(nameof(helpMessage)); @@ -129,7 +129,7 @@ class ChoiceDescription set { - if (value is null) + if (value == null) { throw PSTraceSource.NewArgumentNullException("value"); } diff --git a/src/System.Management.Automation/engine/hostifaces/Command.cs b/src/System.Management.Automation/engine/hostifaces/Command.cs index 325eb0f7ba0..b98e447563b 100644 --- a/src/System.Management.Automation/engine/hostifaces/Command.cs +++ b/src/System.Management.Automation/engine/hostifaces/Command.cs @@ -50,7 +50,7 @@ public Command(string command, bool isScript) public Command(string command, bool isScript, bool useLocalScope) { IsEndOfStatement = false; - if (command is null) + if (command == null) { throw PSTraceSource.NewArgumentNullException(nameof(command)); } @@ -63,7 +63,7 @@ public Command(string command, bool isScript, bool useLocalScope) internal Command(string command, bool isScript, bool? useLocalScope) { IsEndOfStatement = false; - if (command is null) + if (command == null) { throw PSTraceSource.NewArgumentNullException(nameof(command)); } @@ -590,7 +590,7 @@ CommandOrigin origin /// internal static Command FromPSObjectForRemoting(PSObject commandAsPSObject) { - if (commandAsPSObject is null) + if (commandAsPSObject == null) { throw PSTraceSource.NewArgumentNullException(nameof(commandAsPSObject)); } diff --git a/src/System.Management.Automation/engine/hostifaces/Connection.cs b/src/System.Management.Automation/engine/hostifaces/Connection.cs index 1ffd5fea9f8..a57b2d4a626 100644 --- a/src/System.Management.Automation/engine/hostifaces/Connection.cs +++ b/src/System.Management.Automation/engine/hostifaces/Connection.cs @@ -331,7 +331,7 @@ public sealed class RunspaceStateEventArgs : EventArgs /// internal RunspaceStateEventArgs(RunspaceStateInfo runspaceStateInfo) { - if (runspaceStateInfo is null) + if (runspaceStateInfo == null) { throw PSTraceSource.NewArgumentNullException(nameof(runspaceStateInfo)); } @@ -510,7 +510,7 @@ public static Runspace DefaultRunspace set { - if (value is null || !value.RunspaceIsRemote) + if (value == null || !value.RunspaceIsRemote) { t_threadSpecificDefaultRunspace = value; } @@ -650,7 +650,7 @@ public bool RunspaceIsRemote { get { - return !(this is LocalRunspace || ConnectionInfo is null); + return !(this is LocalRunspace || ConnectionInfo == null); } } @@ -977,14 +977,14 @@ internal void UpdateRunspaceAvailability(PipelineState pipelineState, bool raise Pipeline currentPipeline = this.GetCurrentlyRunningPipeline(); RemotePipeline remotePipeline = currentPipeline as RemotePipeline; Guid? pipeLineCmdInstance = (remotePipeline != null && remotePipeline.PowerShell != null) ? remotePipeline.PowerShell.InstanceId : (Guid?)null; - if (currentPipeline is null) + if (currentPipeline == null) { // A runspace is available: // - if there is no currently running pipeline // and for remote runspaces: // - if there is no remote command associated with it. // - if the remote runspace pool is marked as available for connection. - if (remoteCommand is null) + if (remoteCommand == null) { if (remoteRunspace != null) { @@ -1142,7 +1142,7 @@ protected void UpdateRunspaceAvailability(RunspaceState runspaceState, bool rais } else { - this.RunspaceAvailability = (remoteCommand is null && GetCurrentlyRunningPipeline() is null) ? + this.RunspaceAvailability = (remoteCommand == null && GetCurrentlyRunningPipeline() == null) ? RunspaceAvailability.Available : RunspaceAvailability.Busy; } @@ -1699,7 +1699,7 @@ internal SessionStateProxy(RunspaceBase runspace) /// public virtual void SetVariable(string name, object value) { - if (name is null) + if (name == null) { throw PSTraceSource.NewArgumentNullException(nameof(name)); } @@ -1727,7 +1727,7 @@ public virtual void SetVariable(string name, object value) /// public virtual object GetVariable(string name) { - if (name is null) + if (name == null) { throw PSTraceSource.NewArgumentNullException(nameof(name)); } diff --git a/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs b/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs index 8f958943a37..cffbc6d81a1 100644 --- a/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs +++ b/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs @@ -38,7 +38,7 @@ internal abstract class RunspaceBase : Runspace /// protected RunspaceBase(PSHost host) { - if (host is null) + if (host == null) { throw PSTraceSource.NewArgumentNullException(nameof(host)); } @@ -64,12 +64,12 @@ protected RunspaceBase(PSHost host) [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "OK to call ThreadOptions")] protected RunspaceBase(PSHost host, InitialSessionState initialSessionState) { - if (host is null) + if (host == null) { throw PSTraceSource.NewArgumentNullException(nameof(host)); } - if (initialSessionState is null) + if (initialSessionState == null) { throw PSTraceSource.NewArgumentNullException(nameof(initialSessionState)); } @@ -102,12 +102,12 @@ protected RunspaceBase(PSHost host, InitialSessionState initialSessionState) [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "OK to call ThreadOptions")] protected RunspaceBase(PSHost host, InitialSessionState initialSessionState, bool suppressClone) { - if (host is null) + if (host == null) { throw PSTraceSource.NewArgumentNullException(nameof(host)); } - if (initialSessionState is null) + if (initialSessionState == null) { throw PSTraceSource.NewArgumentNullException(nameof(initialSessionState)); } @@ -533,7 +533,7 @@ public override Pipeline CreatePipeline() /// public override Pipeline CreatePipeline(string command) { - if (command is null) + if (command == null) { throw PSTraceSource.NewArgumentNullException(nameof(command)); } @@ -554,7 +554,7 @@ public override Pipeline CreatePipeline(string command) /// public override Pipeline CreatePipeline(string command, bool addToHistory) { - if (command is null) + if (command == null) { throw PSTraceSource.NewArgumentNullException(nameof(command)); } @@ -588,7 +588,7 @@ public override Pipeline CreateNestedPipeline() /// public override Pipeline CreateNestedPipeline(string command, bool addToHistory) { - if (command is null) + if (command == null) { throw PSTraceSource.NewArgumentNullException(nameof(command)); } @@ -971,7 +971,7 @@ internal bool CanRunActionInCurrentPipeline() // If we have no running pipeline, or if the currently running pipeline is // the same as the current thread, then execute the action. var pipelineRunning = _currentlyRunningPipeline as PipelineBase; - return pipelineRunning is null || + return pipelineRunning == null || Thread.CurrentThread == pipelineRunning.NestedPipelineExecutionThread; } } @@ -1065,11 +1065,11 @@ internal void Pulse() { // If we don't already have a pipeline running, pulse the engine. bool pipelineCreated = false; - if (GetCurrentlyRunningPipeline() is null) + if (GetCurrentlyRunningPipeline() == null) { lock (SyncRoot) { - if (GetCurrentlyRunningPipeline() is null) + if (GetCurrentlyRunningPipeline() == null) { // This is a pipeline that does the least amount possible. // It evaluates a constant, and results in the execution of only two parse tree nodes. diff --git a/src/System.Management.Automation/engine/hostifaces/ConnectionFactory.cs b/src/System.Management.Automation/engine/hostifaces/ConnectionFactory.cs index f0ec9e7d482..2021ae6abf9 100644 --- a/src/System.Management.Automation/engine/hostifaces/ConnectionFactory.cs +++ b/src/System.Management.Automation/engine/hostifaces/ConnectionFactory.cs @@ -60,7 +60,7 @@ public static Runspace CreateRunspace() /// public static Runspace CreateRunspace(PSHost host) { - if (host is null) + if (host == null) { throw PSTraceSource.NewArgumentNullException(nameof(host)); } @@ -83,7 +83,7 @@ public static Runspace CreateRunspace(PSHost host) [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Runspace")] public static Runspace CreateRunspace(InitialSessionState initialSessionState) { - if (initialSessionState is null) + if (initialSessionState == null) { throw PSTraceSource.NewArgumentNullException(nameof(initialSessionState)); } @@ -114,12 +114,12 @@ public static Runspace CreateRunspace(InitialSessionState initialSessionState) [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Runspace")] public static Runspace CreateRunspace(PSHost host, InitialSessionState initialSessionState) { - if (host is null) + if (host == null) { throw PSTraceSource.NewArgumentNullException(nameof(host)); } - if (initialSessionState is null) + if (initialSessionState == null) { throw PSTraceSource.NewArgumentNullException(nameof(initialSessionState)); } @@ -148,12 +148,12 @@ public static Runspace CreateRunspace(PSHost host, InitialSessionState initialSe [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Runspace")] internal static Runspace CreateRunspaceFromSessionStateNoClone(PSHost host, InitialSessionState initialSessionState) { - if (host is null) + if (host == null) { throw PSTraceSource.NewArgumentNullException(nameof(host)); } - if (initialSessionState is null) + if (initialSessionState == null) { throw PSTraceSource.NewArgumentNullException(nameof(initialSessionState)); } diff --git a/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs b/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs index 50438950c9a..545440a1574 100644 --- a/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs +++ b/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs @@ -74,7 +74,7 @@ public string Name void SetParameterType(System.Type parameterType) { - if (parameterType is null) + if (parameterType == null) { throw PSTraceSource.NewArgumentNullException(nameof(parameterType)); } @@ -203,7 +203,7 @@ public string Name set { - if (value is null) + if (value == null) { throw PSTraceSource.NewArgumentNullException("value"); } @@ -236,7 +236,7 @@ public string Name set { - if (value is null) + if (value == null) { throw PSTraceSource.NewArgumentNullException("value"); } diff --git a/src/System.Management.Automation/engine/hostifaces/History.cs b/src/System.Management.Automation/engine/hostifaces/History.cs index 245f5a48052..9345462aa56 100644 --- a/src/System.Management.Automation/engine/hostifaces/History.cs +++ b/src/System.Management.Automation/engine/hostifaces/History.cs @@ -287,7 +287,7 @@ internal HistoryInfo[] GetEntries(long id, long count, SwitchParameter newest) throw PSTraceSource.NewArgumentOutOfRangeException(nameof(count), count); } - if (newest.ToString() is null) + if (newest.ToString() == null) { throw PSTraceSource.NewArgumentNullException(nameof(newest)); } @@ -329,7 +329,7 @@ internal HistoryInfo[] GetEntries(long id, long count, SwitchParameter newest) { if (firstId <= 1) break; // if entry is null , continue the loop with the next entry - if (_buffer[GetIndexFromId(i)] is null) continue; + if (_buffer[GetIndexFromId(i)] == null) continue; if (_buffer[GetIndexFromId(i)].Cleared) { // we have to clear count entries before an id, so if an entry is null,decrement @@ -343,7 +343,7 @@ internal HistoryInfo[] GetEntries(long id, long count, SwitchParameter newest) { // if an entry is null after being cleared by clear-history cmdlet, // continue with the next entry - if (_buffer[GetIndexFromId(i)] is null || _buffer[GetIndexFromId(i)].Cleared) + if (_buffer[GetIndexFromId(i)] == null || _buffer[GetIndexFromId(i)].Cleared) continue; entriesList.Add(_buffer[GetIndexFromId(i)].Clone()); } @@ -362,7 +362,7 @@ internal HistoryInfo[] GetEntries(long id, long count, SwitchParameter newest) { if (firstId >= _countEntriesAdded) break; // if entry is null , continue the loop with the next entry - if (_buffer[GetIndexFromId(i)] is null) continue; + if (_buffer[GetIndexFromId(i)] == null) continue; if (_buffer[GetIndexFromId(i)].Cleared) { // we have to clear count entries before an id, so if an entry is null,increment first id @@ -375,7 +375,7 @@ internal HistoryInfo[] GetEntries(long id, long count, SwitchParameter newest) { // if an entry is null after being cleared by clear-history cmdlet, // continue with the next entry - if (_buffer[GetIndexFromId(i)] is null || _buffer[GetIndexFromId(i)].Cleared) + if (_buffer[GetIndexFromId(i)] == null || _buffer[GetIndexFromId(i)].Cleared) continue; entriesList.Add(_buffer[GetIndexFromId(i)].Clone()); } @@ -469,7 +469,7 @@ internal HistoryInfo[] GetEntries(WildcardPattern wildcardpattern, long count, S throw PSTraceSource.NewArgumentOutOfRangeException(nameof(count), count); } - if (newest.ToString() is null) + if (newest.ToString() == null) { throw PSTraceSource.NewArgumentNullException(nameof(newest)); } @@ -606,7 +606,7 @@ internal int Buffercapacity() /// Id starts from 1 and is incremented by 1 for each new entry private long Add(HistoryInfo entry) { - if (entry is null) + if (entry == null) { throw PSTraceSource.NewArgumentNullException(nameof(entry)); } @@ -658,7 +658,7 @@ private HistoryInfo CoreGetEntry(long id) private long SmallestIDinBuffer() { long minID = 0; - if (_buffer is null) + if (_buffer == null) return minID; for (int i = 0; i < _buffer.Length; i++) { @@ -1163,7 +1163,7 @@ private HistoryInfo GetHistoryEntryToInvoke(History history) // User didn't specify any input parameter. Invoke the last // entry - if (_id is null) + if (_id == null) { HistoryInfo[] entries = history.GetEntries(0, 1, true); @@ -1211,7 +1211,7 @@ private HistoryInfo GetHistoryEntryToInvoke(History history) } } - if (entry is null) + if (entry == null) { Exception ex = new ArgumentException @@ -1257,7 +1257,7 @@ private HistoryInfo GetHistoryEntryToInvoke(History history) { // Retrieve the command at the index we've specified entry = history.GetEntry(_historyId); - if (entry is null || entry.Id != _historyId) + if (entry == null || entry.Id != _historyId) { Exception ex = new ArgumentException @@ -1298,7 +1298,7 @@ private HistoryInfo GetHistoryEntryToInvoke(History history) ///
private void PopulateIdAndCommandLine() { - if (_id is null) + if (_id == null) return; try @@ -1432,20 +1432,20 @@ void ProcessRecord() { do { - if (mshObject is null) + if (mshObject == null) { break; } // Read CommandLine property string commandLine = GetPropertyValue(mshObject, "CommandLine") as string; - if (commandLine is null) + if (commandLine == null) { break; } // Read ExecutionStatus property object pipelineState = GetPropertyValue(mshObject, "ExecutionStatus"); - if (pipelineState is null) + if (pipelineState == null) { break; } @@ -1489,7 +1489,7 @@ void ProcessRecord() // Read StartExecutionTime property DateTime startExecutionTime; object temp = GetPropertyValue(mshObject, "StartExecutionTime"); - if (temp is null) + if (temp == null) { break; } @@ -1516,7 +1516,7 @@ void ProcessRecord() // Read EndExecutionTime property DateTime endExecutionTime; temp = GetPropertyValue(mshObject, "EndExecutionTime"); - if (temp is null) + if (temp == null) { break; } @@ -1577,7 +1577,7 @@ private static GetPropertyValue(PSObject mshObject, string propertyName) { PSMemberInfo propertyInfo = mshObject.Properties[propertyName]; - if (propertyInfo is null) + if (propertyInfo == null) return null; return propertyInfo.Value; } @@ -1919,13 +1919,13 @@ private void ClearHistoryByCmdLine() private void ClearHistoryEntries(long id, int count, string cmdline, SwitchParameter newest) { // if cmdline is null,use default parameter set notion. - if (cmdline is null) + if (cmdline == null) { // if id is present,clears count entries from id if (id > 0) { HistoryInfo entry = _history.GetEntry(id); - if (entry is null || entry.Id != id) + if (entry == null || entry.Id != id) { Exception ex = new ArgumentException diff --git a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs index 8881491c973..ecc4780c284 100644 --- a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs +++ b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs @@ -310,7 +310,7 @@ internal static string GetMaxLines(string source, int maxLines) internal static List GetSuggestion(Runspace runspace) { LocalRunspace localRunspace = runspace as LocalRunspace; - if (localRunspace is null) { return new List(); } + if (localRunspace == null) { return new List(); } // Get the last value of $? bool questionMarkVariableValue = localRunspace.ExecutionContext.QuestionMarkVariableValue; @@ -334,7 +334,7 @@ internal static List GetSuggestion(Runspace runspace) ErrorRecord lastErrorRecord = null; // The error was an actual ErrorRecord - if (lastError is null) + if (lastError == null) { lastErrorRecord = errorList[0] as ErrorRecord; } @@ -413,7 +413,7 @@ internal static List GetSuggestion(HistoryInfo lastHistory, object lastE object result = null; ScriptBlock evaluator = suggestion["Rule"] as ScriptBlock; - if (evaluator is null) + if (evaluator == null) { suggestion["Enabled"] = false; @@ -798,12 +798,12 @@ internal static RemoteRunspace CreateConfiguredRunspace( /// Collection of command output result objects. public static Collection InvokeOnRunspace(PSCommand command, Runspace runspace) { - if (command is null) + if (command == null) { throw new PSArgumentNullException(nameof(command)); } - if (runspace is null) + if (runspace == null) { throw new PSArgumentNullException(nameof(runspace)); } @@ -823,7 +823,7 @@ public static Collection InvokeOnRunspace(PSCommand command, Runspace PowerShell ps = PowerShell.Create(); ps.Runspace = runspace; ps.IsRunspaceOwner = false; - if (runspace.ConnectionInfo is null) + if (runspace.ConnectionInfo == null) { // Local runspace. Make a nested PowerShell object as needed. ps.SetIsNested(runspace.GetCurrentlyRunningPipeline() != null); diff --git a/src/System.Management.Automation/engine/hostifaces/InformationalRecord.cs b/src/System.Management.Automation/engine/hostifaces/InformationalRecord.cs index 55fd16d7d12..9325f95ccad 100644 --- a/src/System.Management.Automation/engine/hostifaces/InformationalRecord.cs +++ b/src/System.Management.Automation/engine/hostifaces/InformationalRecord.cs @@ -144,7 +144,7 @@ internal virtual void ToPSObjectForRemoting(PSObject psObject) // The invocation info may be null if the record was created via WriteVerbose/Warning/DebugLine instead of WriteVerbose/Warning/Debug, in that case // we set InformationalRecord_SerializeInvocationInfo to false. // - if (!this.SerializeExtendedInfo || _invocationInfo is null) + if (!this.SerializeExtendedInfo || _invocationInfo == null) { RemotingEncoder.AddNoteProperty(psObject, "InformationalRecord_SerializeInvocationInfo", () => false); } diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHost.cs b/src/System.Management.Automation/engine/hostifaces/InternalHost.cs index edbb2c754bf..e170a3792e4 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHost.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHost.cs @@ -91,12 +91,12 @@ public override System.Version Version { get { - if (_versionResult is null) + if (_versionResult == null) { _versionResult = _externalHostRef.Value.Version; #pragma warning disable 56503 - if (_versionResult is null) + if (_versionResult == null) { throw PSTraceSource.NewNotImplementedException(); } @@ -290,7 +290,7 @@ internal void EnterNestedPrompt(InternalCommand callingCommand) PSObject newValue = PSObject.AsPSObject(callingCommand); commandInfoProperty = newValue.Properties["CommandInfo"]; - if (commandInfoProperty is null) + if (commandInfoProperty == null) { newValue.Properties.Add(new PSNoteProperty("CommandInfo", callingCommand.CommandInfo)); } @@ -301,7 +301,7 @@ internal void EnterNestedPrompt(InternalCommand callingCommand) } stackTraceProperty = newValue.Properties["StackTrace"]; - if (stackTraceProperty is null) + if (stackTraceProperty == null) { newValue.Properties.Add(new PSNoteProperty("StackTrace", new System.Diagnostics.StackTrace())); } @@ -449,7 +449,7 @@ public override void NotifyEndApplication() private IHostSupportsInteractiveSession GetIHostSupportsInteractiveSession() { IHostSupportsInteractiveSession host = _externalHostRef.Value as IHostSupportsInteractiveSession; - if (host is null) + if (host == null) { throw new PSNotImplementedException(); } diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHostRawUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/InternalHostRawUserInterface.cs index e9b09ae82fd..d182ef6302a 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHostRawUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHostRawUserInterface.cs @@ -49,7 +49,7 @@ public override { get { - if (_externalRawUI is null) + if (_externalRawUI == null) { ThrowNotInteractive(); } @@ -61,7 +61,7 @@ public override set { - if (_externalRawUI is null) + if (_externalRawUI == null) { ThrowNotInteractive(); } @@ -85,7 +85,7 @@ public override { get { - if (_externalRawUI is null) + if (_externalRawUI == null) { ThrowNotInteractive(); } @@ -97,7 +97,7 @@ public override set { - if (_externalRawUI is null) + if (_externalRawUI == null) { ThrowNotInteractive(); } @@ -121,7 +121,7 @@ public override { get { - if (_externalRawUI is null) + if (_externalRawUI == null) { ThrowNotInteractive(); } @@ -133,7 +133,7 @@ public override set { - if (_externalRawUI is null) + if (_externalRawUI == null) { ThrowNotInteractive(); } @@ -157,7 +157,7 @@ public override { get { - if (_externalRawUI is null) + if (_externalRawUI == null) { ThrowNotInteractive(); } @@ -169,7 +169,7 @@ public override set { - if (_externalRawUI is null) + if (_externalRawUI == null) { ThrowNotInteractive(); } @@ -193,7 +193,7 @@ public override { get { - if (_externalRawUI is null) + if (_externalRawUI == null) { ThrowNotInteractive(); } @@ -205,7 +205,7 @@ public override set { - if (_externalRawUI is null) + if (_externalRawUI == null) { ThrowNotInteractive(); } @@ -229,7 +229,7 @@ public override { get { - if (_externalRawUI is null) + if (_externalRawUI == null) { ThrowNotInteractive(); } @@ -241,7 +241,7 @@ public override set { - if (_externalRawUI is null) + if (_externalRawUI == null) { ThrowNotInteractive(); } @@ -265,7 +265,7 @@ public override { get { - if (_externalRawUI is null) + if (_externalRawUI == null) { ThrowNotInteractive(); } @@ -277,7 +277,7 @@ public override set { - if (_externalRawUI is null) + if (_externalRawUI == null) { ThrowNotInteractive(); } @@ -301,7 +301,7 @@ public override { get { - if (_externalRawUI is null) + if (_externalRawUI == null) { ThrowNotInteractive(); } @@ -327,7 +327,7 @@ public override { get { - if (_externalRawUI is null) + if (_externalRawUI == null) { ThrowNotInteractive(); } @@ -353,7 +353,7 @@ public override KeyInfo ReadKey(ReadKeyOptions options) { - if (_externalRawUI is null) + if (_externalRawUI == null) { ThrowNotInteractive(); } @@ -368,7 +368,7 @@ public override // PipelineStoppedException is thrown by host when it wants // to stop the pipeline. LocalPipeline lpl = (LocalPipeline)((RunspaceBase)_parentHost.Context.CurrentRunspace).GetCurrentlyRunningPipeline(); - if (lpl is null) + if (lpl == null) { throw; } @@ -391,7 +391,7 @@ public override void FlushInputBuffer() { - if (_externalRawUI is null) + if (_externalRawUI == null) { ThrowNotInteractive(); } @@ -414,7 +414,7 @@ public override { get { - if (_externalRawUI is null) + if (_externalRawUI == null) { ThrowNotInteractive(); } @@ -440,7 +440,7 @@ public override { get { - if (_externalRawUI is null) + if (_externalRawUI == null) { ThrowNotInteractive(); } @@ -452,7 +452,7 @@ public override set { - if (_externalRawUI is null) + if (_externalRawUI == null) { ThrowNotInteractive(); } @@ -474,7 +474,7 @@ public override void SetBufferContents(Coordinates origin, BufferCell[,] contents) { - if (_externalRawUI is null) + if (_externalRawUI == null) { ThrowNotInteractive(); } @@ -500,7 +500,7 @@ public override void SetBufferContents(Rectangle r, BufferCell fill) { - if (_externalRawUI is null) + if (_externalRawUI == null) { ThrowNotInteractive(); } @@ -522,7 +522,7 @@ public override BufferCell[,] GetBufferContents(Rectangle r) { - if (_externalRawUI is null) + if (_externalRawUI == null) { ThrowNotInteractive(); } @@ -556,7 +556,7 @@ public override BufferCell fill ) { - if (_externalRawUI is null) + if (_externalRawUI == null) { ThrowNotInteractive(); } @@ -574,7 +574,7 @@ BufferCell fill /// public override int LengthInBufferCells(string str) { - if (_externalRawUI is null) + if (_externalRawUI == null) { ThrowNotInteractive(); } @@ -596,7 +596,7 @@ public override int LengthInBufferCells(string str, int offset) Dbg.Assert(offset >= 0, "offset >= 0"); Dbg.Assert(string.IsNullOrEmpty(str) || (offset < str.Length), "offset < str.Length"); - if (_externalRawUI is null) + if (_externalRawUI == null) { ThrowNotInteractive(); } @@ -616,7 +616,7 @@ public override int LengthInBufferCells(char character) { - if (_externalRawUI is null) + if (_externalRawUI == null) { ThrowNotInteractive(); } diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs index 9a33f119069..1eef6752602 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs @@ -25,7 +25,7 @@ class InternalHostUserInterface : PSHostUserInterface, IHostUISupportsMultipleCh // parent may not be null, however Dbg.Assert(parentHost != null, "parent may not be null"); - if (parentHost is null) + if (parentHost == null) { throw PSTraceSource.NewArgumentNullException(nameof(parentHost)); } @@ -94,7 +94,7 @@ public override string ReadLine() { - if (_externalUI is null) + if (_externalUI == null) { ThrowNotInteractive(); } @@ -109,7 +109,7 @@ public override // PipelineStoppedException is thrown by host when it wants // to stop the pipeline. LocalPipeline lpl = (LocalPipeline)((RunspaceBase)_parent.Context.CurrentRunspace).GetCurrentlyRunningPipeline(); - if (lpl is null) + if (lpl == null) { throw; } @@ -134,7 +134,7 @@ public override string ReadLineMaskedAsString() { - if (_externalUI is null) + if (_externalUI == null) { ThrowNotInteractive(); } @@ -150,7 +150,7 @@ public override // PipelineStoppedException is thrown by host when it wants // to stop the pipeline. LocalPipeline lpl = (LocalPipeline)((RunspaceBase)_parent.Context.CurrentRunspace).GetCurrentlyRunningPipeline(); - if (lpl is null) + if (lpl == null) { throw; } @@ -173,7 +173,7 @@ public override SecureString ReadLineAsSecureString() { - if (_externalUI is null) + if (_externalUI == null) { ThrowNotInteractive(); } @@ -189,7 +189,7 @@ public override // PipelineStoppedException is thrown by host when it wants // to stop the pipeline. LocalPipeline lpl = (LocalPipeline)((RunspaceBase)_parent.Context.CurrentRunspace).GetCurrentlyRunningPipeline(); - if (lpl is null) + if (lpl == null) { throw; } @@ -214,12 +214,12 @@ public override void Write(string value) { - if (value is null) + if (value == null) { return; } - if (_externalUI is null) + if (_externalUI == null) { return; } @@ -245,12 +245,12 @@ public override void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value) { - if (value is null) + if (value == null) { return; } - if (_externalUI is null) + if (_externalUI == null) { return; } @@ -272,7 +272,7 @@ public override void WriteLine() { - if (_externalUI is null) + if (_externalUI == null) { return; } @@ -294,12 +294,12 @@ public override void WriteLine(string value) { - if (value is null) + if (value == null) { return; } - if (_externalUI is null) + if (_externalUI == null) { return; } @@ -311,12 +311,12 @@ public override void WriteErrorLine(string value) { - if (value is null) + if (value == null) { return; } - if (_externalUI is null) + if (_externalUI == null) { return; } @@ -342,12 +342,12 @@ public override void WriteLine(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value) { - if (value is null) + if (value == null) { return; } - if (_externalUI is null) + if (_externalUI == null) { return; } @@ -376,7 +376,7 @@ internal void WriteDebugRecord(DebugRecord record) { WriteDebugInfoBuffers(record); - if (_externalUI is null) + if (_externalUI == null) { return; } @@ -491,7 +491,7 @@ internal PSInformationalBuffers GetInformationalMessageBuffers() void WriteDebugLineHelper(string message) { - if (message is null) + if (message == null) { return; } @@ -585,7 +585,7 @@ public override void WriteProgress(Int64 sourceId, ProgressRecord record) { - if (record is null) + if (record == null) { throw PSTraceSource.NewArgumentNullException(nameof(record)); } @@ -596,7 +596,7 @@ public override _informationalBuffers.AddProgress(record); } - if (_externalUI is null) + if (_externalUI == null) { return; } @@ -616,7 +616,7 @@ public override void WriteVerboseLine(string message) { - if (message is null) + if (message == null) { return; } @@ -630,7 +630,7 @@ internal void WriteVerboseRecord(VerboseRecord record) { WriteVerboseInfoBuffers(record); - if (_externalUI is null) + if (_externalUI == null) { return; } @@ -660,7 +660,7 @@ internal void WriteVerboseInfoBuffers(VerboseRecord record) public override void WriteWarningLine(string message) { - if (message is null) + if (message == null) { return; } @@ -674,7 +674,7 @@ internal void WriteWarningRecord(WarningRecord record) { WriteWarningInfoBuffers(record); - if (_externalUI is null) + if (_externalUI == null) { return; } @@ -700,7 +700,7 @@ internal void WriteInformationRecord(InformationRecord record) { WriteInformationInfoBuffers(record); - if (_externalUI is null) + if (_externalUI == null) { return; } @@ -771,7 +771,7 @@ public override Dictionary Prompt(string caption, string message, Collection descriptions) { - if (descriptions is null) + if (descriptions == null) { throw PSTraceSource.NewArgumentNullException(nameof(descriptions)); } @@ -781,7 +781,7 @@ public override throw PSTraceSource.NewArgumentException(nameof(descriptions), InternalHostUserInterfaceStrings.PromptEmptyDescriptionsError, "descriptions"); } - if (_externalUI is null) + if (_externalUI == null) { ThrowPromptNotInteractive(message); } @@ -797,7 +797,7 @@ public override // PipelineStoppedException is thrown by host when it wants // to stop the pipeline. LocalPipeline lpl = (LocalPipeline)((RunspaceBase)_parent.Context.CurrentRunspace).GetCurrentlyRunningPipeline(); - if (lpl is null) + if (lpl == null) { throw; } @@ -825,7 +825,7 @@ public override int PromptForChoice(string caption, string message, Collection choices, int defaultChoice) { - if (_externalUI is null) + if (_externalUI == null) { ThrowPromptNotInteractive(message); } @@ -840,7 +840,7 @@ public override // PipelineStoppedException is thrown by host when it wants // to stop the pipeline. LocalPipeline lpl = (LocalPipeline)((RunspaceBase)_parent.Context.CurrentRunspace).GetCurrentlyRunningPipeline(); - if (lpl is null) + if (lpl == null) { throw; } @@ -876,7 +876,7 @@ public Collection PromptForChoice(string caption, Collection choices, IEnumerable defaultChoices) { - if (_externalUI is null) + if (_externalUI == null) { ThrowPromptNotInteractive(message); } @@ -887,7 +887,7 @@ public Collection PromptForChoice(string caption, Collection result = null; try { - if (hostForMultipleChoices is null) + if (hostForMultipleChoices == null) { // host did not implement this new interface.. // so work with V1 host API to get the behavior.. @@ -905,7 +905,7 @@ public Collection PromptForChoice(string caption, // PipelineStoppedException is thrown by host when it wants // to stop the pipeline. LocalPipeline lpl = (LocalPipeline)((RunspaceBase)_parent.Context.CurrentRunspace).GetCurrentlyRunningPipeline(); - if (lpl is null) + if (lpl == null) { throw; } @@ -937,7 +937,7 @@ private Collection EmulatePromptForMultipleChoice(string caption, { Dbg.Assert(_externalUI != null, "externalUI cannot be null."); - if (choices is null) + if (choices == null) { throw PSTraceSource.NewArgumentNullException(nameof(choices)); } diff --git a/src/System.Management.Automation/engine/hostifaces/ListModifier.cs b/src/System.Management.Automation/engine/hostifaces/ListModifier.cs index 96120d97770..191a5309cc7 100644 --- a/src/System.Management.Automation/engine/hostifaces/ListModifier.cs +++ b/src/System.Management.Automation/engine/hostifaces/ListModifier.cs @@ -52,7 +52,7 @@ public PSListModifier(object replacementItems) { _itemsToAdd = new Collection(); _itemsToRemove = new Collection(); - if (replacementItems is null) + if (replacementItems == null) { _replacementItems = new Collection(); } @@ -86,7 +86,7 @@ public PSListModifier(object replacementItems) /// and the value for Remove is the list to remove. public PSListModifier(Hashtable hash) { - if (hash is null) + if (hash == null) { throw PSTraceSource.NewArgumentNullException(nameof(hash)); } @@ -179,7 +179,7 @@ public Collection Replace /// The collection to update. public void ApplyTo(IList collectionToUpdate) { - if (collectionToUpdate is null) + if (collectionToUpdate == null) { throw PSTraceSource.NewArgumentNullException(nameof(collectionToUpdate)); } @@ -212,7 +212,7 @@ public void ApplyTo(IList collectionToUpdate) /// The collection to update. public void ApplyTo(object collectionToUpdate) { - if (collectionToUpdate is null) + if (collectionToUpdate == null) { throw new ArgumentNullException(nameof(collectionToUpdate)); } @@ -220,7 +220,7 @@ public void ApplyTo(object collectionToUpdate) collectionToUpdate = PSObject.Base(collectionToUpdate); IList list = collectionToUpdate as IList; - if (list is null) + if (list == null) { throw PSTraceSource.NewInvalidOperationException(PSListModifierStrings.UpdateFailed); } diff --git a/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs b/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs index a09e1a0f4f5..92740acf8dd 100644 --- a/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs +++ b/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs @@ -80,11 +80,11 @@ public override PSPrimitiveDictionary GetApplicationPrivateData() // if we didn't get applicationPrivateData from a runspace pool, // then we create a new one - if (_applicationPrivateData is null) + if (_applicationPrivateData == null) { lock (this.SyncRoot) { - if (_applicationPrivateData is null) + if (_applicationPrivateData == null) { _applicationPrivateData = new PSPrimitiveDictionary(); } @@ -114,7 +114,7 @@ public override PSEventManager Events { System.Management.Automation.ExecutionContext context = this.GetExecutionContext; - if (context is null) + if (context == null) { return null; } @@ -183,7 +183,7 @@ public override void ResetRunspaceState() { PSInvalidOperationException invalidOperation = null; - if (this.InitialSessionState is null) + if (this.InitialSessionState == null) { invalidOperation = PSTraceSource.NewInvalidOperationException(); } @@ -244,7 +244,7 @@ internal override System.Management.Automation.ExecutionContext GetExecutionCont { get { - if (_engine is null) + if (_engine == null) return null; else return _engine.Context; @@ -260,7 +260,7 @@ internal override bool InNestedPrompt { System.Management.Automation.ExecutionContext context = this.GetExecutionContext; - if (context is null) + if (context == null) { return false; } @@ -470,7 +470,7 @@ internal static void SetDebugPreference(string processName, List appDoma // Debug preference is set to disable. if (debugPreferenceCache.ContainsKey(processName)) { - if (appDomainName is null) + if (appDomainName == null) { debugPreferenceCache.Remove(processName); iscacheUpdated = true; @@ -768,7 +768,7 @@ internal void LogEngineHealthEvent(Exception exception, /// internal PipelineThread GetPipelineThread() { - if (_pipelineThread is null) + if (_pipelineThread == null) { _pipelineThread = new PipelineThread(this.ApartmentState); } @@ -1590,7 +1590,7 @@ protected RunspaceOpenModuleLoadException(SerializationInfo info, StreamingConte /// The destination for this serialization. public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) { throw new PSArgumentNullException(nameof(info)); } diff --git a/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs b/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs index 1b89ad3617c..fd34123937a 100644 --- a/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs +++ b/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs @@ -266,7 +266,7 @@ private void SetupInvokeThread(Thread invokeThread, bool changeName) invokeThread.CurrentUICulture = this.LocalRunspace.ExecutionContext.EngineHostInterface.CurrentUICulture; #endif - if ((invokeThread.Name is null) && changeName) // setup the invoke thread only once + if ((invokeThread.Name == null) && changeName) // setup the invoke thread only once { invokeThread.Name = "Pipeline Execution Thread"; } @@ -825,7 +825,7 @@ private PipelineProcessor CreatePipelineProcessor() { CommandCollection commands = Commands; - if (commands is null || commands.Count == 0) + if (commands == null || commands.Count == 0) { throw PSTraceSource.NewInvalidOperationException(RunspaceStrings.NoCommandInPipeline); } @@ -841,7 +841,7 @@ private PipelineProcessor CreatePipelineProcessor() { CommandProcessorBase commandProcessorBase; // If CommandInfo is null, proceed with CommandDiscovery to resolve the command name - if (command.CommandInfo is null) + if (command.CommandInfo == null) { try { @@ -1077,7 +1077,7 @@ internal override void SetHistoryString(string historyString) internal static System.Management.Automation.ExecutionContext GetExecutionContextFromTLS() { System.Management.Automation.Runspaces.Runspace runspace = Runspace.DefaultRunspace; - if (runspace is null) + if (runspace == null) { return null; } @@ -1315,7 +1315,7 @@ internal bool IsStopping /// internal void Push(PipelineProcessor item) { - if (item is null) + if (item == null) { throw PSTraceSource.NewArgumentNullException(nameof(item)); } diff --git a/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs index 3ed8b87551a..79f4bcff66a 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs @@ -1679,7 +1679,7 @@ public virtual int offset ) { - if (source is null) + if (source == null) { throw PSTraceSource.NewArgumentNullException(nameof(source)); } @@ -1718,7 +1718,7 @@ public virtual string source ) { - if (source is null) + if (source == null) { throw PSTraceSource.NewArgumentNullException(nameof(source)); } @@ -1805,7 +1805,7 @@ char source { #pragma warning disable 56506 - if (contents is null) + if (contents == null) { throw PSTraceSource.NewArgumentNullException(nameof(contents)); } diff --git a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs index 1560de4f230..0c8bf71e94a 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs @@ -182,7 +182,7 @@ public virtual void WriteLine(ConsoleColor foregroundColor, ConsoleColor backgro { // #pragma warning disable 56506 - // expressly not checking for value is null so that attempts to write a null cause an exception + // expressly not checking for value == null so that attempts to write a null cause an exception if ((value != null) && (value.Length != 0)) { @@ -400,7 +400,7 @@ internal void IgnoreCommand(string commandText, InvocationInfo invocation) { TranscribeCommandComplete(null); - if (TranscriptionData.CommandBeingIgnored is null) + if (TranscriptionData.CommandBeingIgnored == null) { TranscriptionData.CommandBeingIgnored = commandText; TranscriptionData.IsHelperCommand = false; @@ -463,7 +463,7 @@ private void CheckSystemTranscript() { lock (TranscriptionData) { - if (TranscriptionData.SystemTranscript is null) + if (TranscriptionData.SystemTranscript == null) { TranscriptionData.SystemTranscript = PSHostUserInterface.GetSystemTranscriptOption(TranscriptionData.SystemTranscript); if (TranscriptionData.SystemTranscript != null) @@ -1021,7 +1021,7 @@ internal static TranscriptionOption GetSystemTranscriptOption(TranscriptionOptio // This way, multiple runspaces opened by the same process will share the same transcript. lock (s_systemTranscriptLock) { - if (systemTranscript is null) + if (systemTranscript == null) { systemTranscript = PSHostUserInterface.GetTranscriptOptionFromSettings(transcription, currentTranscript); } @@ -1201,7 +1201,7 @@ internal void FlushContentToDisk() { if (!_disposed) { - if (_contentWriter is null) + if (_contentWriter == null) { try { diff --git a/src/System.Management.Automation/engine/hostifaces/PSCommand.cs b/src/System.Management.Automation/engine/hostifaces/PSCommand.cs index 65308f354f9..781e53eaf51 100644 --- a/src/System.Management.Automation/engine/hostifaces/PSCommand.cs +++ b/src/System.Management.Automation/engine/hostifaces/PSCommand.cs @@ -87,7 +87,7 @@ internal PSCommand(Command command) /// public PSCommand AddCommand(string command) { - if (command is null) + if (command == null) { throw PSTraceSource.NewArgumentNullException("cmdlet"); } @@ -131,7 +131,7 @@ public PSCommand AddCommand(string command) /// public PSCommand AddCommand(string cmdlet, bool useLocalScope) { - if (cmdlet is null) + if (cmdlet == null) { throw PSTraceSource.NewArgumentNullException(nameof(cmdlet)); } @@ -173,7 +173,7 @@ public PSCommand AddCommand(string cmdlet, bool useLocalScope) /// public PSCommand AddScript(string script) { - if (script is null) + if (script == null) { throw PSTraceSource.NewArgumentNullException(nameof(script)); } @@ -218,7 +218,7 @@ public PSCommand AddScript(string script) /// public PSCommand AddScript(string script, bool useLocalScope) { - if (script is null) + if (script == null) { throw PSTraceSource.NewArgumentNullException(nameof(script)); } @@ -256,7 +256,7 @@ public PSCommand AddScript(string script, bool useLocalScope) /// public PSCommand AddCommand(Command command) { - if (command is null) + if (command == null) { throw PSTraceSource.NewArgumentNullException(nameof(command)); } @@ -302,7 +302,7 @@ public PSCommand AddCommand(Command command) /// public PSCommand AddParameter(string parameterName, object value) { - if (_currentCommand is null) + if (_currentCommand == null) { throw PSTraceSource.NewInvalidOperationException(PSCommandStrings.ParameterRequiresCommand, new object[] { "PSCommand" }); @@ -344,7 +344,7 @@ public PSCommand AddParameter(string parameterName, object value) /// public PSCommand AddParameter(string parameterName) { - if (_currentCommand is null) + if (_currentCommand == null) { throw PSTraceSource.NewInvalidOperationException(PSCommandStrings.ParameterRequiresCommand, new object[] { "PSCommand" }); @@ -386,7 +386,7 @@ public PSCommand AddParameter(string parameterName) /// public PSCommand AddArgument(object value) { - if (_currentCommand is null) + if (_currentCommand == null) { throw PSTraceSource.NewInvalidOperationException(PSCommandStrings.ParameterRequiresCommand, new object[] { "PSCommand" }); diff --git a/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs b/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs index b3ddbe0f6a3..13448528be5 100644 --- a/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs +++ b/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs @@ -331,14 +331,14 @@ internal PSDataCollection(IList listToUse) /// The streaming context for this instance. protected PSDataCollection(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) { throw PSTraceSource.NewArgumentNullException(nameof(info)); } IList listToUse = info.GetValue("Data", typeof(IList)) as IList; - if (listToUse is null) + if (listToUse == null) { throw PSTraceSource.NewArgumentNullException(nameof(info)); } @@ -759,7 +759,7 @@ public int Count { lock (SyncObject) { - if (_data is null) + if (_data == null) return 0; else return _data.Count; @@ -1297,7 +1297,7 @@ protected virtual void RemoveItem(int index) /// The streaming context for this instance. public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) { throw PSTraceSource.NewArgumentNullException(nameof(info)); } @@ -1321,11 +1321,11 @@ internal WaitHandle WaitHandle { get { - if (_readWaitHandle is null) + if (_readWaitHandle == null) { lock (SyncObject) { - if (_readWaitHandle is null) + if (_readWaitHandle == null) { // Create the handle signaled if there are objects in the buffer // or the buffer has been closed. @@ -1512,7 +1512,7 @@ internal void InternalAdd(Guid psInstanceId, T item) /// internal void InternalAddRange(Guid psInstanceId, ICollection collection) { - if (collection is null) + if (collection == null) { throw PSTraceSource.NewArgumentNullException(nameof(collection)); } @@ -1627,7 +1627,7 @@ private int InternalIndexOf(T item) /// private static void VerifyValueType(object value) { - if (value is null) + if (value == null) { if (typeof(T).IsValueType) { @@ -1657,7 +1657,7 @@ private PSObject GetSerializedObject(object value) else { object deserialized = PSSerializer.Deserialize(PSSerializer.Serialize(value)); - if (deserialized is null) + if (deserialized == null) { return null; } @@ -1670,13 +1670,13 @@ private PSObject GetSerializedObject(object value) private bool SerializationWouldHaveNoEffect(PSObject result) { - if (result is null) + if (result == null) { return true; } object baseObject = PSObject.Base(result); - if (baseObject is null) + if (baseObject == null) { return true; } diff --git a/src/System.Management.Automation/engine/hostifaces/PSTask.cs b/src/System.Management.Automation/engine/hostifaces/PSTask.cs index b54a1ac8093..a25e4e2c840 100644 --- a/src/System.Management.Automation/engine/hostifaces/PSTask.cs +++ b/src/System.Management.Automation/engine/hostifaces/PSTask.cs @@ -1189,7 +1189,7 @@ public PSTaskChildDebugger( Debugger debugger, string jobName) { - if (debugger is null) + if (debugger == null) { throw new PSArgumentNullException(nameof(debugger)); } @@ -1526,7 +1526,7 @@ public Debugger Debugger { get { - if (_jobDebuggerWrapper is null) + if (_jobDebuggerWrapper == null) { _jobDebuggerWrapper = new PSTaskChildDebugger( _task.Debugger, diff --git a/src/System.Management.Automation/engine/hostifaces/Parameter.cs b/src/System.Management.Automation/engine/hostifaces/Parameter.cs index 94da3f2a0e2..3f7d072318a 100644 --- a/src/System.Management.Automation/engine/hostifaces/Parameter.cs +++ b/src/System.Management.Automation/engine/hostifaces/Parameter.cs @@ -31,7 +31,7 @@ public sealed class CommandParameter public CommandParameter(string name) : this(name, null) { - if (name is null) + if (name == null) { throw PSTraceSource.NewArgumentNullException(nameof(name)); } @@ -88,7 +88,7 @@ public CommandParameter(string name, object value) internal static CommandParameter FromCommandParameterInternal(CommandParameterInternal internalParameter) { - if (internalParameter is null) + if (internalParameter == null) { throw PSTraceSource.NewArgumentNullException(nameof(internalParameter)); } @@ -123,7 +123,7 @@ internal static CommandParameter FromCommandParameterInternal(CommandParameterIn internal static CommandParameterInternal ToCommandParameterInternal(CommandParameter publicParameter, bool forNativeCommand) { - if (publicParameter is null) + if (publicParameter == null) { throw PSTraceSource.NewArgumentNullException(nameof(publicParameter)); } @@ -131,9 +131,9 @@ internal static CommandParameterInternal ToCommandParameterInternal(CommandParam string name = publicParameter.Name; object value = publicParameter.Value; - Debug.Assert((name is null) || (name.Trim().Length != 0), "Parameter name has to null or have some non-whitespace characters in it"); + Debug.Assert((name == null) || (name.Trim().Length != 0), "Parameter name has to null or have some non-whitespace characters in it"); - if (name is null) + if (name == null) { return CommandParameterInternal.CreateArgument(value); } @@ -176,7 +176,7 @@ internal static CommandParameterInternal ToCommandParameterInternal(CommandParam // Now we just need to use the token to build appropriate CommandParameterInternal object // is this a name+value pair, or is it just a name (of a parameter)? - if (!hasColon && value is null) + if (!hasColon && value == null) { // just a name return CommandParameterInternal.CreateParameter(parameterName, parameterText); @@ -209,7 +209,7 @@ internal static CommandParameterInternal ToCommandParameterInternal(CommandParam /// internal static CommandParameter FromPSObjectForRemoting(PSObject parameterAsPSObject) { - if (parameterAsPSObject is null) + if (parameterAsPSObject == null) { throw PSTraceSource.NewArgumentNullException(nameof(parameterAsPSObject)); } diff --git a/src/System.Management.Automation/engine/hostifaces/Pipeline.cs b/src/System.Management.Automation/engine/hostifaces/Pipeline.cs index 29532a803fe..0a584c6fc36 100644 --- a/src/System.Management.Automation/engine/hostifaces/Pipeline.cs +++ b/src/System.Management.Automation/engine/hostifaces/Pipeline.cs @@ -303,7 +303,7 @@ internal Pipeline(Runspace runspace) /// internal Pipeline(Runspace runspace, CommandCollection command) { - if (runspace is null) + if (runspace == null) { PSTraceSource.NewArgumentNullException(nameof(runspace)); } diff --git a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs index da58d172288..ba559a5e1f6 100644 --- a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs +++ b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs @@ -358,7 +358,7 @@ public PSHost Host set { - if (value is null) + if (value == null) { throw PSTraceSource.NewArgumentNullException("Host"); } @@ -762,7 +762,7 @@ internal void InitForRemotePipeline(CommandCollection command, ObjectStreamBase // create the client remote powershell for remoting // communications - if (RemotePowerShell is null) + if (RemotePowerShell == null) { RemotePowerShell = new ClientRemotePowerShell(this, ((RunspacePool)_rsConnection).RemoteRunspacePoolInternal); } @@ -804,7 +804,7 @@ internal void InitForRemotePipelineConnect(ObjectStreamBase inputstream, ObjectS RedirectShellErrorOutputPipe = redirectShellErrorOutputPipe; - if (RemotePowerShell is null) + if (RemotePowerShell == null) { RemotePowerShell = new ClientRemotePowerShell(this, ((RunspacePool)_rsConnection).RemoteRunspacePoolInternal); } @@ -842,7 +842,7 @@ public static PowerShell Create(RunspaceMode runspace) switch (runspace) { case RunspaceMode.CurrentRunspace: - if (Runspace.DefaultRunspace is null) + if (Runspace.DefaultRunspace == null) { throw new InvalidOperationException(PowerShellStrings.NoDefaultRunspaceForPSCreate); } @@ -891,7 +891,7 @@ public static PowerShell Create(InitialSessionState initialSessionState) /// public static PowerShell Create(Runspace runspace) { - if (runspace is null) + if (runspace == null) { throw new PSArgumentNullException(nameof(runspace)); } @@ -1167,7 +1167,7 @@ internal PowerShell AddCommand(Command command) /// public PowerShell AddCommand(CommandInfo commandInfo) { - if (commandInfo is null) + if (commandInfo == null) { throw PSTraceSource.NewArgumentNullException(nameof(commandInfo)); } @@ -1290,7 +1290,7 @@ public PowerShell AddParameters(IList parameters) { lock (_syncObject) { - if (parameters is null) + if (parameters == null) { throw PSTraceSource.NewArgumentNullException(nameof(parameters)); } @@ -1338,7 +1338,7 @@ public PowerShell AddParameters(IDictionary parameters) { lock (_syncObject) { - if (parameters is null) + if (parameters == null) { throw PSTraceSource.NewArgumentNullException(nameof(parameters)); } @@ -1354,7 +1354,7 @@ public PowerShell AddParameters(IDictionary parameters) { string parameterName = entry.Key as string; - if (parameterName is null) + if (parameterName == null) { throw PSTraceSource.NewArgumentException(nameof(parameters), PowerShellStrings.KeyMustBeString); } @@ -1465,7 +1465,7 @@ public PSCommand Commands set { - if (value is null) + if (value == null) { throw PSTraceSource.NewArgumentNullException("Command"); } @@ -1508,7 +1508,7 @@ internal PSDataCollection ErrorBuffer set { - if (value is null) + if (value == null) { throw PSTraceSource.NewArgumentNullException("Error"); } @@ -1543,7 +1543,7 @@ internal PSDataCollection ProgressBuffer set { - if (value is null) + if (value == null) { throw PSTraceSource.NewArgumentNullException("Progress"); } @@ -1577,7 +1577,7 @@ internal PSDataCollection VerboseBuffer set { - if (value is null) + if (value == null) { throw PSTraceSource.NewArgumentNullException("Verbose"); } @@ -1611,7 +1611,7 @@ internal PSDataCollection DebugBuffer set { - if (value is null) + if (value == null) { throw PSTraceSource.NewArgumentNullException("Debug"); } @@ -1648,7 +1648,7 @@ internal PSDataCollection WarningBuffer set { - if (value is null) + if (value == null) { throw PSTraceSource.NewArgumentNullException("Warning"); } @@ -1685,7 +1685,7 @@ internal PSDataCollection InformationBuffer set { - if (value is null) + if (value == null) { throw PSTraceSource.NewArgumentNullException("Information"); } @@ -1794,11 +1794,11 @@ public Runspace Runspace { get { - if (_runspace is null && _runspacePool is null) // create a runspace only if neither a runspace nor a runspace pool have been set + if (_runspace == null && _runspacePool == null) // create a runspace only if neither a runspace nor a runspace pool have been set { lock (_syncObject) { - if (_runspace is null && _runspacePool is null) + if (_runspace == null && _runspacePool == null) { AssertChangesAreAccepted(); SetRunspace(RunspaceFactory.CreateRunspace(), true); @@ -1835,7 +1835,7 @@ private void SetRunspace(Runspace runspace, bool owner) { RemoteRunspace remoteRunspace = runspace as RemoteRunspace; - if (remoteRunspace is null) + if (remoteRunspace == null) { _rsConnection = runspace; } @@ -2027,7 +2027,7 @@ public IAsyncResult ConnectAsync( OutputBuffer = output; OutputBufferOwner = false; } - else if (OutputBuffer is null) + else if (OutputBuffer == null) { OutputBuffer = new PSDataCollection(); OutputBufferOwner = true; @@ -2042,7 +2042,7 @@ public IAsyncResult ConnectAsync( InformationalBuffers, null); } - Dbg.Assert((_invokeAsyncResult is null), "Async result should be null in the reconstruct scenario."); + Dbg.Assert((_invokeAsyncResult == null), "Async result should be null in the reconstruct scenario."); _invokeAsyncResult = new PowerShellAsyncResult(InstanceId, invocationCallback, state, streamToUse, true); } else @@ -2064,7 +2064,7 @@ public IAsyncResult ConnectAsync( OutputBuffer = output; OutputBufferOwner = false; } - else if (_invokeAsyncResult.Output is null || + else if (_invokeAsyncResult.Output == null || !_invokeAsyncResult.Output.IsOpen) { OutputBuffer = new PSDataCollection(); @@ -2129,7 +2129,7 @@ private void CheckRunspacePoolAndConnect() remoteRunspacePoolInternal = (_rsConnection as RunspacePool).RemoteRunspacePoolInternal; } - if (remoteRunspacePoolInternal is null) + if (remoteRunspacePoolInternal == null) { throw new InvalidOperationException(PowerShellStrings.CannotConnect); } @@ -2220,7 +2220,7 @@ internal void InvokeWithDebugger( { if (addToHistory) { - if (settings is null) + if (settings == null) { settings = new PSInvocationSettings(); } @@ -2725,7 +2725,7 @@ public void Invoke(IEnumerable input, IList output) /// public void Invoke(IEnumerable input, IList output, PSInvocationSettings settings) { - if (output is null) + if (output == null) { throw PSTraceSource.NewArgumentNullException(nameof(output)); } @@ -2796,7 +2796,7 @@ public void Invoke(IEnumerable input, IList output, PSInvocationSettings s /// public void Invoke(PSDataCollection input, PSDataCollection output, PSInvocationSettings settings) { - if (output is null) + if (output == null) { throw PSTraceSource.NewArgumentNullException(nameof(output)); } @@ -3032,7 +3032,7 @@ public IAsyncResult BeginInvoke(PSDataCollection input, /// public IAsyncResult BeginInvoke(PSDataCollection input, PSDataCollection output, PSInvocationSettings settings, AsyncCallback callback, object state) { - if (output is null) + if (output == null) { throw PSTraceSource.NewArgumentNullException(nameof(output)); } @@ -3309,7 +3309,7 @@ private IAsyncResult BeginBatchInvoke(PSDataCollection { PSDataCollection asyncOutput = (object)output as PSDataCollection; - if (asyncOutput is null) + if (asyncOutput == null) { throw PSTraceSource.NewInvalidOperationException(); } @@ -3404,7 +3404,7 @@ private void BatchInvocationWorkItem(object state) // If we get here, then ErrorActionPreference is either Continue, // SilentlyContinue, or Inquire (Continue), so we just continue.... - if (_batchInvocationSettings is null) + if (_batchInvocationSettings == null) { ActionPreference preference = (ActionPreference)Runspace.SessionStateProxy.GetVariable("ErrorActionPreference"); @@ -3504,7 +3504,7 @@ private void BatchInvocationCallback(IAsyncResult result) break; } - if (objs is null) + if (objs == null) { objs = _batchAsyncResult.Output; } @@ -3647,14 +3647,14 @@ public PSDataCollection EndInvoke(IAsyncResult asyncResult) { _commandInvokedSynchronously = true; - if (asyncResult is null) + if (asyncResult == null) { throw PSTraceSource.NewArgumentNullException(nameof(asyncResult)); } PowerShellAsyncResult psAsyncResult = asyncResult as PowerShellAsyncResult; - if ((psAsyncResult is null) || + if ((psAsyncResult == null) || (psAsyncResult.OwnerId != InstanceId) || (psAsyncResult.IsAssociatedWithAsyncInvoke != true)) { @@ -3750,14 +3750,14 @@ public IAsyncResult BeginStop(AsyncCallback callback, object state) /// public void EndStop(IAsyncResult asyncResult) { - if (asyncResult is null) + if (asyncResult == null) { throw PSTraceSource.NewArgumentNullException(nameof(asyncResult)); } PowerShellAsyncResult psAsyncResult = asyncResult as PowerShellAsyncResult; - if ((psAsyncResult is null) || + if ((psAsyncResult == null) || (psAsyncResult.OwnerId != InstanceId) || (psAsyncResult.IsAssociatedWithAsyncInvoke)) { @@ -3889,7 +3889,7 @@ internal ExecutionContext GetContextFromTLS() ExecutionContext context = LocalPipeline.GetExecutionContextFromTLS(); // If ExecutionContext from TLS is null then we are not in powershell engine thread. - if (context is null) + if (context == null) { string scriptText = this.Commands.Commands.Count > 0 ? this.Commands.Commands[0].CommandText : null; PSInvalidOperationException e = null; @@ -4770,7 +4770,7 @@ private IAsyncResult CoreInvokeAsync(PSDataCollection i RunspacePool pool = _rsConnection as RunspacePool; // We dont need to create worker if pool is remote - Prepare(input, output, settings, (pool is null || !pool.IsRemote)); + Prepare(input, output, settings, (pool == null || !pool.IsRemote)); _invokeAsyncResult = new PowerShellAsyncResult(InstanceId, callback, state, asyncResultOutput, true); @@ -4819,7 +4819,7 @@ private IAsyncResult CoreInvokeAsync(PSDataCollection i if (!RemotePowerShell.Initialized) { - if (inputStream is null) + if (inputStream == null) { inputStream = new ObjectStream(); inputStream.Close(); @@ -4971,7 +4971,7 @@ private void Prepare(PSDataCollection input, PSDataColl lock (_syncObject) { - if ((_psCommand is null) || (_psCommand.Commands is null) || (0 == _psCommand.Commands.Count)) + if ((_psCommand == null) || (_psCommand.Commands == null) || (0 == _psCommand.Commands.Count)) { throw PSTraceSource.NewInvalidOperationException(PowerShellStrings.NoCommandToInvoke); } @@ -5075,7 +5075,7 @@ private IAsyncResult CoreStop(bool isSyncCall, AsyncCallback callback, object st case PSInvocationState.Stopping: // Create new stop sync object if none exists. Otherwise return existing. - if (_stopAsyncResult is null) + if (_stopAsyncResult == null) { _stopAsyncResult = new PowerShellAsyncResult(InstanceId, callback, state, null, false); _stopAsyncResult.SetAsCompleted(null); @@ -5385,7 +5385,7 @@ internal void CreateRunspaceIfNeededAndDoWork(Runspace rsToUse, bool isSync) { // Set the host for this local runspace if user specified one. LocalRunspace rs = rsToUse as LocalRunspace; - if (rs is null) + if (rs == null) { lock (_shell._syncObject) { @@ -5646,7 +5646,7 @@ internal void InternalClearSuppressExceptions() _outputStream.Close(); _errorStream.Close(); - if (CurrentlyRunningPipeline is null) + if (CurrentlyRunningPipeline == null) { return; } @@ -5655,7 +5655,7 @@ internal void InternalClearSuppressExceptions() // and pipeline.dispose will not change powershell instances state CurrentlyRunningPipeline.StateChanged -= _shell.PipelineStateChanged; - if ((GetRunspaceAsyncResult is null) && (_shell._rsConnection is null)) + if ((GetRunspaceAsyncResult == null) && (_shell._rsConnection == null)) { // user did not supply a runspace..Invoke* method created // a new runspace..so close it. @@ -5718,7 +5718,7 @@ internal void GetSettings(out bool addToHistory, out bool noInput, out uint apar /// internal static PowerShell FromPSObjectForRemoting(PSObject powerShellAsPSObject) { - if (powerShellAsPSObject is null) + if (powerShellAsPSObject == null) { throw PSTraceSource.NewArgumentNullException(nameof(powerShellAsPSObject)); } @@ -5738,7 +5738,7 @@ internal static PowerShell FromPSObjectForRemoting(PSObject powerShellAsPSObject System.Management.Automation.Runspaces.Command command = System.Management.Automation.Runspaces.Command.FromPSObjectForRemoting(extraCommand); - if (cmd is null) + if (cmd == null) { cmd = new PSCommand(command); } @@ -5758,7 +5758,7 @@ internal static PowerShell FromPSObjectForRemoting(PSObject powerShellAsPSObject System.Management.Automation.Runspaces.Command command = System.Management.Automation.Runspaces.Command.FromPSObjectForRemoting(commandAsPSObject); - if (psCommand is null) + if (psCommand == null) { psCommand = new PSCommand(command); } @@ -5833,7 +5833,7 @@ private List CommandsAsListOfPSObjects(CommandCollection commands, Ver /// internal void SuspendIncomingData() { - if (RemotePowerShell is null) + if (RemotePowerShell == null) { throw new PSNotSupportedException(); } @@ -5849,7 +5849,7 @@ internal void SuspendIncomingData() /// internal void ResumeIncomingData() { - if (RemotePowerShell is null) + if (RemotePowerShell == null) { throw new PSNotSupportedException(); } @@ -5867,7 +5867,7 @@ internal void ResumeIncomingData() /// internal void WaitForServicingComplete() { - if (RemotePowerShell is null) + if (RemotePowerShell == null) { throw new PSNotSupportedException(); } @@ -6151,12 +6151,12 @@ internal class PowerShellStopper : IDisposable internal PowerShellStopper(ExecutionContext context, PowerShell powerShell) { - if (context is null) + if (context == null) { throw new ArgumentNullException(nameof(context)); } - if (powerShell is null) + if (powerShell == null) { throw new ArgumentNullException(nameof(powerShell)); } diff --git a/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs b/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs index d245d56f9d9..35029df1e06 100644 --- a/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs +++ b/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs @@ -60,7 +60,7 @@ public PowerShellProcessInstance(Version powerShellVersion, PSCredential credent startingWindowsPowerShell51 = (powerShellVersion != null) && (powerShellVersion.Major == 5) && (powerShellVersion.Minor == 1); if (startingWindowsPowerShell51) { - if (WinPwshExePath is null) + if (WinPwshExePath == null) { throw new PSInvalidOperationException(RemotingErrorIdStrings.WindowsPowerShellNotPresent); } diff --git a/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs b/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs index 245c3c9741d..3c88f8b9ff7 100644 --- a/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs +++ b/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs @@ -741,7 +741,7 @@ public event EventHandler StateChanged { lock (_syncObject) { - bool firstEntry = (InternalStateChanged is null); + bool firstEntry = (InternalStateChanged == null); InternalStateChanged += value; if (firstEntry) { @@ -758,7 +758,7 @@ public event EventHandler StateChanged lock (_syncObject) { InternalStateChanged -= value; - if (InternalStateChanged is null) + if (InternalStateChanged == null) { _internalPool.StateChanged -= OnStateChanged; } @@ -799,7 +799,7 @@ internal event EventHandler ForwardEvent { lock (_syncObject) { - bool firstEntry = InternalForwardEvent is null; + bool firstEntry = InternalForwardEvent == null; InternalForwardEvent += value; @@ -816,7 +816,7 @@ internal event EventHandler ForwardEvent { InternalForwardEvent -= value; - if (InternalForwardEvent is null) + if (InternalForwardEvent == null) { _internalPool.ForwardEvent -= OnInternalPoolForwardEvent; } @@ -854,7 +854,7 @@ internal event EventHandler RunspaceCreated { lock (_syncObject) { - bool firstEntry = (InternalRunspaceCreated is null); + bool firstEntry = (InternalRunspaceCreated == null); InternalRunspaceCreated += value; if (firstEntry) { @@ -871,7 +871,7 @@ internal event EventHandler RunspaceCreated lock (_syncObject) { InternalRunspaceCreated -= value; - if (InternalRunspaceCreated is null) + if (InternalRunspaceCreated == null) { _internalPool.RunspaceCreated -= OnRunspaceCreated; } diff --git a/src/System.Management.Automation/engine/hostifaces/RunspacePoolInternal.cs b/src/System.Management.Automation/engine/hostifaces/RunspacePoolInternal.cs index ebb1c133b69..37ab127658c 100644 --- a/src/System.Management.Automation/engine/hostifaces/RunspacePoolInternal.cs +++ b/src/System.Management.Automation/engine/hostifaces/RunspacePoolInternal.cs @@ -74,7 +74,7 @@ public RunspacePoolInternal(int minRunspaces, PSHost host) : this(minRunspaces, maxRunspaces) { - if (host is null) + if (host == null) { throw PSTraceSource.NewArgumentNullException(nameof(host)); } @@ -119,12 +119,12 @@ public RunspacePoolInternal(int minRunspaces, PSHost host) : this(minRunspaces, maxRunspaces) { - if (initialSessionState is null) + if (initialSessionState == null) { throw PSTraceSource.NewArgumentNullException(nameof(initialSessionState)); } - if (host is null) + if (host == null) { throw PSTraceSource.NewArgumentNullException(nameof(host)); } @@ -227,11 +227,11 @@ public RunspacePoolStateInfo RunspacePoolStateInfo /// internal virtual PSPrimitiveDictionary GetApplicationPrivateData() { - if (_applicationPrivateData is null) + if (_applicationPrivateData == null) { lock (this.syncObject) { - if (_applicationPrivateData is null) + if (_applicationPrivateData == null) { _applicationPrivateData = new PSPrimitiveDictionary(); } @@ -616,14 +616,14 @@ public IAsyncResult BeginOpen(AsyncCallback callback, object state) /// public void EndOpen(IAsyncResult asyncResult) { - if (asyncResult is null) + if (asyncResult == null) { throw PSTraceSource.NewArgumentNullException(nameof(asyncResult)); } RunspacePoolAsyncResult rsAsyncResult = asyncResult as RunspacePoolAsyncResult; - if ((rsAsyncResult is null) || + if ((rsAsyncResult == null) || (rsAsyncResult.OwnerId != instanceId) || (!rsAsyncResult.IsAssociatedWithAsyncOpen)) { @@ -683,14 +683,14 @@ public virtual IAsyncResult BeginClose(AsyncCallback callback, object state) /// public virtual void EndClose(IAsyncResult asyncResult) { - if (asyncResult is null) + if (asyncResult == null) { throw PSTraceSource.NewArgumentNullException(nameof(asyncResult)); } RunspacePoolAsyncResult rsAsyncResult = asyncResult as RunspacePoolAsyncResult; - if ((rsAsyncResult is null) || + if ((rsAsyncResult == null) || (rsAsyncResult.OwnerId != instanceId) || (rsAsyncResult.IsAssociatedWithAsyncOpen)) { @@ -752,7 +752,7 @@ public Runspace GetRunspace() /// public void ReleaseRunspace(Runspace runspace) { - if (runspace is null) + if (runspace == null) { throw PSTraceSource.NewArgumentNullException(nameof(runspace)); } @@ -891,7 +891,7 @@ internal IAsyncResult BeginGetRunspace( /// internal void CancelGetRunspace(IAsyncResult asyncResult) { - if (asyncResult is null) + if (asyncResult == null) { throw PSTraceSource.NewArgumentNullException(nameof(asyncResult)); } @@ -899,7 +899,7 @@ internal void CancelGetRunspace(IAsyncResult asyncResult) GetRunspaceAsyncResult grsAsyncResult = asyncResult as GetRunspaceAsyncResult; - if ((grsAsyncResult is null) || (grsAsyncResult.OwnerId != instanceId)) + if ((grsAsyncResult == null) || (grsAsyncResult.OwnerId != instanceId)) { throw PSTraceSource.NewArgumentException(nameof(asyncResult), RunspacePoolStrings.AsyncResultNotOwned, @@ -930,7 +930,7 @@ internal void CancelGetRunspace(IAsyncResult asyncResult) /// internal Runspace EndGetRunspace(IAsyncResult asyncResult) { - if (asyncResult is null) + if (asyncResult == null) { throw PSTraceSource.NewArgumentNullException(nameof(asyncResult)); } @@ -938,7 +938,7 @@ internal Runspace EndGetRunspace(IAsyncResult asyncResult) GetRunspaceAsyncResult grsAsyncResult = asyncResult as GetRunspaceAsyncResult; - if ((grsAsyncResult is null) || (grsAsyncResult.OwnerId != instanceId)) + if ((grsAsyncResult == null) || (grsAsyncResult.OwnerId != instanceId)) { throw PSTraceSource.NewArgumentException(nameof(asyncResult), RunspacePoolStrings.AsyncResultNotOwned, diff --git a/src/System.Management.Automation/engine/hostifaces/internalHostuserInterfacesecurity.cs b/src/System.Management.Automation/engine/hostifaces/internalHostuserInterfacesecurity.cs index 0efc2725e16..86286d955e7 100644 --- a/src/System.Management.Automation/engine/hostifaces/internalHostuserInterfacesecurity.cs +++ b/src/System.Management.Automation/engine/hostifaces/internalHostuserInterfacesecurity.cs @@ -61,7 +61,7 @@ public override PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options) { - if (_externalUI is null) + if (_externalUI == null) { ThrowPromptNotInteractive(message); } @@ -76,7 +76,7 @@ public override // PipelineStoppedException is thrown by host when it wants // to stop the pipeline. LocalPipeline lpl = (LocalPipeline)((RunspaceBase)_parent.Context.CurrentRunspace).GetCurrentlyRunningPipeline(); - if (lpl is null) + if (lpl == null) { throw; } diff --git a/src/System.Management.Automation/engine/hostifaces/pipelinebase.cs b/src/System.Management.Automation/engine/hostifaces/pipelinebase.cs index c54f5ca235e..64efdb12e4a 100644 --- a/src/System.Management.Automation/engine/hostifaces/pipelinebase.cs +++ b/src/System.Management.Automation/engine/hostifaces/pipelinebase.cs @@ -126,7 +126,7 @@ protected PipelineBase(PipelineBase pipeline) : this(pipeline.Runspace, null, false, pipeline.IsNested) { // NTRAID#Windows Out Of Band Releases-915851-2005/09/13 - if (pipeline is null) + if (pipeline == null) { throw PSTraceSource.NewArgumentNullException(nameof(pipeline)); } @@ -473,7 +473,7 @@ private void CoreInvoke(IEnumerable input, bool syncCall) throw PSTraceSource.NewObjectDisposedException("pipeline"); } - if (Commands is null || Commands.Count == 0) + if (Commands == null || Commands.Count == 0) { throw PSTraceSource.NewInvalidOperationException( RunspaceStrings.NoCommandInPipeline); @@ -618,7 +618,7 @@ internal void DoConcurrentCheck(bool syncCall, object syncObject, bool isInLock) if (IsNested == false) { - if (currentPipeline is null) + if (currentPipeline == null) { return; } @@ -669,7 +669,7 @@ internal void DoConcurrentCheck(bool syncCall, object syncObject, bool isInLock) RunspaceStrings.NestedPipelineInvokeAsync); } - if (currentPipeline is null) + if (currentPipeline == null) { if (this.IsChild) { @@ -995,7 +995,7 @@ private void Initialize(Runspace runspace, string command, bool addToHistory, bo _isNested = isNested; - if (addToHistory && command is null) + if (addToHistory && command == null) { throw PSTraceSource.NewArgumentNullException(nameof(command)); } diff --git a/src/System.Management.Automation/engine/interpreter/BranchLabel.cs b/src/System.Management.Automation/engine/interpreter/BranchLabel.cs index 65aa79c7a28..919a7b06106 100644 --- a/src/System.Management.Automation/engine/interpreter/BranchLabel.cs +++ b/src/System.Management.Automation/engine/interpreter/BranchLabel.cs @@ -110,7 +110,7 @@ internal void AddBranch(InstructionList instructions, int branchIndex) if (_targetIndex == UnknownIndex) { - if (_forwardBranchFixups is null) + if (_forwardBranchFixups == null) { _forwardBranchFixups = new List(); } diff --git a/src/System.Management.Automation/engine/interpreter/CallInstruction.Generated.cs b/src/System.Management.Automation/engine/interpreter/CallInstruction.Generated.cs index 5645f6673b1..b63bde344bc 100644 --- a/src/System.Management.Automation/engine/interpreter/CallInstruction.Generated.cs +++ b/src/System.Management.Automation/engine/interpreter/CallInstruction.Generated.cs @@ -103,7 +103,7 @@ public virtual object Invoke(params object[] args) { /// private static CallInstruction FastCreate(MethodInfo target, ParameterInfo[] pi) { Type t = TryGetParameterOrReturnType(target, pi, 0); - if (t is null) { + if (t == null) { return new ActionCallInstruction(target); } @@ -138,7 +138,7 @@ private static CallInstruction FastCreate(MethodInfo target, ParameterInfo[] pi) private static CallInstruction FastCreate(MethodInfo target, ParameterInfo[] pi) { Type t = TryGetParameterOrReturnType(target, pi, 1); - if (t is null) { + if (t == null) { if (target.ReturnType == typeof(void)) { return new ActionCallInstruction(target); } @@ -177,7 +177,7 @@ private static CallInstruction FastCreate(MethodInfo target, ParameterInfo[] private static CallInstruction FastCreate(MethodInfo target, ParameterInfo[] pi) { Type t = TryGetParameterOrReturnType(target, pi, 2); - if (t is null) { + if (t == null) { if (target.ReturnType == typeof(void)) { return new ActionCallInstruction(target); } diff --git a/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs b/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs index a590e6b06df..56aca65df37 100644 --- a/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs +++ b/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs @@ -157,7 +157,7 @@ public override Instruction[] Cache { get { - if (s_caches is null) + if (s_caches == null) { s_caches = new Instruction[2][][] { new Instruction[2][], new Instruction[2][] }; } @@ -312,7 +312,7 @@ internal sealed class EnterTryCatchFinallyInstruction : IndexedBranchInstruction internal void SetTryHandler(TryCatchFinallyHandler tryHandler) { - Debug.Assert(_tryHandler is null && tryHandler != null, "the tryHandler can be set only once"); + Debug.Assert(_tryHandler == null && tryHandler != null, "the tryHandler can be set only once"); _tryHandler = tryHandler; } @@ -381,7 +381,7 @@ public override int Run(InterpretedFrame frame) // Search for the best handler in the TryCatchFinally block. If no suitable handler is found, rethrow ExceptionHandler exHandler; frame.InstructionIndex += _tryHandler.GotoHandler(frame, exception, out exHandler); - if (exHandler is null) { throw; } + if (exHandler == null) { throw; } bool rethrow = false; try { @@ -746,7 +746,7 @@ public override int Run(InterpretedFrame frame) private bool Compiled { - get { return _loop is null; } + get { return _loop == null; } } private void Compile(object frameObj) diff --git a/src/System.Management.Automation/engine/interpreter/InstructionFactory.cs b/src/System.Management.Automation/engine/interpreter/InstructionFactory.cs index 06cc5c06777..286fce26f15 100644 --- a/src/System.Management.Automation/engine/interpreter/InstructionFactory.cs +++ b/src/System.Management.Automation/engine/interpreter/InstructionFactory.cs @@ -26,7 +26,7 @@ internal abstract class InstructionFactory internal static InstructionFactory GetFactory(Type type) { - if (s_factories is null) + if (s_factories == null) { var factories = new ConditionalWeakTable(); factories.Add(typeof(object), InstructionFactory.Factory); @@ -113,7 +113,7 @@ protected internal override Instruction NewArrayInit(int elementCount) { if (elementCount < MaxArrayInitElementCountCache) { - if (_newArrayInit is null) + if (_newArrayInit == null) { _newArrayInit = new Instruction[MaxArrayInitElementCountCache]; } diff --git a/src/System.Management.Automation/engine/interpreter/InstructionList.cs b/src/System.Management.Automation/engine/interpreter/InstructionList.cs index dd718d7bac0..9617c746359 100644 --- a/src/System.Management.Automation/engine/interpreter/InstructionList.cs +++ b/src/System.Management.Automation/engine/interpreter/InstructionList.cs @@ -231,7 +231,7 @@ private void UpdateStackDepth(Instruction instruction) public void SetDebugCookie(object cookie) { #if DEBUG - if (_debugCookies is null) + if (_debugCookies == null) { _debugCookies = new List>(); } @@ -351,13 +351,13 @@ public void EmitLoad(bool value) public void EmitLoad(object value, Type type) { - if (value is null) + if (value == null) { Emit(s_null ?? (s_null = new LoadObjectInstruction(null))); return; } - if (type is null || type.IsValueType) + if (type == null || type.IsValueType) { if (value is bool) { @@ -370,7 +370,7 @@ public void EmitLoad(object value, Type type) int i = (int)value; if (i >= PushIntMinCachedValue && i <= PushIntMaxCachedValue) { - if (s_ints is null) + if (s_ints == null) { s_ints = new Instruction[PushIntMaxCachedValue - PushIntMinCachedValue + 1]; } @@ -382,10 +382,10 @@ public void EmitLoad(object value, Type type) } } - if (_objects is null) + if (_objects == null) { _objects = new List(); - if (s_loadObjectCached is null) + if (s_loadObjectCached == null) { s_loadObjectCached = new Instruction[CachedObjectCount]; } @@ -449,7 +449,7 @@ internal void SwitchToBoxed(int index, int instructionIndex) public void EmitLoadLocal(int index) { - if (s_loadLocal is null) + if (s_loadLocal == null) { s_loadLocal = new Instruction[LocalInstrCacheSize]; } @@ -471,7 +471,7 @@ public void EmitLoadLocalBoxed(int index) internal static Instruction LoadLocalBoxed(int index) { - if (s_loadLocalBoxed is null) + if (s_loadLocalBoxed == null) { s_loadLocalBoxed = new Instruction[LocalInstrCacheSize]; } @@ -488,7 +488,7 @@ internal static Instruction LoadLocalBoxed(int index) public void EmitLoadLocalFromClosure(int index) { - if (s_loadLocalFromClosure is null) + if (s_loadLocalFromClosure == null) { s_loadLocalFromClosure = new Instruction[LocalInstrCacheSize]; } @@ -505,7 +505,7 @@ public void EmitLoadLocalFromClosure(int index) public void EmitLoadLocalFromClosureBoxed(int index) { - if (s_loadLocalFromClosureBoxed is null) + if (s_loadLocalFromClosureBoxed == null) { s_loadLocalFromClosureBoxed = new Instruction[LocalInstrCacheSize]; } @@ -522,7 +522,7 @@ public void EmitLoadLocalFromClosureBoxed(int index) public void EmitAssignLocal(int index) { - if (s_assignLocal is null) + if (s_assignLocal == null) { s_assignLocal = new Instruction[LocalInstrCacheSize]; } @@ -539,7 +539,7 @@ public void EmitAssignLocal(int index) public void EmitStoreLocal(int index) { - if (s_storeLocal is null) + if (s_storeLocal == null) { s_storeLocal = new Instruction[LocalInstrCacheSize]; } @@ -561,7 +561,7 @@ public void EmitAssignLocalBoxed(int index) internal static Instruction AssignLocalBoxed(int index) { - if (s_assignLocalBoxed is null) + if (s_assignLocalBoxed == null) { s_assignLocalBoxed = new Instruction[LocalInstrCacheSize]; } @@ -583,7 +583,7 @@ public void EmitStoreLocalBoxed(int index) internal static Instruction StoreLocalBoxed(int index) { - if (s_storeLocalBoxed is null) + if (s_storeLocalBoxed == null) { s_storeLocalBoxed = new Instruction[LocalInstrCacheSize]; } @@ -600,7 +600,7 @@ internal static Instruction StoreLocalBoxed(int index) public void EmitAssignLocalToClosure(int index) { - if (s_assignLocalToClosure is null) + if (s_assignLocalToClosure == null) { s_assignLocalToClosure = new Instruction[LocalInstrCacheSize]; } @@ -645,7 +645,7 @@ internal void EmitInitializeParameter(int index) internal static Instruction Parameter(int index) { - if (s_parameter is null) + if (s_parameter == null) { s_parameter = new Instruction[LocalInstrCacheSize]; } @@ -660,7 +660,7 @@ internal static Instruction Parameter(int index) internal static Instruction ParameterBox(int index) { - if (s_parameterBox is null) + if (s_parameterBox == null) { s_parameterBox = new Instruction[LocalInstrCacheSize]; } @@ -675,7 +675,7 @@ internal static Instruction ParameterBox(int index) internal static Instruction InitReference(int index) { - if (s_initReference is null) + if (s_initReference == null) { s_initReference = new Instruction[LocalInstrCacheSize]; } @@ -690,7 +690,7 @@ internal static Instruction InitReference(int index) internal static Instruction InitImmutableRefBox(int index) { - if (s_initImmutableRefBox is null) + if (s_initImmutableRefBox == null) { s_initImmutableRefBox = new Instruction[LocalInstrCacheSize]; } @@ -1081,7 +1081,7 @@ internal static Instruction CreateDynamicInstruction(Type delegateType, CallSite } Type instructionType = DynamicInstructionN.GetDynamicInstructionType(delegateType); - if (instructionType is null) + if (instructionType == null) { return new DynamicInstructionN(delegateType, CallSite.Create(delegateType, binder)); } @@ -1125,7 +1125,7 @@ private RuntimeLabel[] BuildRuntimeLabels() public BranchLabel MakeLabel() { - if (_labels is null) + if (_labels == null) { _labels = new List(); } diff --git a/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs b/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs index a66a0b2293f..d4d6923da81 100644 --- a/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs +++ b/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs @@ -180,7 +180,7 @@ public IEnumerable GetStackTraceDebugInfo() internal void SaveTraceToException(Exception exception) { - if (exception.Data[typeof(InterpretedFrameInfo)] is null) + if (exception.Data[typeof(InterpretedFrameInfo)] == null) { exception.Data[typeof(InterpretedFrameInfo)] = new List(GetStackTraceDebugInfo()).ToArray(); } diff --git a/src/System.Management.Automation/engine/interpreter/Interpreter.cs b/src/System.Management.Automation/engine/interpreter/Interpreter.cs index d414f7c7ab3..8afdfe69b3d 100644 --- a/src/System.Management.Automation/engine/interpreter/Interpreter.cs +++ b/src/System.Management.Automation/engine/interpreter/Interpreter.cs @@ -64,7 +64,7 @@ internal int ClosureSize { get { - if (ClosureVariables is null) + if (ClosureVariables == null) { return 0; } diff --git a/src/System.Management.Automation/engine/interpreter/LabelInfo.cs b/src/System.Management.Automation/engine/interpreter/LabelInfo.cs index 375ca16d326..a8518099824 100644 --- a/src/System.Management.Automation/engine/interpreter/LabelInfo.cs +++ b/src/System.Management.Automation/engine/interpreter/LabelInfo.cs @@ -176,7 +176,7 @@ internal void ValidateFinish() private void EnsureLabel(LightCompiler compiler) { - if (_label is null) + if (_label == null) { _label = compiler.Instructions.MakeLabel(); } @@ -219,14 +219,14 @@ private LabelScopeInfo FirstDefinition() private void AddDefinition(LabelScopeInfo scope) { - if (_definitions is null) + if (_definitions == null) { _definitions = scope; } else { HashSet set = _definitions as HashSet; - if (set is null) + if (set == null) { _definitions = set = new HashSet() { (LabelScopeInfo)_definitions }; } @@ -336,7 +336,7 @@ internal bool CanJumpInto internal bool ContainsTarget(LabelTarget target) { - if (_labels is null) + if (_labels == null) { return false; } @@ -346,7 +346,7 @@ internal bool ContainsTarget(LabelTarget target) internal bool TryGetLabelInfo(LabelTarget target, out LabelInfo info) { - if (_labels is null) + if (_labels == null) { info = null; return false; @@ -359,7 +359,7 @@ internal void AddLabelInfo(LabelTarget target, LabelInfo info) { Debug.Assert(CanJumpInto); - if (_labels is null) + if (_labels == null) { _labels = new HybridReferenceDictionary(); } diff --git a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs index bf2ac7542b6..e5d399bf480 100644 --- a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs +++ b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs @@ -38,7 +38,7 @@ internal sealed class ExceptionHandler internal TryCatchFinallyHandler Parent = null; - public bool IsFault { get { return ExceptionType is null; } } + public bool IsFault { get { return ExceptionType == null; } } internal ExceptionHandler(int start, int end, int labelIndex, int handlerStartIndex, int handlerEndIndex, Type exceptionType) { @@ -52,13 +52,13 @@ internal ExceptionHandler(int start, int end, int labelIndex, int handlerStartIn internal void SetParent(TryCatchFinallyHandler tryHandler) { - Debug.Assert(Parent is null); + Debug.Assert(Parent == null); Parent = tryHandler; } public bool Matches(Type exceptionType) { - if (ExceptionType is null || ExceptionType.IsAssignableFrom(exceptionType)) + if (ExceptionType == null || ExceptionType.IsAssignableFrom(exceptionType)) { return true; } @@ -68,7 +68,7 @@ public bool Matches(Type exceptionType) public bool IsBetterThan(ExceptionHandler other) { - if (other is null) return true; + if (other == null) return true; Debug.Assert(StartIndex == other.StartIndex && EndIndex == other.EndIndex, "we only need to compare handlers for the same try block"); return HandlerStartIndex < other.HandlerStartIndex; @@ -168,7 +168,7 @@ internal int GotoHandler(InterpretedFrame frame, object exception, out Exception { Debug.Assert(_handlers != null, "we should have at least one handler if the method gets called"); handler = Array.Find(_handlers, t => t.Matches(exception.GetType())); - if (handler is null) { return 0; } + if (handler == null) { return 0; } return frame.Goto(handler.LabelIndex, exception, gotoExceptionHandler: true); } @@ -1123,7 +1123,7 @@ private void CompileLabelExpression(Expression expr) _labelBlock.TryGetLabelInfo(node.Target, out label); // We're in a block but didn't find our label, try switch - if (label is null && _labelBlock.Parent.Kind == LabelScopeKind.Switch) + if (label == null && _labelBlock.Parent.Kind == LabelScopeKind.Switch) { _labelBlock.Parent.TryGetLabelInfo(node.Target, out label); } @@ -1132,7 +1132,7 @@ private void CompileLabelExpression(Expression expr) Debug.Assert(label != null); } - if (label is null) + if (label == null) { label = DefineLabel(node.Target); } @@ -1202,7 +1202,7 @@ private LabelInfo ReferenceLabel(LabelTarget node) internal LabelInfo DefineLabel(LabelTarget node) { - if (node is null) + if (node == null) { return new LabelInfo(null); } @@ -1298,7 +1298,7 @@ private bool TryPushLabelBlock(Expression node) private void DefineBlockLabels(Expression node) { var block = node as BlockExpression; - if (block is null) + if (block == null) { return; } @@ -1330,7 +1330,7 @@ private void CompileThrowUnaryExpression(Expression expr, bool asVoid) { var node = (UnaryExpression)expr; - if (node.Operand is null) + if (node.Operand == null) { CompileParameterExpression(_exceptionForRethrowStack.Peek()); if (asVoid) @@ -1362,7 +1362,7 @@ private bool EndsWithRethrow(Expression expr) if (expr.NodeType == ExpressionType.Throw) { var node = (UnaryExpression)expr; - return node.Operand is null; + return node.Operand == null; } BlockExpression block = expr as BlockExpression; @@ -1381,7 +1381,7 @@ private void CompileAsVoidRemoveRethrow(Expression expr) if (expr.NodeType == ExpressionType.Throw) { - Debug.Assert(((UnaryExpression)expr).Operand is null); + Debug.Assert(((UnaryExpression)expr).Operand == null); return; } @@ -1434,10 +1434,10 @@ private void CompileTryExpression(Expression expr) exHandlers = new List(); // TODO: emulates faults (replace by true fault support) - if (node.Finally is null && node.Handlers.Count == 1) + if (node.Finally == null && node.Handlers.Count == 1) { var handler = node.Handlers[0]; - if (handler.Filter is null && handler.Test == typeof(Exception) && handler.Variable is null) + if (handler.Filter == null && handler.Test == typeof(Exception) && handler.Variable == null) { if (EndsWithRethrow(handler.Body)) { diff --git a/src/System.Management.Automation/engine/interpreter/LightDelegateCreator.cs b/src/System.Management.Automation/engine/interpreter/LightDelegateCreator.cs index 58bf458a683..5c96d2f6870 100644 --- a/src/System.Management.Automation/engine/interpreter/LightDelegateCreator.cs +++ b/src/System.Management.Automation/engine/interpreter/LightDelegateCreator.cs @@ -98,7 +98,7 @@ internal Delegate CreateDelegate(StrongBox[] closure) } } - if (_interpreter is null) + if (_interpreter == null) { // We can't interpret, so force a compile Compile(null); diff --git a/src/System.Management.Automation/engine/interpreter/LightLambdaClosureVisitor.cs b/src/System.Management.Automation/engine/interpreter/LightLambdaClosureVisitor.cs index 043b729a18b..00fe0b95c77 100644 --- a/src/System.Management.Automation/engine/interpreter/LightLambdaClosureVisitor.cs +++ b/src/System.Management.Automation/engine/interpreter/LightLambdaClosureVisitor.cs @@ -149,7 +149,7 @@ protected override Expression VisitRuntimeVariables(RuntimeVariablesExpression n for (int i = 0; i < count; i++) { Expression box = GetClosureItem(node.Variables[i], false); - if (box is null) + if (box == null) { indexes[i] = vars.Count; vars.Add(node.Variables[i]); @@ -187,7 +187,7 @@ protected override Expression VisitRuntimeVariables(RuntimeVariablesExpression n protected override Expression VisitParameter(ParameterExpression node) { Expression closureItem = GetClosureItem(node, true); - if (closureItem is null) + if (closureItem == null) { return node; } diff --git a/src/System.Management.Automation/engine/interpreter/LocalAccess.cs b/src/System.Management.Automation/engine/interpreter/LocalAccess.cs index a4ad42d3fe7..7b0711b1930 100644 --- a/src/System.Management.Automation/engine/interpreter/LocalAccess.cs +++ b/src/System.Management.Automation/engine/interpreter/LocalAccess.cs @@ -39,7 +39,7 @@ protected LocalAccessInstruction(int index) public override string ToDebugString(int instructionIndex, object cookie, Func labelIndexer, IList objects) { - return cookie is null ? + return cookie == null ? InstructionName + "(" + _index + ")" : InstructionName + "(" + cookie + ": " + _index + ")"; } diff --git a/src/System.Management.Automation/engine/interpreter/LocalVariables.cs b/src/System.Management.Automation/engine/interpreter/LocalVariables.cs index f9e28d96e26..97908c8b2b6 100644 --- a/src/System.Management.Automation/engine/interpreter/LocalVariables.cs +++ b/src/System.Management.Automation/engine/interpreter/LocalVariables.cs @@ -118,7 +118,7 @@ public override bool Equals(object obj) public override int GetHashCode() { - if (_parameter is null) + if (_parameter == null) { return 0; } @@ -160,7 +160,7 @@ public LocalDefinition DefineLocal(ParameterExpression variable, int start) if (_variables.TryGetValue(variable, out existing)) { newScope = new VariableScope(result, start, existing); - if (existing.ChildScopes is null) + if (existing.ChildScopes == null) { existing.ChildScopes = new List(); } @@ -293,7 +293,7 @@ internal Dictionary ClosureVariables internal LocalVariable AddClosureVariable(ParameterExpression variable) { - if (_closureVariables is null) + if (_closureVariables == null) { _closureVariables = new Dictionary(); } diff --git a/src/System.Management.Automation/engine/interpreter/LoopCompiler.cs b/src/System.Management.Automation/engine/interpreter/LoopCompiler.cs index b7933085921..6ff0e36f5c3 100644 --- a/src/System.Management.Automation/engine/interpreter/LoopCompiler.cs +++ b/src/System.Management.Automation/engine/interpreter/LoopCompiler.cs @@ -206,7 +206,7 @@ protected override Expression VisitBlock(BlockExpression node) private HashSet EnterVariableScope(ICollection variables) { - if (_loopLocals is null) + if (_loopLocals == null) { _loopLocals = new HashSet(variables); return null; @@ -374,7 +374,7 @@ private Expression VisitVariable(ParameterExpression node, ExpressionAccess acce private ParameterExpression AddTemp(ParameterExpression variable) { - if (_temps is null) + if (_temps == null) { _temps = new List(); } diff --git a/src/System.Management.Automation/engine/interpreter/Utilities.cs b/src/System.Management.Automation/engine/interpreter/Utilities.cs index 3001068a088..810dea30d1a 100644 --- a/src/System.Management.Automation/engine/interpreter/Utilities.cs +++ b/src/System.Management.Automation/engine/interpreter/Utilities.cs @@ -261,9 +261,9 @@ internal static object GetPrimitiveDefaultValue(Type type) case TypeCode.DateTime: return default(DateTime); case TypeCode.Decimal: return default(Decimal); // TypeCode.Empty: null; - // TypeCode.Object: default(object) is null; - // TypeCode.DBNull: default(DBNull) is null; - // TypeCode.String: default(string) is null; + // TypeCode.Object: default(object) == null; + // TypeCode.DBNull: default(DBNull) == null; + // TypeCode.String: default(string) == null; default: return null; } } @@ -537,7 +537,7 @@ public TValue this[TKey key] _keysAndValues[i] = new KeyValuePair(key, value); return; } - else if (_keysAndValues[i].Key is null) + else if (_keysAndValues[i].Key == null) { index = i; } @@ -725,7 +725,7 @@ public T Value } /// - /// Gets the current value if its not is null or calls the provided function + /// Gets the current value if its not == null or calls the provided function /// to create a new value. /// public T GetOrCreate(Func func) @@ -734,7 +734,7 @@ public T GetOrCreate(Func func) StorageInfo si = GetStorageInfo(); T res = si.Value; - if (res is null) + if (res == null) { si.Value = res = func(); } @@ -841,7 +841,7 @@ private StorageInfo CreateStorageInfo() } // check and make sure we have a space in the array for our value - if (curStorage is null) + if (curStorage == null) { curStorage = new StorageInfo[threadId + 1]; } @@ -862,7 +862,7 @@ private StorageInfo CreateStorageInfo() // create our StorageInfo in the array, the empty check ensures we're only here // when we need to create. - Debug.Assert(curStorage[threadId] is null || curStorage[threadId].Thread != Thread.CurrentThread); + Debug.Assert(curStorage[threadId] == null || curStorage[threadId].Thread != Thread.CurrentThread); return curStorage[threadId] = newInfo; } diff --git a/src/System.Management.Automation/engine/lang/interface/PSParser.cs b/src/System.Management.Automation/engine/lang/interface/PSParser.cs index 3df14dfea14..2b6886dbce6 100644 --- a/src/System.Management.Automation/engine/lang/interface/PSParser.cs +++ b/src/System.Management.Automation/engine/lang/interface/PSParser.cs @@ -146,7 +146,7 @@ private Collection Errors /// public static Collection Tokenize(string script, out Collection errors) { - if (script is null) + if (script == null) throw PSTraceSource.NewArgumentNullException(nameof(script)); PSParser psParser = new PSParser(); @@ -173,7 +173,7 @@ public static Collection Tokenize(string script, out Collection public static Collection Tokenize(object[] script, out Collection errors) { - if (script is null) + if (script == null) throw PSTraceSource.NewArgumentNullException(nameof(script)); StringBuilder sb = new StringBuilder(); diff --git a/src/System.Management.Automation/engine/lang/parserutils.cs b/src/System.Management.Automation/engine/lang/parserutils.cs index d2a34e3de67..d3af98dcea5 100644 --- a/src/System.Management.Automation/engine/lang/parserutils.cs +++ b/src/System.Management.Automation/engine/lang/parserutils.cs @@ -329,7 +329,7 @@ internal static int FixNum(object obj, IScriptExtent errorPosition) { obj = PSObject.Base(obj); - if (obj is null) + if (obj == null) return 0; if (obj is int) return (int)obj; @@ -381,7 +381,7 @@ internal static object ImplicitOp(object lval, object rval, string op, IScriptEx Type lvalType = lval != null ? lval.GetType() : null; Type rvalType = rval != null ? rval.GetType() : null; Type opType; - if (lvalType is null || (lvalType.IsPrimitive)) + if (lvalType == null || (lvalType.IsPrimitive)) { // Prefer the LHS type when looking for the operator, but attempt the right // the lhs can't have an operator. @@ -390,20 +390,20 @@ internal static object ImplicitOp(object lval, object rval, string op, IScriptEx // would look for overloads in both types, but this logic covers the most common // cases. - opType = (rvalType is null || rvalType.IsPrimitive) ? null : rvalType; + opType = (rvalType == null || rvalType.IsPrimitive) ? null : rvalType; } else { opType = lvalType; } - if (opType is null) + if (opType == null) { throw InterpreterError.NewInterpreterException(lval, typeof(RuntimeException), errorPosition, "NotADefinedOperationForType", ParserStrings.NotADefinedOperationForType, - lvalType is null ? "$null" : lvalType.FullName, + lvalType == null ? "$null" : lvalType.FullName, errorOp, - rvalType is null ? "$null" : rvalType.FullName); + rvalType == null ? "$null" : rvalType.FullName); } // None of the explicit conversions worked so try and invoke a method instead... @@ -530,7 +530,7 @@ private static IReadOnlyList SplitOperatorImpl(ExecutionContext context, if (args.Length >= 1) { predicate = args[0] as ScriptBlock; - if (predicate is null) + if (predicate == null) { separatorPattern = PSObject.ToStringParser(context, args[0]); } @@ -547,7 +547,7 @@ private static IReadOnlyList SplitOperatorImpl(ExecutionContext context, if (args.Length >= 3 && args[2] != null) { string args2asString = args[2] as string; - if (args2asString is null || !string.IsNullOrEmpty(args2asString)) + if (args2asString == null || !string.IsNullOrEmpty(args2asString)) { options = ConvertTo(args[2], errorPosition); if (predicate != null) @@ -567,7 +567,7 @@ private static IReadOnlyList SplitOperatorImpl(ExecutionContext context, options |= SplitOptions.IgnoreCase; } - if (predicate is null) + if (predicate == null) { return SplitWithPattern(context, errorPosition, content, separatorPattern, limit, options); } @@ -952,7 +952,7 @@ internal static object ReplaceOperator(ExecutionContext context, IScriptExtent e } Regex rr = pattern as Regex; - if (rr is null) + if (rr == null) { try { @@ -966,7 +966,7 @@ internal static object ReplaceOperator(ExecutionContext context, IScriptExtent e } IEnumerator list = LanguagePrimitives.GetEnumerator(lval); - if (list is null) + if (list == null) { string lvalString; if (ExperimentalFeature.IsEnabled("PSCultureInvariantReplaceOperator")) @@ -1049,11 +1049,11 @@ internal static object IsOperator(ExecutionContext context, IScriptExtent errorP Type rType = rval as Type; - if (rType is null) + if (rType == null) { rType = ConvertTo(rval, errorPosition); - if (rType is null) + if (rType == null) { // "the right operand of '-is' must be a type" throw InterpreterError.NewInterpreterException(rval, typeof(RuntimeException), @@ -1090,11 +1090,11 @@ internal static object IsNotOperator(ExecutionContext context, IScriptExtent err Type rType = rval as Type; - if (rType is null) + if (rType == null) { rType = ConvertTo(rval, errorPosition); - if (rType is null) + if (rType == null) { // "the right operand of '-is' must be a type" throw InterpreterError.NewInterpreterException(rval, typeof(RuntimeException), @@ -1128,7 +1128,7 @@ internal static object IsNotOperator(ExecutionContext context, IScriptExtent err internal static object LikeOperator(ExecutionContext context, IScriptExtent errorPosition, object lval, object rval, TokenKind @operator) { var wcp = rval as WildcardPattern; - if (wcp is null) + if (wcp == null) { var ignoreCase = @operator == TokenKind.Ilike || @operator == TokenKind.Inotlike; wcp = WildcardPattern.Get(PSObject.ToStringParser(context, rval), @@ -1137,9 +1137,9 @@ internal static object LikeOperator(ExecutionContext context, IScriptExtent erro bool notLike = @operator == TokenKind.Inotlike || @operator == TokenKind.Cnotlike; IEnumerator list = LanguagePrimitives.GetEnumerator(lval); - if (list is null) + if (list == null) { - string lvalString = lval is null ? string.Empty : PSObject.ToStringParser(context, lval); + string lvalString = lval == null ? string.Empty : PSObject.ToStringParser(context, lval); return BoolToObject(wcp.IsMatch(lvalString) ^ notLike); } @@ -1150,7 +1150,7 @@ internal static object LikeOperator(ExecutionContext context, IScriptExtent erro { object val = ParserOps.Current(errorPosition, list); - string lvalString = val is null ? string.Empty : PSObject.ToStringParser(context, val); + string lvalString = val == null ? string.Empty : PSObject.ToStringParser(context, val); if (wcp.IsMatch(lvalString) ^ notLike) { @@ -1183,9 +1183,9 @@ internal static object MatchOperator(ExecutionContext context, IScriptExtent err ?? NewRegex(PSObject.ToStringParser(context, rval), reOptions); IEnumerator list = LanguagePrimitives.GetEnumerator(lval); - if (list is null) + if (list == null) { - string lvalString = lval is null ? string.Empty : PSObject.ToStringParser(context, lval); + string lvalString = lval == null ? string.Empty : PSObject.ToStringParser(context, lval); // Find a match in the string. Match m = r.Match(lvalString); @@ -1228,7 +1228,7 @@ internal static object MatchOperator(ExecutionContext context, IScriptExtent err { object val = list.Current; - string lvalString = val is null ? string.Empty : PSObject.ToStringParser(context, val); + string lvalString = val == null ? string.Empty : PSObject.ToStringParser(context, val); // Find a single match in the string. Match m = r.Match(lvalString); @@ -1277,7 +1277,7 @@ internal static bool ContainsOperatorCompiled(ExecutionContext context, object right) { IEnumerator list = getEnumeratorSite.Target.Invoke(getEnumeratorSite, left); - if (list is null || list is EnumerableOps.NonEnumerableObjectEnumerator) + if (list == null || list is EnumerableOps.NonEnumerableObjectEnumerator) { return (bool)comparerSite.Target.Invoke(comparerSite, left, right); } @@ -1307,7 +1307,7 @@ internal static bool ContainsOperatorCompiled(ExecutionContext context, internal static object ContainsOperator(ExecutionContext context, IScriptExtent errorPosition, object left, object right, bool contains, bool ignoreCase) { IEnumerator list = LanguagePrimitives.GetEnumerator(left); - if (list is null) + if (list == null) { return BoolToObject(contains == @@ -1332,7 +1332,7 @@ internal static object ContainsOperator(ExecutionContext context, IScriptExtent internal static object CompareOperators(ExecutionContext context, IScriptExtent errorPosition, object left, object right, CompareDelegate compareDelegate, bool ignoreCase) { IEnumerator list = LanguagePrimitives.GetEnumerator(left); - if (list is null) + if (list == null) { return BoolToObject(compareDelegate(left, right, ignoreCase)); } @@ -1461,13 +1461,13 @@ internal static object Current(IScriptExtent errorPosition, IEnumerator enumerat /// The obj's type full name. internal static string GetTypeFullName(object obj) { - if (obj is null) + if (obj == null) { return string.Empty; } PSObject mshObj = obj as PSObject; - if (mshObj is null) + if (mshObj == null) { return obj.GetType().FullName; } @@ -1539,7 +1539,7 @@ internal static object CallMethod( targetMethod = targetAsPSObject.Members[methodName] as PSMethodInfo; } - if (targetMethod is null) + if (targetMethod == null) { string typeFullName = null; if (callStatic) @@ -1573,7 +1573,7 @@ internal static object CallMethod( { PSParameterizedProperty propertyToSet = targetMethod as PSParameterizedProperty; - if (propertyToSet is null) + if (propertyToSet == null) { throw InterpreterError.NewInterpreterException(methodName, typeof(RuntimeException), errorPosition, "ParameterizedPropertyAssignmentFailed", ParserStrings.ParameterizedPropertyAssignmentFailed, GetTypeFullName(target), methodName); @@ -1597,13 +1597,13 @@ internal static object CallMethod( } catch (MethodInvocationException mie) { - if (mie.ErrorRecord.InvocationInfo is null) + if (mie.ErrorRecord.InvocationInfo == null) mie.ErrorRecord.SetInvocationInfo(new InvocationInfo(null, errorPosition)); throw; } catch (RuntimeException rte) { - if (rte.ErrorRecord.InvocationInfo is null) + if (rte.ErrorRecord.InvocationInfo == null) rte.ErrorRecord.SetInvocationInfo(new InvocationInfo(null, errorPosition)); throw; } @@ -1818,7 +1818,7 @@ internal static RuntimeException NewInterpreterExceptionWithInnerException(objec try { string message; - if (args is null || 0 == args.Length) + if (args == null || 0 == args.Length) { // Don't format in case the string contains literal curly braces message = resourceString; @@ -1919,7 +1919,7 @@ private static RuntimeException NewBackupInterpreterException( Exception innerException) { string message; - if (innerException is null) + if (innerException == null) { // there is no reason this string lookup should fail message = StringUtil.Format(ParserStrings.BackupParserMessage, errorId); @@ -1935,7 +1935,7 @@ private static RuntimeException NewBackupInterpreterException( internal static void UpdateExceptionErrorRecordPosition(Exception exception, IScriptExtent extent) { - if (extent is null || extent == PositionUtilities.EmptyExtent) + if (extent == null || extent == PositionUtilities.EmptyExtent) { return; } @@ -1945,11 +1945,11 @@ internal static void UpdateExceptionErrorRecordPosition(Exception exception, ISc { var errorRecord = icer.ErrorRecord; var invocationInfo = errorRecord.InvocationInfo; - if (invocationInfo is null) + if (invocationInfo == null) { errorRecord.SetInvocationInfo(new InvocationInfo(null, extent)); } - else if (invocationInfo.ScriptPosition is null || invocationInfo.ScriptPosition == PositionUtilities.EmptyExtent) + else if (invocationInfo.ScriptPosition == null || invocationInfo.ScriptPosition == PositionUtilities.EmptyExtent) { invocationInfo.ScriptPosition = extent; errorRecord.LockScriptStackTrace(); @@ -1967,7 +1967,7 @@ internal static void Trace(int level, string messageId, string resourceString, p // Need access to the execution context to see if we should trace. If we // can't get it, then just return... ExecutionContext context = LocalPipeline.GetExecutionContextFromTLS(); - if (context is null) + if (context == null) return; Trace(context, level, messageId, resourceString, args); } @@ -1979,7 +1979,7 @@ internal static void Trace(ExecutionContext context, int level, string messageId if (context.PSDebugTraceLevel > level) { string message; - if (args is null || 0 == args.Length) + if (args == null || 0 == args.Length) { // Don't format in case the string contains literal curly braces message = resourceString; diff --git a/src/System.Management.Automation/engine/lang/scriptblock.cs b/src/System.Management.Automation/engine/lang/scriptblock.cs index ab1d74fc9e6..5930273ee60 100644 --- a/src/System.Management.Automation/engine/lang/scriptblock.cs +++ b/src/System.Management.Automation/engine/lang/scriptblock.cs @@ -700,7 +700,7 @@ internal SessionState SessionState { get { - if (SessionStateInternal is null) + if (SessionStateInternal == null) { ExecutionContext context = LocalPipeline.GetExecutionContextFromTLS(); if (context != null) @@ -714,7 +714,7 @@ internal SessionState SessionState set { - if (value is null) + if (value == null) { throw PSTraceSource.NewArgumentNullException(nameof(value)); } @@ -823,7 +823,7 @@ internal ExecutionContext GetContextFromTLS() ExecutionContext context = LocalPipeline.GetExecutionContextFromTLS(); // If ExecutionContext from TLS is null then we are not in powershell engine thread. - if (context is null) + if (context == null) { string scriptText = this.ToString(); @@ -881,7 +881,7 @@ internal Collection DoInvoke(object dollarUnder, object input, object[ /// private static Collection GetWrappedResult(List result) { - if (result is null || result.Count == 0) + if (result == null || result.Count == 0) { return new Collection(); } @@ -959,7 +959,7 @@ internal void InvokeWithPipe( context = SessionStateInternal.ExecutionContext; shouldGenerateEvent = true; } - else if (context is null) + else if (context == null) { // This will throw. GetContextFromTLS(); @@ -1099,12 +1099,12 @@ public sealed class SteppablePipeline : IDisposable { internal SteppablePipeline(ExecutionContext context, PipelineProcessor pipeline) { - if (pipeline is null) + if (pipeline == null) { throw new ArgumentNullException(nameof(pipeline)); } - if (context is null) + if (context == null) { throw new ArgumentNullException(nameof(context)); } @@ -1131,14 +1131,14 @@ internal SteppablePipeline(ExecutionContext context, PipelineProcessor pipeline) /// Context used to figure out how to route the output and errors. public void Begin(bool expectInput, EngineIntrinsics contextToRedirectTo) { - if (contextToRedirectTo is null) + if (contextToRedirectTo == null) { throw new ArgumentNullException(nameof(contextToRedirectTo)); } ExecutionContext executionContext = contextToRedirectTo.SessionState.Internal.ExecutionContext; CommandProcessorBase commandProcessor = executionContext.CurrentCommandProcessor; - ICommandRuntime crt = commandProcessor is null ? null : commandProcessor.CommandRuntime; + ICommandRuntime crt = commandProcessor == null ? null : commandProcessor.CommandRuntime; Begin(expectInput, crt); } @@ -1150,7 +1150,7 @@ public void Begin(bool expectInput, EngineIntrinsics contextToRedirectTo) /// The command you're calling this from (i.e. instance of PSCmdlet or value of $PSCmdlet variable). public void Begin(InternalCommand command) { - if (command is null || command.MyInvocation is null) + if (command == null || command.MyInvocation == null) { throw new ArgumentNullException(nameof(command)); } @@ -1430,7 +1430,7 @@ internal ScriptBlockInvocationEventArgs( InvocationInfo invocationInfo, object[] args) { - if (scriptBlock is null) + if (scriptBlock == null) { throw PSTraceSource.NewArgumentNullException(nameof(scriptBlock)); } diff --git a/src/System.Management.Automation/engine/parser/Compiler.cs b/src/System.Management.Automation/engine/parser/Compiler.cs index f7e23e8fcf7..e77097f2088 100644 --- a/src/System.Management.Automation/engine/parser/Compiler.cs +++ b/src/System.Management.Automation/engine/parser/Compiler.cs @@ -685,7 +685,7 @@ internal static Expression Constant(int i) } Expression result = s_intConstants[i + 1]; - if (result is null) + if (result == null) { result = Expression.Constant(i); s_intConstants[i + 1] = result; @@ -951,7 +951,7 @@ internal Expression CompileExpressionOperand(ExpressionAst exprAst) private IEnumerable CompileInvocationArguments(IEnumerable arguments) { - return arguments is null ? Array.Empty() : arguments.Select(CompileExpressionOperand); + return arguments == null ? Array.Empty() : arguments.Select(CompileExpressionOperand); } internal Expression ReduceAssignment(ISupportsAssignment left, TokenKind tokenKind, Expression right) @@ -1091,7 +1091,7 @@ internal static Expression CallStringEquals(Expression left, Expression right, b internal static Expression IsStrictMode(int version, Expression executionContext = null) { - if (executionContext is null) + if (executionContext == null) { executionContext = ExpressionCache.NullExecutionContext; } @@ -1155,12 +1155,12 @@ internal static Type GetTypeConstraintForMethodResolution(ExpressionAst expr) expr = ((AttributedExpressionAst)expr).Child; } - return firstConvert is null ? null : firstConvert.Type.TypeName.GetReflectionType(); + return firstConvert == null ? null : firstConvert.Type.TypeName.GetReflectionType(); } internal static PSMethodInvocationConstraints CombineTypeConstraintForMethodResolution(Type targetType, Type argType) { - if (targetType is null && argType is null) + if (targetType == null && argType == null) { return null; } @@ -1170,7 +1170,7 @@ internal static PSMethodInvocationConstraints CombineTypeConstraintForMethodReso internal static PSMethodInvocationConstraints CombineTypeConstraintForMethodResolution(Type targetType, Type[] argTypes) { - if (targetType is null && (argTypes is null || argTypes.Length == 0)) + if (targetType == null && (argTypes == null || argTypes.Length == 0)) { return null; } @@ -1687,7 +1687,7 @@ private static Attribute NewValidateNotNullAttribute(AttributeAst ast) internal static Attribute GetAttribute(AttributeAst attributeAst) { var attributeType = attributeAst.TypeName.GetReflectionAttributeType(); - if (attributeType is null) + if (attributeType == null) { throw InterpreterError.NewInterpreterException( attributeAst, @@ -1734,7 +1734,7 @@ internal static Attribute GetAttribute(AttributeAst attributeAst) // Unwrap the wrapped exception var innerException = tie.InnerException; var rte = innerException as RuntimeException; - if (rte is null) + if (rte == null) { rte = InterpreterError.NewInterpreterExceptionWithInnerException( null, @@ -1761,7 +1761,7 @@ internal static Attribute GetAttribute(TypeConstraintAst typeConstraintAst) type = ihct.CachedType; } - if (type is null) + if (type == null) { type = TypeOps.ResolveTypeName(typeConstraintAst.TypeName, typeConstraintAst.Extent); if (ihct != null) @@ -1972,7 +1972,7 @@ internal void Compile(CompiledScriptBlockData scriptBlock, bool optimize) { // TODO: default argument support var parameters = ((IParameterMetadataProvider)functionMemberAst.Body).Parameters; - if (parameters is null || parameters.Count == 0) + if (parameters == null || parameters.Count == 0) { SpecialMemberFunctionType = functionMemberAst.IsStatic ? SpecialMemberFunctionType.StaticConstructor @@ -2028,7 +2028,7 @@ internal void Compile(CompiledScriptBlockData scriptBlock, bool optimize) // The sequence points are identical optimized or not. Regardless, we want to ensure // that the list is unique no matter when the property is accessed, so make sure it is set just once. - if (scriptBlock.SequencePoints is null) + if (scriptBlock.SequencePoints == null) { scriptBlock.SequencePoints = _sequencePoints.ToArray(); } @@ -2036,7 +2036,7 @@ internal void Compile(CompiledScriptBlockData scriptBlock, bool optimize) private Action CompileTree(Expression> lambda, CompileInterpretChoice compileInterpretChoice) { - if (lambda is null) + if (lambda == null) { return null; } @@ -2100,7 +2100,7 @@ private static object GetExpressionValue( // Can't be exposed to untrusted input - invoking arbitrary code could result in remote code // execution. - if (lambda is null) + if (lambda == null) { lambda = (new Compiler()).CompileSingleExpression(expressionAst, out sequencePoints, out localsTupleType); } @@ -2589,7 +2589,7 @@ private void GenerateTypesAndUsings(ScriptBlockAst rootForDefiningTypesAndUsings // But it's possible that we are loading something from the codepaths that we never execute. // If Parent of rootForDefiningTypesAndUsings is not null, then we already defined all types, when Visit a parent ScriptBlock - if (rootForDefiningTypesAndUsings.Parent is null) + if (rootForDefiningTypesAndUsings.Parent == null) { if (rootForDefiningTypesAndUsings.UsingStatements.Count > 0) { @@ -2673,7 +2673,7 @@ internal static Assembly DefinePowerShellTypes(Ast rootForDefiningTypes, TypeDef { // TODO(sevoroby): this Diagnostic is conceptually right. // BUT It triggers, when we define type in an InitialSessionState and use it later in two different PowerShell instances. - // Diagnostics.Assert(typeAsts[0].Type is null, "We must not call DefinePowerShellTypes twice for the same TypeDefinitionAsts"); + // Diagnostics.Assert(typeAsts[0].Type == null, "We must not call DefinePowerShellTypes twice for the same TypeDefinitionAsts"); if (typeAsts[0].Type != null) { // We treat Type as a mutable buffer field and wipe it here to start definitions from scratch. @@ -2755,7 +2755,7 @@ private static void PopulateRuntimeTypes(ReadOnlyDictionary parseTypePair in parseTimeTypes) { // We only need to populate types, if ASTs are not reused. Otherwise it's already populated. - if (parseTypePair.Value.Type is null) + if (parseTypePair.Value.Type == null) { TypeDefinitionAst typeDefinitionAst; if (!runtimeTypes.TryGetValue(parseTypePair.Key, out typeDefinitionAst)) @@ -2800,7 +2800,7 @@ private static Assembly LoadAssembly(string assemblyName, string scriptFileName) { } - if (assembly is null) + if (assembly == null) { throw InterpreterError.NewInterpreterException( assemblyName, @@ -2922,11 +2922,11 @@ private void GenerateFunctionProlog(List exprs, List(); - bool wantStatic = ourThis is null; + bool wantStatic = ourThis == null; var bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | (wantStatic ? BindingFlags.Static : BindingFlags.Instance); foreach (var propertyMember in _memberFunctionType.Members.OfType()) { - if (propertyMember.InitialValue is null || propertyMember.IsStatic != wantStatic) + if (propertyMember.InitialValue == null || propertyMember.IsStatic != wantStatic) { continue; } @@ -3270,7 +3270,7 @@ private bool ShouldSetExecutionStatusToSuccess(PipelineAst pipelineAst) ExpressionAst expressionAst = pipelineAst.GetPureExpression(); // If the pipeline is not a simple expression, it will set $? - if (expressionAst is null) + if (expressionAst == null) { return false; } @@ -3898,7 +3898,7 @@ private Expression GetRedirectedExpression(CommandExpressionAst commandExpr, boo // This will simply return a Linq.Expression representing the redirection. var compiledRedirection = VisitFileRedirection(fileRedirectionAst); - if (extraFileRedirectExprs is null) + if (extraFileRedirectExprs == null) { extraFileRedirectExprs = new List(commandExpr.Redirections.Count); } @@ -4205,7 +4205,7 @@ private Expression GetCommandArgumentExpression(CommandElementAst element) { result = Expression.Call(CachedReflectionInfo.PipelineOps_CheckAutomationNullInCommandArgumentArray, result); } - else if (constElement is null && result.Type == typeof(object)) + else if (constElement == null && result.Type == typeof(object)) { result = Expression.Call(CachedReflectionInfo.PipelineOps_CheckAutomationNullInCommandArgument, result); } @@ -4330,7 +4330,7 @@ internal static Expression CreateThrow(Type resultType, Type exception, Type[] e const BindingFlags Flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; ConstructorInfo constructor = exception.GetConstructor(Flags, null, CallingConventions.Any, exceptionArgTypes, null); - if (constructor is null) + if (constructor == null) { throw new PSArgumentException("Type doesn't have constructor with a given signature"); } @@ -4769,7 +4769,7 @@ private Expression GenerateWhileLoop(string loopLabel, _generatingWhileOrDoLoop = true; generateLoopBody(loopBodyExprs, breakLabel, continueLabel); _generatingWhileOrDoLoop = false; - if (continueAst is null) + if (continueAst == null) { loopBodyExprs.Add(Expression.Goto(loopTop)); } @@ -5321,11 +5321,11 @@ public object VisitTryStatement(TryStatementAst tryStatementAst) { var ct = c.CatchTypes[index1]; catchTypes[i] = ct.TypeName.GetReflectionType(); - if (catchTypes[i] is null) + if (catchTypes[i] == null) { // Type needs to be resolved at runtime, so we'll use code like: // - // if (catchTypes[i] is null) catchTypes[i] = ResolveTypeName(ct.TypeName) + // if (catchTypes[i] == null) catchTypes[i] = ResolveTypeName(ct.TypeName) // // We use a constant array, resolve just once (unless it fails) to prevent re-resolving // each time it executes. @@ -5590,7 +5590,7 @@ public object VisitThrowStatement(ThrowStatementAst throwStatementAst) // We should not preserve the partial output if exception is thrown when evaluating throwStmt.pipeline. Expression throwExpr = throwStatementAst.IsRethrow ? s_currentExceptionBeingHandled - : (throwStatementAst.Pipeline is null) + : (throwStatementAst.Pipeline == null) ? ExpressionCache.NullConstant : CaptureStatementResults(throwStatementAst.Pipeline, CaptureAstContext.AssignmentWithoutResultPreservation); @@ -5924,13 +5924,13 @@ public object VisitBinaryExpression(BinaryExpressionAst binaryExpressionAst) private static Expression GetLikeRHSOperand(WildcardOptions options, Expression expr) { var constExpr = expr as ConstantExpression; - if (constExpr is null) + if (constExpr == null) { return expr; } var val = constExpr.Value as string; - if (val is null) + if (val == null) { return expr; } @@ -6099,7 +6099,7 @@ public object VisitConvertExpression(ConvertExpressionAst convertExpressionAst) } } - if (childExpr is null) + if (childExpr == null) { childExpr = Compile(convertExpressionAst.Child); } @@ -6397,7 +6397,7 @@ public object VisitArrayExpression(ArrayExpressionAst arrayExpressionAst) ExpressionAst pureExprAst = null; var subExpr = arrayExpressionAst.SubExpression; - if (subExpr.Traps is null) + if (subExpr.Traps == null) { if (subExpr.Statements.Count == 1) { @@ -6668,7 +6668,7 @@ private IEnumerable GetArgumentExprs(Compiler compiler) return _argExprTemps; } - return InvokeMemberExpressionAst.Arguments is null + return InvokeMemberExpressionAst.Arguments == null ? Array.Empty() : InvokeMemberExpressionAst.Arguments.Select(compiler.Compile).ToArray(); } diff --git a/src/System.Management.Automation/engine/parser/ConstantValues.cs b/src/System.Management.Automation/engine/parser/ConstantValues.cs index 483e84221b5..5813ed9d41f 100644 --- a/src/System.Management.Automation/engine/parser/ConstantValues.cs +++ b/src/System.Management.Automation/engine/parser/ConstantValues.cs @@ -34,7 +34,7 @@ public static bool IsConstant(Ast ast, out object constantValue, bool forAttribu parent = parent.Parent; } - if (parent is null) + if (parent == null) { constantValue = ast.Accept(new ConstantValueVisitor { AttributeArgument = forAttribute, RequiresArgument = forRequires }); return true; @@ -161,13 +161,13 @@ public object VisitPipeline(PipelineAst pipelineAst) private static bool IsNullDivisor(ExpressionAst operand) { var varExpr = operand as VariableExpressionAst; - if (varExpr is null) + if (varExpr == null) { return false; } var parent = operand.Parent as BinaryExpressionAst; - if (parent is null || parent.Right != operand) + if (parent == null || parent.Right != operand) { return false; } @@ -209,7 +209,7 @@ public object VisitUnaryExpression(UnaryExpressionAst unaryExpressionAst) public object VisitConvertExpression(ConvertExpressionAst convertExpressionAst) { var type = convertExpressionAst.Type.TypeName.GetReflectionType(); - if (type is null) + if (type == null) { return false; } @@ -267,13 +267,13 @@ public object VisitMemberExpression(MemberExpressionAst memberExpressionAst) } var type = ((TypeExpressionAst)memberExpressionAst.Expression).TypeName.GetReflectionType(); - if (type is null) + if (type == null) { return false; } var member = memberExpressionAst.Member as StringConstantExpressionAst; - if (member is null) + if (member == null) { return false; } diff --git a/src/System.Management.Automation/engine/parser/DebugViewWriter.cs b/src/System.Management.Automation/engine/parser/DebugViewWriter.cs index 495df9c12e6..bc65cefa866 100644 --- a/src/System.Management.Automation/engine/parser/DebugViewWriter.cs +++ b/src/System.Management.Automation/engine/parser/DebugViewWriter.cs @@ -96,7 +96,7 @@ private void NewLine() { } private static int GetId(T e, ref Dictionary ids) { - if (ids is null) { + if (ids == null) { ids = new Dictionary(); ids.Add(e, 1); return 1; @@ -455,7 +455,7 @@ protected override Expression VisitLambda(Expression node) { ) ); - if (_lambdas is null) { + if (_lambdas == null) { _lambdas = new Queue(); } @@ -503,7 +503,7 @@ protected override Expression VisitConditional(ConditionalExpression node) { protected override Expression VisitConstant(ConstantExpression node) { object value = node.Value; - if (value is null) { + if (value == null) { Out("null"); } else if ((value is string) && node.Type == typeof(string)) { Out(string.Format( @@ -595,7 +595,7 @@ protected override Expression VisitInvocation(InvocationExpression node) { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] private static bool NeedsParentheses(Expression parent, Expression child) { Debug.Assert(parent != null); - if (child is null) { + if (child == null) { return false; } @@ -925,7 +925,7 @@ protected override Expression VisitUnary(UnaryExpression node) { Out("'"); break; case ExpressionType.Throw: - if (node.Operand is null) { + if (node.Operand == null) { Out(".Rethrow"); } else { Out(".Throw", Flow.Space); diff --git a/src/System.Management.Automation/engine/parser/FusionAssemblyIdentity.cs b/src/System.Management.Automation/engine/parser/FusionAssemblyIdentity.cs index f1511a24d9f..93e11f598b1 100644 --- a/src/System.Management.Automation/engine/parser/FusionAssemblyIdentity.cs +++ b/src/System.Management.Automation/engine/parser/FusionAssemblyIdentity.cs @@ -175,7 +175,7 @@ internal static unsafe byte[] GetPropertyBytes(IAssemblyName nameObject, Propert internal static unsafe string GetPropertyString(IAssemblyName nameObject, PropertyId propertyId) { byte[] data = GetPropertyBytes(nameObject, propertyId); - if (data is null) + if (data == null) { return null; } @@ -263,7 +263,7 @@ internal static IAssemblyName GetBestMatch(IEnumerable candidates Version candidateVersion = GetVersion(candidate); Debug.Assert(candidateVersion != null); - if (bestVersion is null) + if (bestVersion == null) { bestVersion = GetVersion(bestCandidate); Debug.Assert(bestVersion != null); @@ -277,7 +277,7 @@ internal static IAssemblyName GetBestMatch(IEnumerable candidates string candidateCulture = GetCulture(candidate); Debug.Assert(candidateCulture != null); - if (bestCulture is null) + if (bestCulture == null) { bestCulture = GetCulture(candidate); Debug.Assert(bestCulture != null); diff --git a/src/System.Management.Automation/engine/parser/GlobalAssemblyCache.cs b/src/System.Management.Automation/engine/parser/GlobalAssemblyCache.cs index 9fb742db7c0..467f3f2c5e7 100644 --- a/src/System.Management.Automation/engine/parser/GlobalAssemblyCache.cs +++ b/src/System.Management.Automation/engine/parser/GlobalAssemblyCache.cs @@ -162,14 +162,14 @@ public static unsafe string ResolvePartialName( ProcessorArchitecture[] architectureFilter = null, CultureInfo preferredCulture = null) { - if (displayName is null) + if (displayName == null) { throw new ArgumentNullException("displayName"); } location = null; FusionAssemblyIdentity.IAssemblyName nameObject = FusionAssemblyIdentity.ToAssemblyNameObject(displayName); - if (nameObject is null) + if (nameObject == null) { return null; } @@ -178,7 +178,7 @@ public static unsafe string ResolvePartialName( string cultureName = (preferredCulture != null && !preferredCulture.IsNeutralCulture) ? preferredCulture.Name : null; var bestMatch = FusionAssemblyIdentity.GetBestMatch(candidates, cultureName); - if (bestMatch is null) + if (bestMatch == null) { return null; } diff --git a/src/System.Management.Automation/engine/parser/PSType.cs b/src/System.Management.Automation/engine/parser/PSType.cs index cf57d0e1ff8..8a18f880bab 100644 --- a/src/System.Management.Automation/engine/parser/PSType.cs +++ b/src/System.Management.Automation/engine/parser/PSType.cs @@ -57,7 +57,7 @@ private static CustomAttributeBuilder GetAttributeBuilder(Parser parser, Attribu Diagnostics.Assert(attributeType != null, "Semantic checks should have verified attribute type exists"); Diagnostics.Assert( - attributeType.GetCustomAttribute(true) is null || + attributeType.GetCustomAttribute(true) == null || (attributeType.GetCustomAttribute(true).ValidOn & attributeTargets) != 0, "Semantic checks should have verified attribute usage"); var positionalArgs = new object[attributeAst.PositionalArguments.Count]; @@ -87,7 +87,7 @@ private static CustomAttributeBuilder GetAttributeBuilder(Parser parser, Attribu out expandParamsOnBest, out callNonVirtually); - if (bestMethod is null) + if (bestMethod == null) { parser.ReportError(new ParseError(attributeAst.Extent, errorId, string.Format(CultureInfo.InvariantCulture, errorMsg, attributeType.Name, attributeAst.PositionalArguments.Count))); @@ -340,7 +340,7 @@ private Type GetBaseTypes(Parser parser, TypeDefinitionAst typeDefinitionAst, ou else { baseClass = firstBaseTypeAst.TypeName.GetReflectionType(); - if (baseClass is null) + if (baseClass == null) { parser.ReportError(firstBaseTypeAst.Extent, nameof(ParserStrings.TypeNotFound), @@ -416,7 +416,7 @@ private Type GetBaseTypes(Parser parser, TypeDefinitionAst typeDefinitionAst, ou else { Type interfaceType = baseTypeAsts[i].TypeName.GetReflectionType(); - if (interfaceType is null) + if (interfaceType == null) { parser.ReportError(baseTypeAsts[i].Extent, nameof(ParserStrings.TypeNotFound), @@ -446,7 +446,7 @@ private Type GetBaseTypes(Parser parser, TypeDefinitionAst typeDefinitionAst, ou private bool ShouldImplementProperty(string name, Type type) { - if (_interfaceProperties is null) + if (_interfaceProperties == null) { _interfaceProperties = new HashSet>(); var allInterfaces = new HashSet(); @@ -541,7 +541,7 @@ public void DefineMembers() var parameters = ((IParameterMetadataProvider)ctor.Body).Parameters; // We report error for static ctors with parameters, even with default values. // We don't take them into account. - if (parameters is null || parameters.Count == 0) + if (parameters == null || parameters.Count == 0) { needStaticCtor = false; } @@ -596,7 +596,7 @@ private void DefineProperty(PropertyMemberAst propertyMemberAst) _definedProperties.Add(propertyMemberAst.Name, propertyMemberAst); Type type; - if (propertyMemberAst.PropertyType is null) + if (propertyMemberAst.PropertyType == null) { type = typeof(object); } @@ -766,7 +766,7 @@ private bool CheckForDuplicateOverload(FunctionMemberAst functionMemberAst, Type private Type[] GetParameterTypes(FunctionMemberAst functionMemberAst) { var parameters = ((IParameterMetadataProvider)functionMemberAst).Parameters; - if (parameters is null) + if (parameters == null) { return Type.EmptyTypes; } @@ -779,7 +779,7 @@ private Type[] GetParameterTypes(FunctionMemberAst functionMemberAst) var paramType = (typeConstraint != null) ? typeConstraint.TypeName.GetReflectionType() : typeof(object); - if (paramType is null) + if (paramType == null) { _parser.ReportError(typeConstraint.Extent, nameof(ParserStrings.TypeNotFound), @@ -819,7 +819,7 @@ private bool MethodExistsOnBaseClassAndFinal(string methodName, Type[] parameter private void DefineMethod(FunctionMemberAst functionMemberAst) { var parameterTypes = GetParameterTypes(functionMemberAst); - if (parameterTypes is null) + if (parameterTypes == null) { // There must have been an error, just return return; @@ -871,7 +871,7 @@ private void DefineMethod(FunctionMemberAst functionMemberAst) } var returnType = functionMemberAst.GetReturnType(); - if (returnType is null) + if (returnType == null) { _parser.ReportError(functionMemberAst.ReturnType.Extent, nameof(ParserStrings.TypeNotFound), @@ -1074,7 +1074,7 @@ internal static List Sort(List defineEnumHel foreach (var enumerator in helper._enumDefinitionAst.Members) { var initExpr = ((PropertyMemberAst)enumerator).InitialValue; - if (initExpr is null) + if (initExpr == null) { // No initializer, so no dependency (this is incorrect assumption if // we wanted to be more general like C#.) @@ -1155,7 +1155,7 @@ internal static List Sort(List defineEnumHel internal void DefineEnum() { var typeConstraintAst = _enumDefinitionAst.BaseTypes.FirstOrDefault(); - var underlyingType = typeConstraintAst is null ? typeof(int) : typeConstraintAst.TypeName.GetReflectionType(); + var underlyingType = typeConstraintAst == null ? typeof(int) : typeConstraintAst.TypeName.GetReflectionType(); var definedEnumerators = new HashSet(StringComparer.OrdinalIgnoreCase); var enumBuilder = _moduleBuilder.DefineEnum(_typeName, Reflection.TypeAttributes.Public, underlyingType); @@ -1302,7 +1302,7 @@ private static IEnumerable GetAssemblyAttributeBuilders( internal static Assembly DefineTypes(Parser parser, Ast rootAst, TypeDefinitionAst[] typeDefinitions) { - Diagnostics.Assert(rootAst.Parent is null, "Caller should only define types from the root ast"); + Diagnostics.Assert(rootAst.Parent == null, "Caller should only define types from the root ast"); var definedTypes = new HashSet(StringComparer.OrdinalIgnoreCase); @@ -1427,7 +1427,7 @@ private static string GetClassNameInAssembly(TypeDefinitionAst typeDefinitionAst parent = parent.Parent; } - if (nameParts is null) + if (nameParts == null) { return typeDefinitionAst.Name; } diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index 8c3f8c75bdd..89145011523 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -243,7 +243,7 @@ internal static object ScanNumber(string str, Type toType, bool shouldTryCoercio tokenizer.AllowSignedNumbers = true; var token = tokenizer.NextToken() as NumberToken; - if (token is null || !tokenizer.IsAtEndOfScript(token.Extent)) + if (token == null || !tokenizer.IsAtEndOfScript(token.Extent)) { if (shouldTryCoercion) { @@ -342,7 +342,7 @@ internal void SetPreviousFirstLastToken(ExecutionContext context) private void SkipNewlines() { - if (_ungotToken is null || _ungotToken.Kind == TokenKind.NewLine) + if (_ungotToken == null || _ungotToken.Kind == TokenKind.NewLine) { _ungotToken = null; _tokenizer.SkipNewlines(skipSemis: false); @@ -351,7 +351,7 @@ private void SkipNewlines() private void SkipNewlinesAndSemicolons() { - if (_ungotToken is null || _ungotToken.Kind == TokenKind.NewLine || _ungotToken.Kind == TokenKind.Semi) + if (_ungotToken == null || _ungotToken.Kind == TokenKind.NewLine || _ungotToken.Kind == TokenKind.Semi) { _ungotToken = null; _tokenizer.SkipNewlines(skipSemis: true); @@ -436,7 +436,7 @@ private Token NextToken() private Token PeekToken() { Token token = _ungotToken ?? _tokenizer.NextToken(); - if (_ungotToken is null) + if (_ungotToken == null) _ungotToken = token; return token; } @@ -471,7 +471,7 @@ private Token NextLBracket() private StringToken GetVerbatimCommandArgumentToken() { - if (_ungotToken is null || _ungotToken.Kind == TokenKind.Parameter) + if (_ungotToken == null || _ungotToken.Kind == TokenKind.Parameter) { _ungotToken = null; return _tokenizer.GetVerbatimCommandArgument(); @@ -488,7 +488,7 @@ private void SkipToken() private void UngetToken(Token token) { - Diagnostics.Assert(_ungotToken is null, "Only 1 token lookahead is supported"); + Diagnostics.Assert(_ungotToken == null, "Only 1 token lookahead is supported"); _ungotToken = token; } @@ -716,7 +716,7 @@ internal static bool TryParseAsConstantHashtable(string input, out Hashtable res ParseError[] parseErrors; var ast = Parser.ParseInput(input, out throwAwayTokens, out parseErrors); - if ((ast is null) || + if ((ast == null) || parseErrors.Length > 0 || ast.BeginBlock != null || ast.ProcessBlock != null || @@ -733,19 +733,19 @@ internal static bool TryParseAsConstantHashtable(string input, out Hashtable res } var pipelineAst = statements[0] as PipelineAst; - if (pipelineAst is null) + if (pipelineAst == null) { return false; } var expr = pipelineAst.GetPureExpression(); - if (expr is null) + if (expr == null) { return false; } var hashTableAst = expr as HashtableAst; - if (hashTableAst is null) + if (hashTableAst == null) { return false; } @@ -788,11 +788,11 @@ private ScriptBlockAst ScriptBlockRule(Token lCurly, bool isFilter, StatementAst // Skipping newlines here saves a more expensive resync if there is no parameter block. SkipNewlines(); - var usingStatements = lCurly is null ? UsingStatementsRule() : null; + var usingStatements = lCurly == null ? UsingStatementsRule() : null; var restorePoint = _tokenizer.GetRestorePoint(); ParamBlockAst paramBlock = ParamBlockRule(); - if (paramBlock is null) + if (paramBlock == null) { // In case we scanned some attributes or type constraints but they didn't // belong to a param statement, we need to reparse them (because they will @@ -817,7 +817,7 @@ private List UsingStatementsRule() SkipToken(); var statement = UsingStatementRule(token); SkipNewlinesAndSemicolons(); - if (result is null) + if (result == null) { result = new List(); } @@ -922,7 +922,7 @@ private List ParameterListRule() while (true) { ParameterAst parameter = ParameterRule(); - if (parameter is null) + if (parameter == null) { if (commaToken != null) { @@ -1003,7 +1003,7 @@ private ParameterAst ParameterRule() SkipToken(); SkipNewlines(); defaultValue = ExpressionRule(); - if (defaultValue is null) + if (defaultValue == null) { ReportIncompleteInput(After(equalsToken), nameof(ParserStrings.MissingExpressionAfterToken), @@ -1018,8 +1018,8 @@ private ParameterAst ParameterRule() SetTokenizerMode(oldTokenizerMode); } - IScriptExtent startExtent = (attributes is null) ? variableToken.Extent : attributes[0].Extent; - IScriptExtent endExtent = (defaultValue is null) ? variableToken.Extent : defaultValue.Extent; + IScriptExtent startExtent = (attributes == null) ? variableToken.Extent : attributes[0].Extent; + IScriptExtent endExtent = (defaultValue == null) ? variableToken.Extent : defaultValue.Extent; return new ParameterAst(ExtentOf(startExtent, endExtent), new VariableExpressionAst(variableToken), attributes, defaultValue); } @@ -1059,7 +1059,7 @@ private AttributeBaseAst AttributeRule() // G type-spec var lBracket = NextLBracket(); - if (lBracket is null) + if (lBracket == null) { return null; } @@ -1068,7 +1068,7 @@ private AttributeBaseAst AttributeRule() Token firstTypeNameToken; ITypeName typeName = TypeNameRule(allowAssemblyQualifiedNames: true, firstTypeNameToken: out firstTypeNameToken); - if (typeName is null) + if (typeName == null) { // ErrorRecovery: Return null so we stop looking for attributes. @@ -1187,7 +1187,7 @@ private void AttributeArgumentsRule(ICollection positionalArgumen expr = ExpressionRule(); - if (expr is null) + if (expr == null) { // ErrorRecovery: ? @@ -1619,7 +1619,7 @@ private bool CompleteScriptBlockBody(Token lCurly, ref IScriptExtent bodyExtent, endScriptBlock = rCurly.Extent; // If body was empty, use the extent b/w (but not including) the curlies, but only // if that region has at least 1 character. - if (bodyExtent is null && (lCurly.Extent.EndColumnNumber != rCurly.Extent.StartColumnNumber)) + if (bodyExtent == null && (lCurly.Extent.EndColumnNumber != rCurly.Extent.StartColumnNumber)) { bodyExtent = ExtentOf(After(lCurly), Before(rCurly)); } @@ -1674,7 +1674,7 @@ private ScriptBlockAst ScriptBlockBodyRule(Token lCurly, List while (true) { IScriptExtent extent = StatementListRule(statements, traps); - if (statementListExtent is null) + if (statementListExtent == null) { statementListExtent = extent; } @@ -1729,7 +1729,7 @@ private ScriptBlockAst NamedBlockListRule(Token lCurly, List } else { - // If "lCurly is null", then it's a ps1/psm1 file, and thus the extent is the whole file. + // If "lCurly == null", then it's a ps1/psm1 file, and thus the extent is the whole file. scriptBlockExtent = _tokenizer.GetScriptExtent(); } @@ -1754,7 +1754,7 @@ private ScriptBlockAst NamedBlockListRule(Token lCurly, List break; } - if (startExtent is null) + if (startExtent == null) { startExtent = blockNameToken.Extent; } @@ -1763,7 +1763,7 @@ private ScriptBlockAst NamedBlockListRule(Token lCurly, List StatementBlockAst statementBlock = StatementBlockRule(); - if (statementBlock is null) + if (statementBlock == null) { // ErrorRecovery: Eat the block name and keep going, there might be a valid block next. @@ -1779,19 +1779,19 @@ private ScriptBlockAst NamedBlockListRule(Token lCurly, List } extent = ExtentOf(blockNameToken, endExtent); - if (blockNameToken.Kind == TokenKind.Begin && beginBlock is null) + if (blockNameToken.Kind == TokenKind.Begin && beginBlock == null) { beginBlock = new NamedBlockAst(extent, TokenKind.Begin, statementBlock, false); } - else if (blockNameToken.Kind == TokenKind.Process && processBlock is null) + else if (blockNameToken.Kind == TokenKind.Process && processBlock == null) { processBlock = new NamedBlockAst(extent, TokenKind.Process, statementBlock, false); } - else if (blockNameToken.Kind == TokenKind.End && endBlock is null) + else if (blockNameToken.Kind == TokenKind.End && endBlock == null) { endBlock = new NamedBlockAst(extent, TokenKind.End, statementBlock, false); } - else if (blockNameToken.Kind == TokenKind.Dynamicparam && dynamicParamBlock is null) + else if (blockNameToken.Kind == TokenKind.Dynamicparam && dynamicParamBlock == null) { dynamicParamBlock = new NamedBlockAst(extent, TokenKind.Dynamicparam, statementBlock, false); } @@ -1867,7 +1867,7 @@ private IScriptExtent StatementListRule(List statements, List statements, List statements, List @@ -2309,7 +2309,7 @@ private StatementAst BlockStatementRule(Token kindToken) StatementBlockAst body = StatementBlockRule(); // ErrorRecovery: nothing more to look for, so just return the error statement. - if (body is null) + if (body == null) { ReportIncompleteInput(After(kindToken.Extent), nameof(ParserStrings.MissingStatementAfterKeyword), @@ -2396,7 +2396,7 @@ private StatementAst IfStatementRule(Token ifToken) SkipNewlines(); PipelineBaseAst condition = PipelineChainRule(); - if (condition is null) + if (condition == null) { // ErrorRecovery: assume pipeline just hasn't been entered yet, continue hoping // to find a close paren and statement block. @@ -2436,7 +2436,7 @@ private StatementAst IfStatementRule(Token ifToken) SkipNewlines(); StatementBlockAst body = StatementBlockRule(); - if (body is null) + if (body == null) { // ErrorRecovery: assume the next token is a newline or part of something else, // so stop parsing the statement and try parsing something else. @@ -2462,7 +2462,7 @@ private StatementAst IfStatementRule(Token ifToken) // b = 10 // } - int restorePoint = _ungotToken is null ? _tokenizer.GetRestorePoint() : _ungotToken.Extent.StartOffset; + int restorePoint = _ungotToken == null ? _tokenizer.GetRestorePoint() : _ungotToken.Extent.StartOffset; SkipNewlines(); keyword = PeekToken(); @@ -2476,7 +2476,7 @@ private StatementAst IfStatementRule(Token ifToken) SkipToken(); SkipNewlines(); elseClause = StatementBlockRule(); - if (elseClause is null) + if (elseClause == null) { // ErrorRecovery: assume the next token is a newline or part of something else, // so stop parsing the statement and try parsing something else. @@ -2605,7 +2605,7 @@ private StatementAst SwitchStatementRule(LabelToken labelToken, Token switchToke flags |= SwitchFlags.File; SkipNewlines(); ExpressionAst fileNameExpr = GetSingleCommandArgument(CommandArgumentContext.FileName); - if (fileNameExpr is null) + if (fileNameExpr == null) { // ErrorRecovery: pretend we saw the filename and continue. @@ -2670,7 +2670,7 @@ private StatementAst SwitchStatementRule(LabelToken labelToken, Token switchToke needErrorCondition = true; // need to add condition ast to the error statement if the parsing fails SkipNewlines(); condition = PipelineChainRule(); - if (condition is null) + if (condition == null) { // ErrorRecovery: pretend we saw the condition and keep parsing. @@ -2705,7 +2705,7 @@ private StatementAst SwitchStatementRule(LabelToken labelToken, Token switchToke endErrorStatement = rParen.Extent; } } - else if (condition is null) + else if (condition == null) { if ((flags & SwitchFlags.File) == 0) { @@ -2759,7 +2759,7 @@ private StatementAst SwitchStatementRule(LabelToken labelToken, Token switchToke else { clauseCondition = GetSingleCommandArgument(CommandArgumentContext.SwitchCondition); - if (clauseCondition is null) + if (clauseCondition == null) { // ErrorRecovery: if we don't have anything that looks like a condition, we won't // find a body (because a body is just a script block, which works as a condition.) @@ -2783,7 +2783,7 @@ private StatementAst SwitchStatementRule(LabelToken labelToken, Token switchToke endErrorStatement = clauseCondition.Extent; StatementBlockAst clauseBody = StatementBlockRule(); - if (clauseBody is null) + if (clauseBody == null) { // ErrorRecovery: We might find another condition/body pair, so keep going. @@ -2900,7 +2900,7 @@ private StatementAst ConfigurationStatementRule(IEnumerable custom // Finally read the name for this configuration configurationName = GetWordOrExpression(configurationNameToken); - if (configurationName is null) + if (configurationName == null) { isError = true; ReportIncompleteInput(configurationNameToken.Extent, @@ -2913,7 +2913,7 @@ private StatementAst ConfigurationStatementRule(IEnumerable custom if (IsConstantValueVisitor.IsConstant(configurationName, out outValue)) { simpleConfigurationNameValue = outValue as string; - if (simpleConfigurationNameValue is null || + if (simpleConfigurationNameValue == null || !System.Text.RegularExpressions.Regex.IsMatch(simpleConfigurationNameValue, "^[A-Za-z][A-Za-z0-9_./-]*$")) { // This is actually a semantics check, the syntax is fine at this point. @@ -2938,7 +2938,7 @@ private StatementAst ConfigurationStatementRule(IEnumerable custom { // At this point, we'll need a runspace to use to hold the metadata for the parse. If there is no // current runspace to use, we create one and set it to be the default for this thread... - if (Runspaces.Runspace.DefaultRunspace is null) + if (Runspaces.Runspace.DefaultRunspace == null) { localRunspace = Runspaces.RunspaceFactory.CreateRunspace(Runspaces.InitialSessionState.CreateDefault2()); @@ -2993,7 +2993,7 @@ private StatementAst ConfigurationStatementRule(IEnumerable custom // See of the default CIM keywords are already loaded. If they haven't been // then this is the top level. Record that information and then load the defaults // keywords. - if (DynamicKeyword.GetKeyword("OMI_ConfigurationDocument") is null) + if (DynamicKeyword.GetKeyword("OMI_ConfigurationDocument") == null) { // Load the default CIM keywords Collection CIMKeywordErrors = new Collection(); @@ -3066,7 +3066,7 @@ private StatementAst ConfigurationStatementRule(IEnumerable custom _inConfiguration = oldInConfiguration; } - if (configurationBodyScriptBlock is null) + if (configurationBodyScriptBlock == null) { ReportError(After(lCurly.Extent), nameof(ParserStrings.ConfigurationBodyEmpty), @@ -3174,7 +3174,7 @@ private StatementAst ConfigurationStatementRule(IEnumerable custom if (topLevel) { - if (_configurationKeywordsDefinedInThisFile is null) + if (_configurationKeywordsDefinedInThisFile == null) { _configurationKeywordsDefinedInThisFile = new Dictionary(); } @@ -3272,7 +3272,7 @@ private ExpressionAst GetWordOrExpression(Token keywordToken) } ExpressionAst argument = GetCommandArgument(CommandArgumentContext.CommandArgument, nameToken); - if (argument is null) + if (argument == null) { var extent = keywordToken.Extent; ReportError(After(extent), @@ -3322,7 +3322,7 @@ private StatementAst ForeachStatementRule(LabelToken labelToken, Token forEachTo { SkipNewlines(); throttleLimit = GetSingleCommandArgument(CommandArgumentContext.CommandArgument); - if (throttleLimit is null) + if (throttleLimit == null) { // ErrorRecovery: pretend we saw the throttle limit and continue. @@ -3395,7 +3395,7 @@ private StatementAst ForeachStatementRule(LabelToken labelToken, Token forEachTo { SkipNewlines(); pipeline = PipelineChainRule(); - if (pipeline is null) + if (pipeline == null) { // ErrorRecovery: assume the rest of the statement is missing. @@ -3421,7 +3421,7 @@ private StatementAst ForeachStatementRule(LabelToken labelToken, Token forEachTo else { body = StatementBlockRule(); - if (body is null) + if (body == null) { // ErrorRecovery: nothing more to look for, so just return the error statement. @@ -3523,7 +3523,7 @@ private StatementAst ForStatementRule(LabelToken labelToken, Token forToken) // ErrorRecovery: don't continue parsing the for statement. UngetToken(rParen); - if (endErrorStatement is null) + if (endErrorStatement == null) { endErrorStatement = lParen.Extent; } @@ -3536,7 +3536,7 @@ private StatementAst ForStatementRule(LabelToken labelToken, Token forToken) else { body = StatementBlockRule(); - if (body is null) + if (body == null) { // ErrorRecovery: return an error statement. endErrorStatement = rParen.Extent; @@ -3547,7 +3547,7 @@ private StatementAst ForStatementRule(LabelToken labelToken, Token forToken) } } - if (body is null) + if (body == null) { return new ErrorStatementAst(ExtentOf(labelToken ?? forToken, endErrorStatement), GetNestedErrorAsts(initializer, condition, iterator)); @@ -3584,7 +3584,7 @@ private StatementAst WhileStatementRule(LabelToken labelToken, Token whileToken) SkipNewlines(); PipelineBaseAst condition = PipelineChainRule(); PipelineBaseAst errorCondition = null; - if (condition is null) + if (condition == null) { // ErrorRecovery: assume pipeline just hasn't been entered yet, continue hoping // to find a close paren and statement block. @@ -3624,7 +3624,7 @@ private StatementAst WhileStatementRule(LabelToken labelToken, Token whileToken) SkipNewlines(); StatementBlockAst body = StatementBlockRule(); - if (body is null) + if (body == null) { // ErrorRecovery: assume the next token is a newline or part of something else. @@ -3786,7 +3786,7 @@ private StatementAst DynamicKeywordStatementRule(Token functionName, DynamicKeyw UngetToken(nameToken); instanceName = GetSingleCommandArgument(CommandArgumentContext.CommandName); - if (instanceName is null) + if (instanceName == null) { if (keywordData.NameMode == DynamicKeywordNameMode.SimpleNameRequired || keywordData.NameMode == DynamicKeywordNameMode.SimpleOptionalName) { @@ -3835,7 +3835,7 @@ private StatementAst DynamicKeywordStatementRule(Token functionName, DynamicKeyw // we aren't expecting a name, we still do this so that the signature of the implementing function remains // the same. ExpressionAst originalInstanceName = instanceName; - if (instanceName is null) + if (instanceName == null) { instanceName = new StringConstantExpressionAst(nameToken.Extent, elementName, StringConstantType.BareWord); } @@ -3845,7 +3845,7 @@ private StatementAst DynamicKeywordStatementRule(Token functionName, DynamicKeyw // // Now look for the body of the data statement. // - if (lCurly is null) + if (lCurly == null) { lCurly = NextToken(); @@ -3857,7 +3857,7 @@ private StatementAst DynamicKeywordStatementRule(Token functionName, DynamicKeyw ParserStrings.MissingBraceInObjectDefinition); // Preserve the name expression for tab completion - return originalInstanceName is null + return originalInstanceName == null ? null : new ErrorStatementAst(ExtentOf(functionName, originalInstanceName), GetNestedErrorAsts(originalInstanceName)); @@ -3908,7 +3908,7 @@ instanceInvokeMemberExpressionAst.Arguments[0] is ScriptBlockExpressionAst && UngetToken(lCurly); // Preserve the name expression for tab completion - return originalInstanceName is null + return originalInstanceName == null ? null : new ErrorStatementAst(ExtentOf(functionName, originalInstanceName), GetNestedErrorAsts(originalInstanceName)); @@ -3951,7 +3951,7 @@ instanceInvokeMemberExpressionAst.Arguments[0] is ScriptBlockExpressionAst && } // commandast // elements: instancename/dynamickeyword/hashtable or scripblockexpress - if (body is null) + if (body == null) { // Failed to read the statement body ReportIncompleteInput(After(lCurly), @@ -3960,7 +3960,7 @@ instanceInvokeMemberExpressionAst.Arguments[0] is ScriptBlockExpressionAst && keywordData.Keyword); // Preserve the name expression for tab completion - return originalInstanceName is null + return originalInstanceName == null ? null : new ErrorStatementAst(ExtentOf(functionName, originalInstanceName), GetNestedErrorAsts(originalInstanceName)); @@ -4048,7 +4048,7 @@ private StatementAst DoWhileStatementRule(LabelToken labelToken, Token doToken) Token whileOrUntilToken = null; PipelineBaseAst condition = null; StatementBlockAst body = StatementBlockRule(); - if (body is null) + if (body == null) { // ErrorRecovery: Skip the keyword and stop trying to parse this statement, continue on whatever // comes next. @@ -4092,7 +4092,7 @@ private StatementAst DoWhileStatementRule(LabelToken labelToken, Token doToken) { SkipNewlines(); condition = PipelineChainRule(); - if (condition is null) + if (condition == null) { // ErrorRecovery: try to get the matching close paren, then return an error statement. @@ -4111,7 +4111,7 @@ private StatementAst DoWhileStatementRule(LabelToken labelToken, Token doToken) UngetToken(rParen); - // If condition is null, we issue an error message already, don't bother with this one. + // If condition == null, we issue an error message already, don't bother with this one. if (condition != null) { endErrorStatement = condition.Extent; @@ -4171,7 +4171,7 @@ private StatementAst ClassDefinitionRule(List customAttributes SkipNewlines(); Token classNameToken; var name = SimpleNameRule(out classNameToken); - if (name is null) + if (name == null) { ReportIncompleteInput(After(classToken), nameof(ParserStrings.MissingNameAfterKeyword), @@ -4203,7 +4203,7 @@ private StatementAst ClassDefinitionRule(List customAttributes while (true) { superClass = this.TypeNameRule(allowAssemblyQualifiedNames: false, firstTypeNameToken: out unused); - if (superClass is null) + if (superClass == null) { ReportIncompleteInput(After(ExtentFromFirstOf(commaToken, colonToken)), nameof(ParserStrings.TypeNameExpected), @@ -4256,7 +4256,7 @@ private StatementAst ClassDefinitionRule(List customAttributes if (astsOnError != null && astsOnError.Count > 0) { - if (nestedAsts is null) + if (nestedAsts == null) { nestedAsts = new List(); } @@ -4285,10 +4285,10 @@ private StatementAst ClassDefinitionRule(List customAttributes ? customAttributes[0].Extent : classToken.Extent; var extent = ExtentOf(startExtent, lastExtent); - var classDefn = new TypeDefinitionAst(extent, name.Value, customAttributes is null ? null : customAttributes.OfType(), members, TypeAttributes.Class, superClassesList); + var classDefn = new TypeDefinitionAst(extent, name.Value, customAttributes == null ? null : customAttributes.OfType(), members, TypeAttributes.Class, superClassesList); if (customAttributes != null && customAttributes.OfType().Any()) { - if (nestedAsts is null) + if (nestedAsts == null) { nestedAsts = new List(); } @@ -4355,7 +4355,7 @@ private MemberAst ClassMemberRule(string className, out List astsOnError) if (attribute != null) { lastAttribute = attribute; - if (startExtent is null) + if (startExtent == null) { startExtent = attribute.Extent; } @@ -4365,7 +4365,7 @@ private MemberAst ClassMemberRule(string className, out List astsOnError) { attributeList.Add(attributeAst); } - else if (typeConstraint is null) + else if (typeConstraint == null) { typeConstraint = (TypeConstraintAst)attribute; } @@ -4378,7 +4378,7 @@ private MemberAst ClassMemberRule(string className, out List astsOnError) } token = PeekToken(); - if (startExtent is null) + if (startExtent == null) { startExtent = token.Extent; } @@ -4535,7 +4535,7 @@ private MemberAst ClassMemberRule(string className, out List astsOnError) SkipToken(); var functionDefinition = MethodDeclarationRule(token, className, staticToken != null) as FunctionDefinitionAst; - if (functionDefinition is null) + if (functionDefinition == null) { // TODO: better error recovery - shouldn't assume this was the last class member Diagnostics.Assert(ErrorList.Count > 0, "Should be an error if we don't have a function"); @@ -4591,12 +4591,12 @@ private bool TryUseTokenAsSimpleName(Token token) private void RecordErrorAsts(Ast errAst, ref List astsOnError) { - if (errAst is null) + if (errAst == null) { return; } - if (astsOnError is null) + if (astsOnError == null) { astsOnError = new List(); } @@ -4606,12 +4606,12 @@ private void RecordErrorAsts(Ast errAst, ref List astsOnError) private void RecordErrorAsts(IEnumerable errAsts, ref List astsOnError) { - if (errAsts is null || !errAsts.Any()) + if (errAsts == null || !errAsts.Any()) { return; } - if (astsOnError is null) + if (astsOnError == null) { astsOnError = new List(); } @@ -4662,7 +4662,7 @@ private StatementAst EnumDefinitionRule(List customAttributes, SkipNewlines(); var name = SimpleNameRule(); - if (name is null) + if (name == null) { ReportIncompleteInput( After(enumToken), @@ -4685,7 +4685,7 @@ private StatementAst EnumDefinitionRule(List customAttributes, ITypeName underlyingType; Token unused; underlyingType = this.TypeNameRule(allowAssemblyQualifiedNames: false, firstTypeNameToken: out unused); - if (underlyingType is null) + if (underlyingType == null) { ReportIncompleteInput( After(colonToken), @@ -4695,7 +4695,7 @@ private StatementAst EnumDefinitionRule(List customAttributes, else { var resolvedType = underlyingType.GetReflectionType(); - if (resolvedType is null || !ValidUnderlyingTypeCodes.HasFlag(resolvedType.GetTypeCode())) + if (resolvedType == null || !ValidUnderlyingTypeCodes.HasFlag(resolvedType.GetTypeCode())) { ReportError( underlyingType.Extent, @@ -4746,7 +4746,7 @@ private StatementAst EnumDefinitionRule(List customAttributes, ? customAttributes[0].Extent : enumToken.Extent; var extent = ExtentOf(startExtent, rCurly); - var enumDefn = new TypeDefinitionAst(extent, name.Value, customAttributes is null ? null : customAttributes.OfType(), members, TypeAttributes.Enum, underlyingTypeConstraint is null ? null : new[] { underlyingTypeConstraint }); + var enumDefn = new TypeDefinitionAst(extent, name.Value, customAttributes == null ? null : customAttributes.OfType(), members, TypeAttributes.Enum, underlyingTypeConstraint == null ? null : new[] { underlyingTypeConstraint }); if (customAttributes != null && customAttributes.OfType().Any()) { // No need to report error since there is error reported in method StatementRule @@ -4778,7 +4778,7 @@ private MemberAst EnumMemberRule() SkipNewlines(); var enumeratorName = SimpleNameRule(); - if (enumeratorName is null) + if (enumeratorName == null) { return null; } @@ -4796,7 +4796,7 @@ private MemberAst EnumMemberRule() { SkipToken(); initialValueAst = ExpressionRule(); - if (initialValueAst is null) + if (initialValueAst == null) { ReportError(After(assignToken), nameof(ParserStrings.ExpectedValueExpression), @@ -4912,7 +4912,7 @@ private StatementAst UsingStatementRule(Token usingToken) } var itemAst = GetCommandArgument(CommandArgumentContext.CommandArgument, itemToken); - if (itemAst is null) + if (itemAst == null) { ReportError(itemToken.Extent, nameof(ParserStrings.InvalidValueForUsingItemName), @@ -4944,7 +4944,7 @@ private StatementAst UsingStatementRule(Token usingToken) } // if htAst is not null, then we don't expect alias - if ((aliasAllowed || aliasRequired) && (htAst is null)) + if ((aliasAllowed || aliasRequired) && (htAst == null)) { var equalsToken = PeekToken(); if (equalsToken.Kind == TokenKind.Equals) @@ -4973,7 +4973,7 @@ private StatementAst UsingStatementRule(Token usingToken) RequireStatementTerminator(); - if (htAst is null) + if (htAst == null) { return new UsingStatementAst( ExtentOf(usingToken, aliasToken), @@ -5001,7 +5001,7 @@ private StatementAst UsingStatementRule(Token usingToken) RequireStatementTerminator(); - if (htAst is null) + if (htAst == null) { return new UsingStatementAst(ExtentOf(usingToken, itemAst), kind, (StringConstantExpressionAst)itemAst); } @@ -5084,7 +5084,7 @@ private StringConstantExpressionAst ResolveUsingAssembly(StringConstantExpressio { } - if (assemblyFileName is null || !File.Exists(assemblyFileName)) + if (assemblyFileName == null || !File.Exists(assemblyFileName)) { ReportError(name.Extent, nameof(ParserStrings.ErrorLoadingAssembly), @@ -5185,7 +5185,7 @@ private StatementAst MethodDeclarationRule(Token functionNameToken, string class SetTokenizerMode(oldTokenizerMode); } - if (baseCtorCallParams is null) + if (baseCtorCallParams == null) { // Assuming implicit default ctor baseCtorCallParams = new List(); @@ -5198,7 +5198,7 @@ private StatementAst MethodDeclarationRule(Token functionNameToken, string class // ErrorRecovery: If there is no opening curly, assume it hasn't been entered yet and don't consume anything. UngetToken(lCurly); - if (endErrorStatement is null) + if (endErrorStatement == null) { endErrorStatement = ExtentFromFirstOf(rParen, functionNameToken); ReportIncompleteInput(After(endErrorStatement), @@ -5310,7 +5310,7 @@ private StatementAst FunctionDeclarationRule(Token functionToken) // ErrorRecovery: If there is no opening curly, assume it hasn't been entered yet and don't consume anything. UngetToken(lCurly); - if (endErrorStatement is null) + if (endErrorStatement == null) { endErrorStatement = ExtentFromFirstOf(rParen, functionNameToken); ReportIncompleteInput(After(endErrorStatement), @@ -5390,7 +5390,7 @@ private StatementAst TrapStatementRule(Token trapToken) SkipNewlines(); AttributeBaseAst type = AttributeRule(); var typeConstraintAst = type as TypeConstraintAst; - if (type != null && typeConstraintAst is null) + if (type != null && typeConstraintAst == null) { // Presumably we parsed an attribute instead of a type. Put it back and let the code // below report a missing trap body. The attribute might belong to something that @@ -5401,7 +5401,7 @@ private StatementAst TrapStatementRule(Token trapToken) } var body = StatementBlockRule(); - if (body is null) + if (body == null) { // ErrorRecovery: just return an error statement. @@ -5450,7 +5450,7 @@ private CatchClauseAst CatchBlockRule(ref IScriptExtent endErrorStatement, ref L SkipNewlines(); AttributeBaseAst type = AttributeRule(); - if (type is null) + if (type == null) { if (commaToken != null) { @@ -5466,7 +5466,7 @@ private CatchClauseAst CatchBlockRule(ref IScriptExtent endErrorStatement, ref L } var typeConstraintAst = type as TypeConstraintAst; - if (typeConstraintAst is null) + if (typeConstraintAst == null) { // Presumably we parsed an attribute instead of a type. Put it back and let the code // below report a missing catch clause body. The attribute might belong to something that @@ -5478,7 +5478,7 @@ private CatchClauseAst CatchBlockRule(ref IScriptExtent endErrorStatement, ref L break; } - if (exceptionTypes is null) + if (exceptionTypes == null) { exceptionTypes = new List(); } @@ -5496,11 +5496,11 @@ private CatchClauseAst CatchBlockRule(ref IScriptExtent endErrorStatement, ref L } StatementBlockAst handler = StatementBlockRule(); - if (handler is null) + if (handler == null) { // Avoid issuing an extra error if we've already issued one, plus the end of the ErrorStatementAst // shouldn't be updated. - if (commaToken is null || endErrorStatement != commaToken.Extent) + if (commaToken == null || endErrorStatement != commaToken.Extent) { // ErrorRecovery: just use the "missing" block in the result ast. @@ -5512,7 +5512,7 @@ private CatchClauseAst CatchBlockRule(ref IScriptExtent endErrorStatement, ref L if (exceptionTypes != null) { - if (errorAsts is null) + if (errorAsts == null) { errorAsts = exceptionTypes; } @@ -5548,7 +5548,7 @@ private StatementAst TryStatementRule(Token tryToken) SkipNewlines(); StatementBlockAst body = StatementBlockRule(); - if (body is null) + if (body == null) { // ErrorRecovery: don't parse more, return an error statement. @@ -5575,7 +5575,7 @@ private StatementAst TryStatementRule(Token tryToken) SkipToken(); finallyBlock = StatementBlockRule(); - if (finallyBlock is null) + if (finallyBlock == null) { // ErrorRecovery: just return null, a null finally block is fine in the resulting ast (but maybe consider // marking the resulting ast as having an error.) @@ -5588,7 +5588,7 @@ private StatementAst TryStatementRule(Token tryToken) } } - if (catches.Count == 0 && finallyBlock is null && endErrorStatement is null) + if (catches.Count == 0 && finallyBlock == null && endErrorStatement == null) { // ErrorRecovery: don't parse more, return an error statement. @@ -5650,12 +5650,12 @@ private StatementAst DataStatementRule(Token dataToken) { SkipNewlines(); ExpressionAst ast = GetSingleCommandArgument(CommandArgumentContext.CommandName); - if (ast is null) + if (ast == null) { // ErrorRecovery: Look for the data statement body. // Only report an error if an error hasn't already been issued. - if (endErrorStatement is null) + if (endErrorStatement == null) { ReportIncompleteInput(After(commaToken ?? supportedCommandToken), nameof(ParserStrings.MissingValueForSupportedCommandInDataSectionStatement), @@ -5680,10 +5680,10 @@ private StatementAst DataStatementRule(Token dataToken) } StatementBlockAst body = null; - if (endErrorStatement is null) + if (endErrorStatement == null) { body = StatementBlockRule(); - if (body is null) + if (body == null) { // ErrorRecovery: return an error statement. @@ -5759,7 +5759,7 @@ private PipelineBaseAst PipelineChainRule() SkipNewlines(); StatementAst statement = StatementRule(); - if (statement is null) + if (statement == null) { // ErrorRecovery: we are very likely at EOF because pretty much anything should result in some // pipeline, so just keep parsing. @@ -5807,9 +5807,9 @@ private PipelineBaseAst PipelineChainRule() nextPipeline = (PipelineAst)PipelineRule(); } - if (nextPipeline is null) + if (nextPipeline == null) { - if (currentChainOperatorToken is null) + if (currentChainOperatorToken == null) { // We haven't seen a chain token, so the caller is responsible // for expecting a pipeline and must manage this @@ -5880,7 +5880,7 @@ private PipelineBaseAst PipelineChainRule() default: // If we haven't seen a chain yet, pass through the pipeline // Simplifies the AST and prevents allocation - if (currentPipelineChain is null) + if (currentPipelineChain == null) { if (!background) { @@ -5901,7 +5901,7 @@ private PipelineBaseAst PipelineChainRule() } // Assemble the new chain statement AST - currentPipelineChain = currentPipelineChain is null + currentPipelineChain = currentPipelineChain == null ? (ChainableAst)nextPipeline : new PipelineChainAst( ExtentOf(currentPipelineChain.Extent, nextPipeline.Extent), @@ -5951,7 +5951,7 @@ private PipelineBaseAst PipelineRule( { CommandBaseAst commandAst; - if (expr is null) + if (expr == null) { // Look for an expression at the beginning of a pipeline var oldTokenizerMode = _tokenizer.Mode; @@ -5984,7 +5984,7 @@ private PipelineBaseAst PipelineRule( { SkipToken(); - if (redirections is null) + if (redirections == null) { redirections = new RedirectionAst[CommandBaseAst.MaxRedirections]; } @@ -6008,7 +6008,7 @@ private PipelineBaseAst PipelineRule( if (commandAst != null) { - if (startExtent is null) + if (startExtent == null) { startExtent = commandAst.Extent; } @@ -6122,7 +6122,7 @@ private RedirectionAst RedirectionRule(RedirectionToken redirectionToken, Redire { // get location var filename = GetSingleCommandArgument(CommandArgumentContext.FileName); - if (filename is null) + if (filename == null) { // ErrorRecovery: Just pretend we have a filename and continue parsing. @@ -6132,7 +6132,7 @@ private RedirectionAst RedirectionRule(RedirectionToken redirectionToken, Redire filename = new ErrorExpressionAst(redirectionToken.Extent); } - if (fileRedirectionToken is null) + if (fileRedirectionToken == null) { // Must be an input redirection ReportError(redirectionToken.Extent, @@ -6177,7 +6177,7 @@ private RedirectionAst RedirectionRule(RedirectionToken redirectionToken, Redire result = new MergingRedirectionAst(mergingRedirectionToken.Extent, mergingRedirectionToken.FromStream, toStream); } - if (redirections[(int)result.FromStream] is null) + if (redirections[(int)result.FromStream] == null) { redirections[(int)result.FromStream] = result; } @@ -6266,7 +6266,7 @@ private ExpressionAst GetCommandArgument(CommandArgumentContext context, Token t // If we haven't seen an argument, the caller must issue an error. If we've seen at least one // argument, then we will issue the error and return back the arguments seen so far. - if (commaToken is null) + if (commaToken == null) { return null; } @@ -6364,7 +6364,7 @@ private ExpressionAst GetCommandArgument(CommandArgumentContext context, Token t } commaToken = token; - if (commandArgs is null) + if (commandArgs == null) { commandArgs = new List(); } @@ -6507,7 +6507,7 @@ internal Ast CommandRule(bool forDynamicKeyword) if (parameterToken.UsedColon && PeekToken().Kind != TokenKind.Comma) { parameterArgs = GetCommandArgument(CommandArgumentContext.CommandArgument, NextToken()); - if (parameterArgs is null) + if (parameterArgs == null) { extent = parameterToken.Extent; ReportError(After(extent), @@ -6535,7 +6535,7 @@ internal Ast CommandRule(bool forDynamicKeyword) case TokenKind.RedirectInStd: if ((context & CommandArgumentContext.CommandName) == 0) { - if (redirections is null) + if (redirections == null) { redirections = new RedirectionAst[CommandBaseAst.MaxRedirections]; } @@ -6662,7 +6662,7 @@ private ExpressionAst ExpressionRule(bool endNumberOnTernaryOpChars = false) SetTokenizerMode(TokenizerMode.Expression); ExpressionAst condition = BinaryExpressionRule(endNumberOnTernaryOpChars); - if (condition is null) + if (condition == null) { return null; } @@ -6679,7 +6679,7 @@ private ExpressionAst ExpressionRule(bool endNumberOnTernaryOpChars = false) // We have seen the ternary operator '?' and now expecting the 'IfFalse' expression. ExpressionAst ifTrue = ExpressionRule(endNumberOnTernaryOpChars: true); - if (ifTrue is null) + if (ifTrue == null) { // ErrorRecovery: create an error expression to fill out the ast and keep parsing. IScriptExtent extent = After(token); @@ -6718,7 +6718,7 @@ private ExpressionAst ExpressionRule(bool endNumberOnTernaryOpChars = false) SkipNewlines(); ExpressionAst ifFalse = ExpressionRule(endNumberOnTernaryOpChars: true); - if (ifFalse is null) + if (ifFalse == null) { // ErrorRecovery: create an error expression to fill out the ast and keep parsing. IScriptExtent extent = After(token); @@ -6794,7 +6794,7 @@ private ExpressionAst BinaryExpressionRule(bool endNumberOnTernaryOpChars = fals ExpressionAst lhs, rhs; ExpressionAst expr = ArrayLiteralRule(endNumberOnTernaryOpChars); - if (expr is null) + if (expr == null) { return null; } @@ -6831,7 +6831,7 @@ private ExpressionAst BinaryExpressionRule(bool endNumberOnTernaryOpChars = fals // We have seen a binary operator token and now expecting the right-hand-side expression. expr = ArrayLiteralRule(endNumberOnTernaryOpChars: true); - if (expr is null) + if (expr == null) { // ErrorRecovery: create an error expression to fill out the ast and keep parsing. IScriptExtent extent = After(token); @@ -6928,7 +6928,7 @@ private ExpressionAst ArrayLiteralRule(bool endNumberOnTernaryOpChars = false) // G unary-expression // G unary-expression ',' new-lines:opt array-literal-expression ExpressionAst lastExpr = UnaryExpressionRule(endNumberOnTernaryOpChars); - if (lastExpr is null) + if (lastExpr == null) { return null; } @@ -6950,7 +6950,7 @@ private ExpressionAst ArrayLiteralRule(bool endNumberOnTernaryOpChars = false) // We have seen a comma token and now expecting an expression as an array element. lastExpr = UnaryExpressionRule(endNumberOnTernaryOpChars: true); - if (lastExpr is null) + if (lastExpr == null) { // ErrorRecovery: create an error expression for the ast and break. ReportIncompleteInput(After(commaToken), @@ -7082,7 +7082,7 @@ private ExpressionAst UnaryExpressionRule(bool endNumberOnTernaryOpChars = false { // Possibly a type literal or attribute. var attributes = AttributeListRule(true); - if (attributes is null) + if (attributes == null) { return null; } @@ -7094,7 +7094,7 @@ private ExpressionAst UnaryExpressionRule(bool endNumberOnTernaryOpChars = false // We are now expecting a child expression. child = UnaryExpressionRule(endNumberOnTernaryOpChars: true); - if (child is null) + if (child == null) { // ErrorRecovery: We have a list of attributes, and we know it's not before a param statement, // so we know we must have some sort of expression. Return an error expression then. @@ -7112,7 +7112,7 @@ private ExpressionAst UnaryExpressionRule(bool endNumberOnTernaryOpChars = false else { Diagnostics.Assert( - _ungotToken is null || ErrorList.Count > 0, + _ungotToken == null || ErrorList.Count > 0, "Unexpected lookahead from AttributeListRule."); // If we've looked ahead, don't go looking for a member access token, we've already issued an error, @@ -7140,7 +7140,7 @@ private ExpressionAst UnaryExpressionRule(bool endNumberOnTernaryOpChars = false } } - if (expr is null) + if (expr == null) { expr = new TypeExpressionAst(lastAttribute.Extent, lastAttribute.TypeName); } @@ -7308,7 +7308,7 @@ private ExpressionAst HashExpressionRule(Token atCurlyToken, bool parsingSchemaE while (true) { KeyValuePair pair = GetKeyValuePair(parsingSchemaElement); - if (pair is null) + if (pair == null) { break; } @@ -7368,7 +7368,7 @@ private KeyValuePair GetKeyValuePair(bool parsingSchemaElement) { SetTokenizerMode(TokenizerMode.Expression); key = LabelOrKeyRule(); - if (key is null) + if (key == null) { return null; } @@ -7412,7 +7412,7 @@ private KeyValuePair GetKeyValuePair(bool parsingSchemaElement) SkipNewlines(); statement = StatementRule(); - if (statement is null) + if (statement == null) { // ErrorRecovery: pretend we saw a statement and keep parsing. @@ -7539,7 +7539,7 @@ private ExpressionAst ParenthesizedExpressionRule(Token lParen) SkipNewlines(); pipelineAst = PipelineChainRule(); - if (pipelineAst is null) + if (pipelineAst == null) { IScriptExtent errorPosition = After(lParen); ReportIncompleteInput( @@ -7678,7 +7678,7 @@ private ExpressionAst MemberAccessRule(ExpressionAst targetExpr, Token operatorT CommandElementAst member = MemberNameRule(); - if (member is null) + if (member == null) { // ErrorRecovery: pretend we saw a property name, don't bother looking for an invocation, // and keep parsing. @@ -7770,7 +7770,7 @@ private List InvokeParamParenListRule(Token lParen, out IScriptEx { SkipNewlines(); ExpressionAst argument = ExpressionRule(); - if (argument is null) + if (argument == null) { if (comma != null) { @@ -7831,7 +7831,7 @@ private ExpressionAst ElementAccessRule(ExpressionAst primaryExpression, Token l SkipNewlines(); ExpressionAst indexExpr = ExpressionRule(); - if (indexExpr is null) + if (indexExpr == null) { // ErrorRecovery: hope we see a closing bracket. If we don't, we'll pretend we saw // the closing bracket, but build an expression that can't compile. diff --git a/src/System.Management.Automation/engine/parser/Position.cs b/src/System.Management.Automation/engine/parser/Position.cs index 91a284d4c71..e9f273fed14 100644 --- a/src/System.Management.Automation/engine/parser/Position.cs +++ b/src/System.Management.Automation/engine/parser/Position.cs @@ -572,7 +572,7 @@ internal sealed class EmptyScriptExtent : IScriptExtent public override bool Equals(object obj) { IScriptExtent otherPosition = obj as IScriptExtent; - if (otherPosition is null) + if (otherPosition == null) { return false; } diff --git a/src/System.Management.Automation/engine/parser/SafeValues.cs b/src/System.Management.Automation/engine/parser/SafeValues.cs index 7a0ddffbeba..37320de83d1 100644 --- a/src/System.Management.Automation/engine/parser/SafeValues.cs +++ b/src/System.Management.Automation/engine/parser/SafeValues.cs @@ -184,7 +184,7 @@ public object VisitStatementBlock(StatementBlockAst statementBlockAst) foreach (var statement in statementBlockAst.Statements) { _visitCount++; - if (statement is null) + if (statement == null) { isSafe = false; break; @@ -237,7 +237,7 @@ public object VisitUnaryExpression(UnaryExpressionAst unaryExpressionAst) public object VisitConvertExpression(ConvertExpressionAst convertExpressionAst) { var type = convertExpressionAst.Type.TypeName.GetReflectionType(); - if (type is null) + if (type == null) { return false; } @@ -528,7 +528,7 @@ public object VisitIndexExpression(IndexExpressionAst indexExpressionAst) // Get the value of the index and value and call the compiler var index = indexExpressionAst.Index.Accept(this); var target = indexExpressionAst.Target.Accept(this); - if (index is null || target is null) + if (index == null || target == null) { throw new ArgumentNullException(nameof(indexExpressionAst)); } @@ -546,7 +546,7 @@ public object VisitExpandableStringExpression(ExpandableStringExpressionAst expa ofs = t_context.SessionState.PSVariable.GetValue("OFS") as string; } - if (ofs is null) + if (ofs == null) { ofs = " "; } @@ -651,7 +651,7 @@ public object VisitPipeline(PipelineAst pipelineAst) public object VisitTernaryExpression(TernaryExpressionAst ternaryExpressionAst) { - if (t_context is null) + if (t_context == null) { throw PSTraceSource.NewArgumentException(nameof(ternaryExpressionAst)); } @@ -669,7 +669,7 @@ public object VisitBinaryExpression(BinaryExpressionAst binaryExpressionAst) public object VisitUnaryExpression(UnaryExpressionAst unaryExpressionAst) { - if (t_context is null) + if (t_context == null) { throw PSTraceSource.NewArgumentException(nameof(unaryExpressionAst)); } @@ -681,7 +681,7 @@ public object VisitConvertExpression(ConvertExpressionAst convertExpressionAst) { // at this point, we know we're safe because we checked both the type and the child, // so now we can just call the compiler and indicate that it's trusted (at this point) - if (t_context is null) + if (t_context == null) { throw PSTraceSource.NewArgumentException(nameof(convertExpressionAst)); } @@ -731,7 +731,7 @@ public object VisitVariableExpression(VariableExpressionAst variableExpressionAs if (name.Equals(SpecialVariables.PSScriptRoot, StringComparison.OrdinalIgnoreCase)) { var scriptFileName = variableExpressionAst.Extent.File; - if (scriptFileName is null) + if (scriptFileName == null) return null; return Path.GetDirectoryName(scriptFileName); diff --git a/src/System.Management.Automation/engine/parser/SemanticChecks.cs b/src/System.Management.Automation/engine/parser/SemanticChecks.cs index 1e87ff9e3d4..f681a30d070 100644 --- a/src/System.Management.Automation/engine/parser/SemanticChecks.cs +++ b/src/System.Management.Automation/engine/parser/SemanticChecks.cs @@ -53,7 +53,7 @@ private SemanticChecks(Parser parser) private bool AnalyzingStaticMember() { MemberAst currentMember; - if (_memberScopeStack.Count == 0 || (currentMember = _memberScopeStack.Peek()) is null) + if (_memberScopeStack.Count == 0 || (currentMember = _memberScopeStack.Peek()) == null) { return false; } @@ -175,7 +175,7 @@ public override AstVisitAction VisitAttribute(AttributeAst attributeAst) if (checkingAttributeOnClass) { var attributeType = attributeAst.TypeName.GetReflectionAttributeType(); - if (attributeType is null) + if (attributeType == null) { Diagnostics.Assert(_parser.ErrorList.Count > 0, "Symbol resolve should have reported error already"); } @@ -212,7 +212,7 @@ public override AstVisitAction VisitAttribute(AttributeAst attributeAst) var propertyInfo = members[0] as PropertyInfo; if (propertyInfo != null) { - if (propertyInfo.GetSetMethod() is null) + if (propertyInfo.GetSetMethod() == null) { _parser.ReportError(namedArg.Extent, nameof(ExtendedTypeSystem.ReadOnlyProperty), @@ -552,14 +552,14 @@ public override AstVisitAction VisitTryStatement(TryStatementAst tryStatementAst { Type type1 = typeLiteral1.TypeName.GetReflectionType(); // If the type can't be resolved yet, there isn't much we can do, so skip it. - if (type1 is null) + if (type1 == null) continue; foreach (TypeConstraintAst typeLiteral2 in block2.CatchTypes) { Type type2 = typeLiteral2.TypeName.GetReflectionType(); // If the type can't be resolved yet, there isn't much we can do, so skip it. - if (type2 is null) + if (type2 == null) continue; if (type1 == type2 || type2.IsSubclassOf(type1)) @@ -663,7 +663,7 @@ private static string GetLabel(ExpressionAst expr) { // We only return null from this method if the label is unknown. If no label is specified, // we just use the empty string. - if (expr is null) + if (expr == null) { return string.Empty; } @@ -693,7 +693,7 @@ public override AstVisitAction VisitContinueStatement(ContinueStatementAst conti private void CheckForReturnStatement(ReturnStatementAst ast) { var functionMemberAst = _memberScopeStack.Peek() as FunctionMemberAst; - if (functionMemberAst is null) + if (functionMemberAst == null) { return; } @@ -752,7 +752,7 @@ private void CheckAssignmentTarget(ExpressionAst ast, bool simpleAssignment, Act if (parenExpressionAst != null) { ExpressionAst expr = parenExpressionAst.Pipeline.GetPureExpression(); - if (expr is null) + if (expr == null) { errorAst = parenExpressionAst.Pipeline; } @@ -1190,7 +1190,7 @@ private void CheckMemberAccess(MemberExpressionAst ast) TypeExpressionAst typeExpression = ast.Expression as TypeExpressionAst; // If this is static access on a variable, it may be suspicious - if (ast.Static && (typeExpression is null)) + if (ast.Static && (typeExpression == null)) { MarkAstParentsAsSuspicious(ast); } @@ -1214,7 +1214,7 @@ private void MarkAstParentsAsSuspicious(Ast ast) public override AstVisitAction VisitScriptBlock(ScriptBlockAst scriptBlockAst) { _scopeStack.Push(scriptBlockAst); - if (scriptBlockAst.Parent is null || scriptBlockAst.Parent is ScriptBlockExpressionAst || !(scriptBlockAst.Parent.Parent is FunctionMemberAst)) + if (scriptBlockAst.Parent == null || scriptBlockAst.Parent is ScriptBlockExpressionAst || !(scriptBlockAst.Parent.Parent is FunctionMemberAst)) { _memberScopeStack.Push(null); } @@ -1267,7 +1267,7 @@ public override AstVisitAction VisitScriptBlockExpression(ScriptBlockExpressionA var commandAst = pipelineAst.PipelineElements[0] as CommandAst; if (commandAst != null && commandAst.CommandElements.Count <= 2 && - commandAst.DefiningKeyword is null) + commandAst.DefiningKeyword == null) { // Here indicates a CommandAst followed by a ScriptBlockExpression, // which is invalid if the DSC resource is not defined @@ -1330,7 +1330,7 @@ public override AstVisitAction VisitConfigurationDefinition(ConfigurationDefinit } } - // ToRemove: No need to continue the parsing if there is no EndBlock, check if (configBody.EndBlock is null) + // ToRemove: No need to continue the parsing if there is no EndBlock, check if (configBody.EndBlock == null) } return AstVisitAction.Continue; @@ -1369,7 +1369,7 @@ public override AstVisitAction VisitDynamicKeywordStatement(DynamicKeywordStatem foreach (var keyValueTuple in hashtable.KeyValuePairs) { var propName = keyValueTuple.Item1 as StringConstantExpressionAst; - if (propName is null) + if (propName == null) { _parser.ReportError(keyValueTuple.Item1.Extent, nameof(ParserStrings.ConfigurationInvalidPropertyName), @@ -1446,7 +1446,7 @@ public void PostVisit(Ast ast) var scriptBlockAst = ast as ScriptBlockAst; if (scriptBlockAst != null) { - if (scriptBlockAst.Parent is null || scriptBlockAst.Parent is ScriptBlockExpressionAst || !(scriptBlockAst.Parent.Parent is FunctionMemberAst)) + if (scriptBlockAst.Parent == null || scriptBlockAst.Parent is ScriptBlockExpressionAst || !(scriptBlockAst.Parent.Parent is FunctionMemberAst)) { _memberScopeStack.Pop(); } @@ -1571,7 +1571,7 @@ internal static void CheckType(Parser parser, TypeDefinitionAst typeDefinitionAs /// Flag to indicate if the class contains Key property. private static void LookupRequiredMembers(Parser parser, TypeDefinitionAst typeDefinitionAst, ref bool hasSet, ref bool hasGet, ref bool hasTest, ref bool hasKey) { - if (typeDefinitionAst is null) + if (typeDefinitionAst == null) { return; } @@ -1584,13 +1584,13 @@ private static void LookupRequiredMembers(Parser parser, TypeDefinitionAst typeD foreach (var baseType in typeDefinitionAst.BaseTypes) { var baseTypeName = baseType.TypeName as TypeName; - if (baseTypeName is null) + if (baseTypeName == null) { continue; } TypeDefinitionAst baseTypeDefinitionAst = baseTypeName._typeDefinitionAst; - if (baseTypeDefinitionAst is null || !baseTypeDefinitionAst.IsClass) + if (baseTypeDefinitionAst == null || !baseTypeDefinitionAst.IsClass) { continue; } @@ -1641,7 +1641,7 @@ private static void CheckGet(Parser parser, FunctionMemberAst functionMemberAst, var typeName = (arrayTypeName != null ? arrayTypeName.ElementType : functionMemberAst.ReturnType.TypeName) as TypeName; - if (typeName is null || typeName._typeDefinitionAst != functionMemberAst.Parent) + if (typeName == null || typeName._typeDefinitionAst != functionMemberAst.Parent) { parser.ReportError(functionMemberAst.Extent, nameof(ParserStrings.DscResourceInvalidGetMethod), @@ -1868,7 +1868,7 @@ private void CheckTypeName(Ast ast, ITypeName typename) // Int16, UInt16, Int32, UInt32, Int64, UInt64, Single, Double, Decimal, DateTime, String // We reject anything with a typecode or element typecode of object... // If we couldn't resolve the type, then it's definitely an error. - if (type is null || ((type.IsArray ? type.GetElementType() : type).GetTypeCode() == TypeCode.Object)) + if (type == null || ((type.IsArray ? type.GetElementType() : type).GetTypeCode() == TypeCode.Object)) { ReportError(ast, nameof(ParserStrings.TypeNotAllowedInDataSection), @@ -2096,11 +2096,11 @@ public override AstVisitAction VisitCommand(CommandAst commandAst) return AstVisitAction.Continue; } - if (_allowedCommands is null) + if (_allowedCommands == null) return AstVisitAction.Continue; string commandName = commandAst.GetCommandName(); - if (commandName is null) + if (commandName == null) { if (commandAst.InvocationOperator == TokenKind.Ampersand) { diff --git a/src/System.Management.Automation/engine/parser/SymbolResolver.cs b/src/System.Management.Automation/engine/parser/SymbolResolver.cs index 02e1e05af2a..42091ba2e7b 100644 --- a/src/System.Management.Automation/engine/parser/SymbolResolver.cs +++ b/src/System.Management.Automation/engine/parser/SymbolResolver.cs @@ -289,7 +289,7 @@ private static PowerShell UsingStatementResolvePowerShell get { // The goal is to re-use runspaces, because creating runspace is an expensive part in creating PowerShell instance. - if (t_usingStatementResolvePowerShell is null) + if (t_usingStatementResolvePowerShell == null) { if (Runspace.DefaultRunspace != null) { @@ -326,7 +326,7 @@ private SymbolResolver(Parser parser, TypeResolutionState typeResolutionState) internal static void ResolveSymbols(Parser parser, ScriptBlockAst scriptBlockAst) { - Diagnostics.Assert(scriptBlockAst.Parent is null, "Can only resolve starting from the root"); + Diagnostics.Assert(scriptBlockAst.Parent == null, "Can only resolve starting from the root"); var usingState = scriptBlockAst.UsingStatements.Count > 0 ? new TypeResolutionState(TypeOps.GetNamespacesForTypeResolutionState(scriptBlockAst.UsingStatements), TypeResolutionState.emptyAssemblies) @@ -381,7 +381,7 @@ public override AstVisitAction VisitAssignmentStatement(AssignmentStatementAst a { var expression = expressionAst; var variableExpressionAst = expression as VariableExpressionAst; - while (variableExpressionAst is null && expression != null) + while (variableExpressionAst == null && expression != null) { var convertExpressionAst = expression as ConvertExpressionAst; if (convertExpressionAst != null) @@ -659,7 +659,7 @@ private bool VisitTypeName(TypeName typeName, int genericArgumentCount, bool isA : _typeResolutionState; var type = TypeResolver.ResolveTypeNameWithContext(typeName, out e, null, trs); - if (type is null) + if (type == null) { if (_symbolTable.GetCurrentTypeDefinitionAst() != null) { diff --git a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs index 0c544713ec6..77efa843f28 100644 --- a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs +++ b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs @@ -207,9 +207,9 @@ internal IList GetMembersByInferredType(PSTypeName typename, bool isStat internal void AddMembersByInferredTypesClrType(PSTypeName typename, bool isStatic, Func filter, Func filterToCall, List results) { - if (CurrentTypeDefinitionAst is null || CurrentTypeDefinitionAst.Type != typename.Type) + if (CurrentTypeDefinitionAst == null || CurrentTypeDefinitionAst.Type != typename.Type) { - if (filterToCall is null) + if (filterToCall == null) { filterToCall = o => !IsMemberHidden(o); } @@ -277,7 +277,7 @@ internal void AddMembersByInferredTypeDefinitionAst( { if (CurrentTypeDefinitionAst != typename.TypeDefinitionAst) { - if (filterToCall is null) + if (filterToCall == null) { filterToCall = o => !IsMemberHidden(o); } @@ -317,7 +317,7 @@ internal void AddMembersByInferredTypeDefinitionAst( foreach (var baseType in typename.TypeDefinitionAst.BaseTypes) { var baseTypeName = baseType.TypeName as TypeName; - if (baseTypeName is null) + if (baseTypeName == null) { continue; } @@ -330,7 +330,7 @@ internal void AddMembersByInferredTypeDefinitionAst( if (isStatic) { // Don't add base class constructors - if (filter is null) + if (filter == null) { filterToCall = o => !IsConstructor(o); } @@ -378,7 +378,7 @@ internal void AddMembersByInferredTypeCimType(PSTypeName typename, List foreach (var cimClass in cimClasses) { - if (filterToCall is null) + if (filterToCall == null) { results.AddRange(cimClass.CimClassProperties); } @@ -429,7 +429,7 @@ internal static bool ParseCimCommandsTypeName(PSTypeName typename, out string ci { cimNamespace = null; className = null; - if (typename is null) + if (typename == null) { return false; } @@ -567,7 +567,7 @@ object ICustomAstVisitor.VisitHashtable(HashtableAst hashtableAst) break; default: typeName = InferTypes(kv.Item2).FirstOrDefault()?.Name; - if (typeName is null) + if (typeName == null) { if (SafeExprEvaluator.TrySafeEval(expression, _context.ExecutionContext, out object safeValue)) { @@ -986,7 +986,7 @@ private void InferTypesFrom(CommandAst commandAst, List inferredType PseudoBindingInfo pseudoBinding = new PseudoParameterBinder() .DoPseudoParameterBinding(commandAst, null, null, PseudoParameterBinder.BindingType.ParameterCompletion); - if (pseudoBinding?.CommandInfo is null) + if (pseudoBinding?.CommandInfo == null) { return; } @@ -1122,7 +1122,7 @@ private void InferTypesFromForeachCommand(PseudoBindingInfo pseudoBinding, Comma if (pseudoBinding.BoundArguments.TryGetValue("MemberName", out AstParameterArgumentPair argument)) { var previousPipelineElement = GetPreviousPipelineCommand(commandAst); - if (previousPipelineElement is null) + if (previousPipelineElement == null) { return; } @@ -1190,7 +1190,7 @@ private void InferTypesFromGroupCommand(PseudoBindingInfo pseudoBinding, Command bool IsInPropertyArgument(object o) { - if (properties is null) + if (properties == null) { return true; } @@ -1305,7 +1305,7 @@ void InferFromSelectProperties(AstParameterArgumentPair astParameterArgumentPair break; } - if (properties is null) + if (properties == null) { return; } @@ -1356,7 +1356,7 @@ bool IsInPropertyArgument(object o) } var previousPipelineElement = GetPreviousPipelineCommand(commandAst); - if (previousPipelineElement is null) + if (previousPipelineElement == null) { return; } @@ -1485,13 +1485,13 @@ private IEnumerable InferTypesFrom(MemberExpressionAst memberExpress // If the member name isn't simple, don't even try. var memberAsStringConst = memberCommandElement as StringConstantExpressionAst; - if (memberAsStringConst is null) + if (memberAsStringConst == null) { return Array.Empty(); } var exprType = GetExpressionType(expression, isStatic); - if (exprType is null || exprType.Length == 0) + if (exprType == null || exprType.Length == 0) { return Array.Empty(); } @@ -1729,16 +1729,16 @@ private PSTypeName[] GetExpressionType(ExpressionAst expression, bool isStatic) if (isStatic) { var exprAsType = expression as TypeExpressionAst; - if (exprAsType is null) + if (exprAsType == null) { return null; } var type = exprAsType.TypeName.GetReflectionType(); - if (type is null) + if (type == null) { var typeName = exprAsType.TypeName as TypeName; - if (typeName?._typeDefinitionAst is null) + if (typeName?._typeDefinitionAst == null) { return null; } @@ -1890,7 +1890,7 @@ private void InferTypeFrom(VariableExpressionAst variableExpressionAst, List inferredTypes) PSTypeName foundType = null; foreach (PSTypeName inferredType in inferredTypes) { - if (inferredType.Type is null) + if (inferredType.Type == null) { return new PSTypeName(typeof(object[])); } @@ -2043,7 +2043,7 @@ private PSTypeName GetArrayType(IEnumerable inferredTypes) break; } - if (foundType is null) + if (foundType == null) { foundType = inferredType; continue; @@ -2056,7 +2056,7 @@ private PSTypeName GetArrayType(IEnumerable inferredTypes) } } - if (foundType is null) + if (foundType == null) { return new PSTypeName(typeof(object[])); } @@ -2265,14 +2265,14 @@ private IEnumerable GetInferredEnumeratedTypes(IEnumerable(); } @@ -249,7 +249,7 @@ private static Type CallResolveTypeNameWorkerHelper(TypeName typeName, var currentScope = context != null ? context.EngineSessionState.CurrentScope : null; Type result = ResolveTypeNameWorker(typeName, currentScope, typeResolutionState.assemblies, t_searchedAssemblies, typeResolutionState, /*onlySearchInGivenAssemblies*/ false, /* reportAmbiguousException */ true, out exception); - if (exception is null && result is null) + if (exception == null && result == null) { if (context != null && !isAssembliesExplicitlyPassedIn) { @@ -260,7 +260,7 @@ private static Type CallResolveTypeNameWorkerHelper(TypeName typeName, /*onlySearchInGivenAssemblies*/ true, /* reportAmbiguousException */ false, out exception); } - if (result is null) + if (result == null) { // Search from the assembly list passed in. result = ResolveTypeNameWorker(typeName, currentScope, assemblies, t_searchedAssemblies, typeResolutionState, @@ -309,7 +309,7 @@ internal static Type ResolveTypeNameWithContext(TypeName typeName, out Exception ExecutionContext context = null; exception = null; - if (typeResolutionState is null) + if (typeResolutionState == null) { // Usings from script scope (and if no script scope, fall back to default 'using namespace system') context = LocalPipeline.GetExecutionContextFromTLS(); @@ -370,7 +370,7 @@ internal static Type ResolveTypeNameWithContext(TypeName typeName, out Exception return typeName._typeDefinitionAst.Type; } - if (context is null) + if (context == null) { context = LocalPipeline.GetExecutionContextFromTLS(); } @@ -388,7 +388,7 @@ internal static Type ResolveTypeNameWithContext(TypeName typeName, out Exception return result; } - if (exception is null) + if (exception == null) { foreach (var ns in typeResolutionState.namespaces) { @@ -413,7 +413,7 @@ internal static Type ResolveTypeNameWithContext(TypeName typeName, out Exception if (newResult != null) { - if (result is null) + if (result == null) { result = newResult; } @@ -463,7 +463,7 @@ internal static Type ResolveITypeName(ITypeName iTypeName, out Exception excepti { exception = null; var typeName = iTypeName as TypeName; - if (typeName is null) + if (typeName == null) { // The type is something more complicated - generic or array. try @@ -495,7 +495,7 @@ internal static Type ResolveType(string strTypeName, out Exception exception) } var iTypeName = Parser.ScanType(strTypeName, ignoreErrors: false); - if (iTypeName is null) + if (iTypeName == null) { return null; } @@ -582,7 +582,7 @@ private TypeResolutionState(TypeResolutionState other, HashSet typesDefi internal static TypeResolutionState GetDefaultUsingState(ExecutionContext context) { - if (context is null) + if (context == null) { context = LocalPipeline.GetExecutionContextFromTLS(); } @@ -617,7 +617,7 @@ public override bool Equals(object obj) var other = obj as TypeResolutionState; - if (other is null) + if (other == null) return false; if (this.attribute != other.attribute) @@ -891,7 +891,7 @@ internal static string FindBuiltinAccelerator(Type type, string expectedKey = nu { // Taking attributes as special case. In this case, we only want to return the // accelerator. - if (expectedKey is null || typeof(Attribute).IsAssignableFrom(type)) + if (expectedKey == null || typeof(Attribute).IsAssignableFrom(type)) { foreach (KeyValuePair entry in builtinTypeAccelerators) { @@ -958,7 +958,7 @@ public static Dictionary Get { get { - if (s_allTypeAccelerators is null) + if (s_allTypeAccelerators == null) { s_allTypeAccelerators = new Dictionary(StringComparer.OrdinalIgnoreCase); FillCache(s_allTypeAccelerators); diff --git a/src/System.Management.Automation/engine/parser/VariableAnalysis.cs b/src/System.Management.Automation/engine/parser/VariableAnalysis.cs index 7b1ff901f5d..052a4d5aa7f 100644 --- a/src/System.Management.Automation/engine/parser/VariableAnalysis.cs +++ b/src/System.Management.Automation/engine/parser/VariableAnalysis.cs @@ -598,10 +598,10 @@ private Tuple> AnalyzeImpl(IParameterMetadataProvi if (paramAst is TypeConstraintAst) { countConverts += 1; - if (type is null) + if (type == null) { type = paramAst.TypeName.GetReflectionType(); - if (type is null) + if (type == null) { anyUnresolvedTypes = true; } @@ -610,7 +610,7 @@ private Tuple> AnalyzeImpl(IParameterMetadataProvi else { var attrType = paramAst.TypeName.GetReflectionAttributeType(); - if (attrType is null) + if (attrType == null) { anyUnresolvedTypes = true; } @@ -852,7 +852,7 @@ private void CheckLHSAssign(ExpressionAst lhs, BitArray assignedBitArray) if (varPath.IsAnyLocal()) { var varName = GetUnaliasedVariableName(varPath); - if (convertType is null && + if (convertType == null && (varName.Equals(SpecialVariables.@foreach, StringComparison.OrdinalIgnoreCase) || varName.Equals(SpecialVariables.@switch, StringComparison.OrdinalIgnoreCase))) { @@ -891,13 +891,13 @@ private VariableAnalysisDetails CheckLHSAssignVar(string variableName, BitArray } var type = analysisDetails.Type; - if (type is null) + if (type == null) { analysisDetails.Type = convertType ?? typeof(object); } else { - if (!assignedBitArray[analysisDetails.BitIndex] && convertType is null) + if (!assignedBitArray[analysisDetails.BitIndex] && convertType == null) { // The variable has not been assigned in the current flow control path, but has been on some other // path (because the type was already assigned.) Make sure they are compatible by forcing a type comparison. @@ -1027,7 +1027,7 @@ public object VisitIfStatement(IfStatementAst ifStmtAst) { Block afterStmt = new Block(); - if (ifStmtAst.ElseClause is null) + if (ifStmtAst.ElseClause == null) { // There is no else, flow can go straight to afterStmt. _currentBlock.FlowsTo(afterStmt); @@ -1037,7 +1037,7 @@ public object VisitIfStatement(IfStatementAst ifStmtAst) for (int i = 0; i < clauseCount; i++) { var clause = ifStmtAst.Clauses[i]; - bool isLastClause = (i == (clauseCount - 1) && ifStmtAst.ElseClause is null); + bool isLastClause = (i == (clauseCount - 1) && ifStmtAst.ElseClause == null); Block clauseBlock = new Block(); Block nextBlock = isLastClause ? afterStmt : new Block(); @@ -1351,7 +1351,7 @@ public object VisitTryStatement(TryStatementAst tryStatementAst) tryStatementAst.Body.Accept(this); Block lastBlockInTry = _currentBlock; - var finallyFirstBlock = tryStatementAst.Finally is null ? null : new Block(); + var finallyFirstBlock = tryStatementAst.Finally == null ? null : new Block(); Block finallyLastBlock = null; // This is the first block after all the catches and finally (if present). @@ -1432,7 +1432,7 @@ where t.Label.Equals(labelStrAst.Value, StringComparison.OrdinalIgnoreCase) targetBlock = fieldSelector(_loopTargets.Last()); } - if (targetBlock is null) + if (targetBlock == null) { // We need to report an error about bad break statement here _currentBlock.FlowsTo(_exitBlock); @@ -1535,7 +1535,7 @@ public object VisitAssignmentStatement(AssignmentStatementAst assignmentStatemen { convertCount += 1; convertAst = leftAst as ConvertExpressionAst; - if (convertAst is null) + if (convertAst == null) { anyAttributes = true; } @@ -1552,7 +1552,7 @@ public object VisitAssignmentStatement(AssignmentStatementAst assignmentStatemen // We don't handle them at all in the variable analysis. if (anyAttributes || convertCount > 1 || - (convertAst != null && convertAst.Type.TypeName.GetReflectionType() is null)) + (convertAst != null && convertAst.Type.TypeName.GetReflectionType() == null)) { var varPath = ((VariableExpressionAst)leftAst).VariablePath; if (varPath.IsAnyLocal()) diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index e4ad627babc..7baec6102c3 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -93,7 +93,7 @@ public abstract class Ast /// protected Ast(IScriptExtent extent) { - if (extent is null) + if (extent == null) { throw PSTraceSource.NewArgumentNullException(nameof(extent)); } @@ -119,7 +119,7 @@ protected Ast(IScriptExtent extent) /// Returns the value returned by the visitor. public object Visit(ICustomAstVisitor astVisitor) { - if (astVisitor is null) + if (astVisitor == null) { throw PSTraceSource.NewArgumentNullException(nameof(astVisitor)); } @@ -133,7 +133,7 @@ public object Visit(ICustomAstVisitor astVisitor) /// The visitor. public void Visit(AstVisitor astVisitor) { - if (astVisitor is null) + if (astVisitor == null) { throw PSTraceSource.NewArgumentNullException(nameof(astVisitor)); } @@ -149,7 +149,7 @@ public void Visit(AstVisitor astVisitor) /// A possibly empty collection of matching Ast nodes. public IEnumerable FindAll(Func predicate, bool searchNestedScriptBlocks) { - if (predicate is null) + if (predicate == null) { throw PSTraceSource.NewArgumentNullException(nameof(predicate)); } @@ -165,7 +165,7 @@ public IEnumerable FindAll(Func predicate, bool searchNestedScri /// The first matching node, or null if there is no match. public Ast Find(Func predicate, bool searchNestedScriptBlocks) { - if (predicate is null) + if (predicate == null) { throw PSTraceSource.NewArgumentNullException(nameof(predicate)); } @@ -220,7 +220,7 @@ public object SafeGetValue() /// internal static T[] CopyElements(ReadOnlyCollection elements) where T : Ast { - if (elements is null || elements.Count == 0) { return null; } + if (elements == null || elements.Count == 0) { return null; } var result = new T[elements.Count]; for (int i = 0; i < result.Length; i++) @@ -239,7 +239,7 @@ internal static T[] CopyElements(ReadOnlyCollection elements) where T : As /// internal static T CopyElement(T element) where T : Ast { - if (element is null) { return null; } + if (element == null) { return null; } return (T)element.Copy(); } @@ -276,7 +276,7 @@ internal void SetParent(Ast child) throw new InvalidOperationException(ParserStrings.AstIsReused); } - Diagnostics.Assert(child.Parent is null, "Parent can only be set once"); + Diagnostics.Assert(child.Parent == null, "Parent can only be set once"); child.Parent = this; } @@ -449,7 +449,7 @@ internal ErrorStatementAst(IScriptExtent extent, IEnumerable nestedAsts = n internal ErrorStatementAst(IScriptExtent extent, Token kind, IEnumerable nestedAsts = null) : base(extent) { - if (kind is null) + if (kind == null) { throw PSTraceSource.NewArgumentNullException(nameof(kind)); } @@ -465,7 +465,7 @@ internal ErrorStatementAst(IScriptExtent extent, Token kind, IEnumerable ne internal ErrorStatementAst(IScriptExtent extent, Token kind, IEnumerable>> flags, IEnumerable conditions, IEnumerable bodies) : base(extent) { - if (kind is null) + if (kind == null) { throw PSTraceSource.NewArgumentNullException(nameof(kind)); } @@ -538,7 +538,7 @@ internal ErrorStatementAst(IScriptExtent extent, Token kind, IEnumerable public override Ast Copy() { - if (this.Kind is null) + if (this.Kind == null) { var newNestedAst = CopyElements(this.NestedAst); return new ErrorStatementAst(this.Extent, newNestedAst); @@ -594,7 +594,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) { foreach (var tuple in Flags.Values) { - if (tuple.Item2 is null) + if (tuple.Item2 == null) continue; action = tuple.Item2.InternalVisit(visitor); @@ -1023,7 +1023,7 @@ public ScriptBlockAst(IScriptExtent extent, IEnumerable using this.Attributes = s_emptyAttributeList; } - if (statements is null) + if (statements == null) { throw PSTraceSource.NewArgumentNullException(nameof(statements)); } @@ -1481,7 +1481,7 @@ Tuple IParameterMetadataProvider.GetWithInputHandlingForInvokeCo string scriptBlockText = GetWithInputHandlingForInvokeCommandImpl(usingVariablesTuple); string paramText = null; - if (ParamBlock is null) + if (ParamBlock == null) { paramText = "param(" + additionalNewParams + ")" + Environment.NewLine; } @@ -1495,9 +1495,9 @@ private string GetWithInputHandlingForInvokeCommandImpl(Tuple attributes, MethodAttributes methodAttributes) : base(extent) { - if (functionDefinitionAst is null) + if (functionDefinitionAst == null) { throw PSTraceSource.NewArgumentNullException(nameof(functionDefinitionAst)); } @@ -3441,15 +3441,15 @@ Tuple IParameterMetadataProvider.GetWithInputHandlingForInvokeCo #region Internal helpers internal bool IsReturnTypeVoid() { - if (ReturnType is null) + if (ReturnType == null) return true; var typeName = ReturnType.TypeName as TypeName; - return typeName is null ? false : typeName.IsType(typeof(void)); + return typeName == null ? false : typeName.IsType(typeof(void)); } internal Type GetReturnType() { - return ReturnType is null ? typeof(void) : ReturnType.TypeName.GetReflectionType(); + return ReturnType == null ? typeof(void) : ReturnType.TypeName.GetReflectionType(); } #endregion } @@ -3473,7 +3473,7 @@ internal CompilerGeneratedMemberFunctionAst(IScriptExtent extent, TypeDefinition statement = new CommandExpressionAst(extent, invokeMemberAst, null); } - Body = new ScriptBlockAst(extent, null, new StatementBlockAst(extent, statement is null ? null : new[] { statement }, null), false); + Body = new ScriptBlockAst(extent, null, new StatementBlockAst(extent, statement == null ? null : new[] { statement }, null), false); this.SetParent(Body); definingType.SetParent(this); DefiningType = definingType; @@ -3596,7 +3596,7 @@ public FunctionDefinitionAst(IScriptExtent extent, throw PSTraceSource.NewArgumentNullException(nameof(name)); } - if (body is null) + if (body == null) { throw PSTraceSource.NewArgumentNullException(nameof(body)); } @@ -3696,7 +3696,7 @@ public CommentHelpInfo GetHelpContent() /// public CommentHelpInfo GetHelpContent(Dictionary scriptBlockTokenCache) { - if (scriptBlockTokenCache is null) + if (scriptBlockTokenCache == null) { throw new ArgumentNullException(nameof(scriptBlockTokenCache)); } @@ -3842,7 +3842,7 @@ PowerShell IParameterMetadataProvider.GetPowerShell(ExecutionContext context, Di string IParameterMetadataProvider.GetWithInputHandlingForInvokeCommand() { string result = ((IParameterMetadataProvider)Body).GetWithInputHandlingForInvokeCommand(); - return Parameters is null ? result : (GetParamTextFromParameterList() + result); + return Parameters == null ? result : (GetParamTextFromParameterList() + result); } Tuple IParameterMetadataProvider.GetWithInputHandlingForInvokeCommandWithUsingExpression( @@ -3851,7 +3851,7 @@ Tuple IParameterMetadataProvider.GetWithInputHandlingForInvokeCo Tuple result = ((IParameterMetadataProvider)Body).GetWithInputHandlingForInvokeCommandWithUsingExpression(usingVariablesTuple); - if (Parameters is null) + if (Parameters == null) { return result; } @@ -3899,7 +3899,7 @@ public class IfStatementAst : StatementAst public IfStatementAst(IScriptExtent extent, IEnumerable clauses, StatementBlockAst elseClause) : base(extent) { - if (clauses is null || !clauses.Any()) + if (clauses == null || !clauses.Any()) { throw PSTraceSource.NewArgumentException(nameof(clauses)); } @@ -4004,7 +4004,7 @@ public DataStatementAst(IScriptExtent extent, StatementBlockAst body) : base(extent) { - if (body is null) + if (body == null) { throw PSTraceSource.NewArgumentNullException(nameof(body)); } @@ -4146,7 +4146,7 @@ public abstract class LoopStatementAst : LabeledStatementAst protected LoopStatementAst(IScriptExtent extent, string label, PipelineBaseAst condition, StatementBlockAst body) : base(extent, label, condition) { - if (body is null) + if (body == null) { throw PSTraceSource.NewArgumentNullException(nameof(body)); } @@ -4209,9 +4209,9 @@ public ForEachStatementAst(IScriptExtent extent, StatementBlockAst body) : base(extent, label, expression, body) { - if (expression is null || variable is null) + if (expression == null || variable == null) { - throw PSTraceSource.NewArgumentNullException(expression is null ? "expression" : "variablePath"); + throw PSTraceSource.NewArgumentNullException(expression == null ? "expression" : "variablePath"); } this.Flags = flags; @@ -4413,7 +4413,7 @@ public class DoWhileStatementAst : LoopStatementAst public DoWhileStatementAst(IScriptExtent extent, string label, PipelineBaseAst condition, StatementBlockAst body) : base(extent, label, condition, body) { - if (condition is null) + if (condition == null) { throw PSTraceSource.NewArgumentNullException(nameof(condition)); } @@ -4469,7 +4469,7 @@ public class DoUntilStatementAst : LoopStatementAst public DoUntilStatementAst(IScriptExtent extent, string label, PipelineBaseAst condition, StatementBlockAst body) : base(extent, label, condition, body) { - if (condition is null) + if (condition == null) { throw PSTraceSource.NewArgumentNullException(nameof(condition)); } @@ -4525,7 +4525,7 @@ public class WhileStatementAst : LoopStatementAst public WhileStatementAst(IScriptExtent extent, string label, PipelineBaseAst condition, StatementBlockAst body) : base(extent, label, condition, body) { - if (condition is null) + if (condition == null) { throw PSTraceSource.NewArgumentNullException(nameof(condition)); } @@ -4643,7 +4643,7 @@ public SwitchStatementAst(IScriptExtent extent, StatementBlockAst @default) : base(extent, label, condition) { - if ((clauses is null || !clauses.Any()) && @default is null) + if ((clauses == null || !clauses.Any()) && @default == null) { // Must specify either clauses or default. If neither, just complain about clauses as that's the most likely // invalid argument. @@ -4761,7 +4761,7 @@ public class CatchClauseAst : Ast public CatchClauseAst(IScriptExtent extent, IEnumerable catchTypes, StatementBlockAst body) : base(extent) { - if (body is null) + if (body == null) { throw PSTraceSource.NewArgumentNullException(nameof(body)); } @@ -4864,12 +4864,12 @@ public TryStatementAst(IScriptExtent extent, StatementBlockAst @finally) : base(extent) { - if (body is null) + if (body == null) { throw PSTraceSource.NewArgumentNullException(nameof(body)); } - if ((catchClauses is null || !catchClauses.Any()) && @finally is null) + if ((catchClauses == null || !catchClauses.Any()) && @finally == null) { // If no catches and no finally, just complain about catchClauses as that's the most likely invalid argument. throw PSTraceSource.NewArgumentException(nameof(catchClauses)); @@ -4973,7 +4973,7 @@ public class TrapStatementAst : StatementAst public TrapStatementAst(IScriptExtent extent, TypeConstraintAst trapType, StatementBlockAst body) : base(extent) { - if (body is null) + if (body == null) { throw PSTraceSource.NewArgumentNullException(nameof(body)); } @@ -5389,12 +5389,12 @@ public PipelineChainAst( bool background = false) : base(extent) { - if (lhsChain is null) + if (lhsChain == null) { throw new ArgumentNullException(nameof(lhsChain)); } - if (rhsPipeline is null) + if (rhsPipeline == null) { throw new ArgumentNullException(nameof(rhsPipeline)); } @@ -5529,7 +5529,7 @@ public class PipelineAst : ChainableAst public PipelineAst(IScriptExtent extent, IEnumerable pipelineElements, bool background) : base(extent) { - if (pipelineElements is null || !pipelineElements.Any()) + if (pipelineElements == null || !pipelineElements.Any()) { throw PSTraceSource.NewArgumentException(nameof(pipelineElements)); } @@ -5566,7 +5566,7 @@ public PipelineAst(IScriptExtent extent, IEnumerable pipelineEle public PipelineAst(IScriptExtent extent, CommandBaseAst commandAst, bool background) : base(extent) { - if (commandAst is null) + if (commandAst == null) { throw PSTraceSource.NewArgumentNullException(nameof(commandAst)); } @@ -5709,9 +5709,9 @@ public class CommandParameterAst : CommandElementAst public CommandParameterAst(IScriptExtent extent, string parameterName, ExpressionAst argument, IScriptExtent errorPosition) : base(extent) { - if (errorPosition is null || string.IsNullOrEmpty(parameterName)) + if (errorPosition == null || string.IsNullOrEmpty(parameterName)) { - throw PSTraceSource.NewArgumentNullException(errorPosition is null ? "errorPosition" : "parameterName"); + throw PSTraceSource.NewArgumentNullException(errorPosition == null ? "errorPosition" : "parameterName"); } this.ParameterName = parameterName; @@ -5839,7 +5839,7 @@ public CommandAst(IScriptExtent extent, IEnumerable redirections) : base(extent, redirections) { - if (commandElements is null || !commandElements.Any()) + if (commandElements == null || !commandElements.Any()) { throw PSTraceSource.NewArgumentException(nameof(commandElements)); } @@ -5960,7 +5960,7 @@ public CommandExpressionAst(IScriptExtent extent, IEnumerable redirections) : base(extent, redirections) { - if (expression is null) + if (expression == null) { throw PSTraceSource.NewArgumentNullException(nameof(expression)); } @@ -6153,7 +6153,7 @@ public class FileRedirectionAst : RedirectionAst public FileRedirectionAst(IScriptExtent extent, RedirectionStream stream, ExpressionAst file, bool append) : base(extent, stream) { - if (file is null) + if (file == null) { throw PSTraceSource.NewArgumentNullException(nameof(file)); } @@ -6224,9 +6224,9 @@ public class AssignmentStatementAst : PipelineBaseAst public AssignmentStatementAst(IScriptExtent extent, ExpressionAst left, TokenKind @operator, StatementAst right, IScriptExtent errorPosition) : base(extent) { - if (left is null || right is null || errorPosition is null) + if (left == null || right == null || errorPosition == null) { - throw PSTraceSource.NewArgumentNullException(left is null ? "left" : right is null ? "right" : "errorPosition"); + throw PSTraceSource.NewArgumentNullException(left == null ? "left" : right == null ? "right" : "errorPosition"); } if ((@operator.GetTraits() & TokenFlags.AssignmentOperator) == 0) @@ -6370,17 +6370,17 @@ public ConfigurationDefinitionAst(IScriptExtent extent, ConfigurationType type, ExpressionAst instanceName) : base(extent) { - if (extent is null) + if (extent == null) { throw PSTraceSource.NewArgumentNullException(nameof(extent)); } - if (body is null) + if (body == null) { throw PSTraceSource.NewArgumentNullException(nameof(body)); } - if (instanceName is null) + if (instanceName == null) { throw PSTraceSource.NewArgumentNullException(nameof(instanceName)); } @@ -6422,7 +6422,7 @@ public override Ast Copy() { LCurlyToken = this.LCurlyToken, ConfigurationToken = this.ConfigurationToken, - CustomAttributes = this.CustomAttributes is null ? null : this.CustomAttributes.Select(e => (AttributeAst)e.Copy()) + CustomAttributes = this.CustomAttributes == null ? null : this.CustomAttributes.Select(e => (AttributeAst)e.Copy()) }; } @@ -6521,7 +6521,7 @@ internal PipelineAst GenerateSetItemPipelineAst() cea.Add(new CommandParameterAst(PositionUtilities.EmptyExtent, "ResourceModuleTuplesToImport", new ConstantExpressionAst(PositionUtilities.EmptyExtent, resourceModulePairsToImport), PositionUtilities.EmptyExtent)); var scriptBlockBody = new ScriptBlockAst(Body.Extent, - CustomAttributes is null ? null : CustomAttributes.Select(att => (AttributeAst)att.Copy()).ToList(), + CustomAttributes == null ? null : CustomAttributes.Select(att => (AttributeAst)att.Copy()).ToList(), null, new StatementBlockAst(Body.Extent, resourceBody, null), false, false); @@ -6580,7 +6580,7 @@ internal PipelineAst GenerateSetItemPipelineAst() var statmentBlockAst = new StatementBlockAst(this.Extent, funcStatements, null); var funcBody = new ScriptBlockAst(Body.Extent, - CustomAttributes is null ? null : CustomAttributes.Select(att => (AttributeAst)att.Copy()).ToList(), + CustomAttributes == null ? null : CustomAttributes.Select(att => (AttributeAst)att.Copy()).ToList(), paramBlockAst, statmentBlockAst, false, true); var funcBodyExp = new ScriptBlockExpressionAst(this.Extent, funcBody); @@ -6633,7 +6633,7 @@ internal PipelineAst GenerateSetItemPipelineAst() private static bool IsImportCommand(StatementAst stmt, List> resourceModulePairsToImport) { var dkwsAst = stmt as DynamicKeywordStatementAst; - if (dkwsAst is null || !dkwsAst.Keyword.Keyword.Equals("Import-DscResource", StringComparison.OrdinalIgnoreCase)) + if (dkwsAst == null || !dkwsAst.Keyword.Keyword.Equals("Import-DscResource", StringComparison.OrdinalIgnoreCase)) { return false; } @@ -6741,7 +6741,7 @@ private static IEnumerable ConfigurationBuildInParameters { get { - if (s_configurationBuildInParameters is null) + if (s_configurationBuildInParameters == null) { s_configurationBuildInParameters = new List(); @@ -6767,7 +6767,7 @@ private static IEnumerable ConfigurationBuildInParameterAttribAsts { get { - if (s_configurationBuildInParameterAttrAsts is null) + if (s_configurationBuildInParameterAttrAsts == null) { s_configurationBuildInParameterAttrAsts = new List(); @@ -6776,7 +6776,7 @@ private static IEnumerable ConfigurationBuildInParameterAttribAsts var sba = Parser.ParseInput(ConfigurationBuildInParametersStr, out tokens, out errors); if (sba != null) { - if (s_configurationBuildInParameters is null) + if (s_configurationBuildInParameters == null) { s_configurationBuildInParameters = new List(); @@ -6803,7 +6803,7 @@ private static IEnumerable ConfigurationExtraParameterStatements { get { - if (s_configurationExtraParameterStatements is null) + if (s_configurationExtraParameterStatements == null) { s_configurationExtraParameterStatements = new List(); Token[] tokens; @@ -6852,7 +6852,7 @@ public class DynamicKeywordStatementAst : StatementAst public DynamicKeywordStatementAst(IScriptExtent extent, IEnumerable commandElements) : base(extent) { - if (commandElements is null || !commandElements.Any()) + if (commandElements == null || !commandElements.Any()) { throw PSTraceSource.NewArgumentException(nameof(commandElements)); } @@ -7030,7 +7030,7 @@ internal PipelineAst GenerateCommandCallPipelineAst() foreach (var keyValueTuple in hashtable.KeyValuePairs) { var propName = keyValueTuple.Item1 as StringConstantExpressionAst; - if (propName is null) + if (propName == null) { isHashtableValid = false; break; @@ -7208,19 +7208,19 @@ internal virtual bool ShouldPreserveOutputInCaseOfException() var parenExpr = this as ParenExpressionAst; var subExpr = this as SubExpressionAst; - if (parenExpr is null && subExpr is null) + if (parenExpr == null && subExpr == null) { PSTraceSource.NewInvalidOperationException(); } var commandExpr = this.Parent as CommandExpressionAst; - if (commandExpr is null) + if (commandExpr == null) { return false; } var pipelineAst = commandExpr.Parent as PipelineAst; - if (pipelineAst is null || pipelineAst.PipelineElements.Count > 1) + if (pipelineAst == null || pipelineAst.PipelineElements.Count > 1) { return false; } @@ -7365,9 +7365,9 @@ public BinaryExpressionAst(IScriptExtent extent, ExpressionAst left, TokenKind @ throw PSTraceSource.NewArgumentException(nameof(@operator)); } - if (left is null || right is null || errorPosition is null) + if (left == null || right == null || errorPosition == null) { - throw PSTraceSource.NewArgumentNullException(left is null ? "left" : right is null ? "right" : "errorPosition"); + throw PSTraceSource.NewArgumentNullException(left == null ? "left" : right == null ? "right" : "errorPosition"); } this.Left = left; @@ -7478,7 +7478,7 @@ public UnaryExpressionAst(IScriptExtent extent, TokenKind tokenKind, ExpressionA throw PSTraceSource.NewArgumentException(nameof(tokenKind)); } - if (child is null) + if (child == null) { throw PSTraceSource.NewArgumentNullException(nameof(child)); } @@ -7555,9 +7555,9 @@ public class BlockStatementAst : StatementAst public BlockStatementAst(IScriptExtent extent, Token kind, StatementBlockAst body) : base(extent) { - if (kind is null || body is null) + if (kind == null || body == null) { - throw PSTraceSource.NewArgumentNullException(kind is null ? "kind" : "body"); + throw PSTraceSource.NewArgumentNullException(kind == null ? "kind" : "body"); } if (kind.Kind != TokenKind.Sequence && kind.Kind != TokenKind.Parallel) @@ -7629,9 +7629,9 @@ public class AttributedExpressionAst : ExpressionAst, ISupportsAssignment, IAssi public AttributedExpressionAst(IScriptExtent extent, AttributeBaseAst attribute, ExpressionAst child) : base(extent) { - if (attribute is null || child is null) + if (attribute == null || child == null) { - throw PSTraceSource.NewArgumentNullException(attribute is null ? "attribute" : "child"); + throw PSTraceSource.NewArgumentNullException(attribute == null ? "attribute" : "child"); } this.Attribute = attribute; @@ -7727,7 +7727,7 @@ Expression IAssignableValue.SetValue(Compiler compiler, Expression rhs) var assignableValue = GetActualAssignableAst().GetAssignableValue(); var variableExpr = assignableValue as VariableExpressionAst; - if (variableExpr is null) + if (variableExpr == null) { return assignableValue.SetValue(compiler, Compiler.ConvertValue(rhs, attributes)); } @@ -7853,9 +7853,9 @@ public class MemberExpressionAst : ExpressionAst, ISupportsAssignment public MemberExpressionAst(IScriptExtent extent, ExpressionAst expression, CommandElementAst member, bool @static) : base(extent) { - if (expression is null || member is null) + if (expression == null || member == null) { - throw PSTraceSource.NewArgumentNullException(expression is null ? "expression" : "member"); + throw PSTraceSource.NewArgumentNullException(expression == null ? "expression" : "member"); } this.Expression = expression; @@ -8185,9 +8185,9 @@ public sealed class TypeName : ITypeName, ISupportsTypeCaching /// public TypeName(IScriptExtent extent, string name) { - if (extent is null || string.IsNullOrEmpty(name)) + if (extent == null || string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentNullException(extent is null ? "extent" : "name"); + throw PSTraceSource.NewArgumentNullException(extent == null ? "extent" : "name"); } var c = name[0]; @@ -8261,10 +8261,10 @@ public TypeName(IScriptExtent extent, string name, string assembly) internal bool HasDefaultCtor() { - if (_typeDefinitionAst is null) + if (_typeDefinitionAst == null) { Type reflectionType = GetReflectionType(); - if (reflectionType is null) + if (reflectionType == null) { // we are pessimistic about default ctor presence. return false; @@ -8304,7 +8304,7 @@ internal bool HasDefaultCtor() /// public Type GetReflectionType() { - if (_type is null) + if (_type == null) { Exception e; Type type = _typeDefinitionAst != null ? _typeDefinitionAst.Type : TypeResolver.ResolveTypeName(this, out e); @@ -8340,7 +8340,7 @@ public Type GetReflectionType() public Type GetReflectionAttributeType() { var result = GetReflectionType(); - if (result is null || !typeof(Attribute).IsAssignableFrom(result)) + if (result == null || !typeof(Attribute).IsAssignableFrom(result)) { var attrTypeName = new TypeName(_extent, FullName + "Attribute"); result = attrTypeName.GetReflectionType(); @@ -8355,8 +8355,8 @@ public Type GetReflectionAttributeType() internal void SetTypeDefinition(TypeDefinitionAst typeDefinitionAst) { - Diagnostics.Assert(_typeDefinitionAst is null, "Class definition is already set and cannot be changed"); - Diagnostics.Assert(_type is null, "Cannot set class definition if type is already resolved"); + Diagnostics.Assert(_typeDefinitionAst == null, "Class definition is already set and cannot be changed"); + Diagnostics.Assert(_type == null, "Cannot set class definition if type is already resolved"); _typeDefinitionAst = typeDefinitionAst; } @@ -8372,16 +8372,16 @@ public override string ToString() public override bool Equals(object obj) { var other = obj as TypeName; - if (other is null) + if (other == null) return false; if (!_name.Equals(other._name, StringComparison.OrdinalIgnoreCase)) return false; - if (AssemblyName is null) - return other.AssemblyName is null; + if (AssemblyName == null) + return other.AssemblyName == null; - if (other.AssemblyName is null) + if (other.AssemblyName == null) return false; return AssemblyName.Equals(other.AssemblyName, StringComparison.OrdinalIgnoreCase); @@ -8392,7 +8392,7 @@ public override int GetHashCode() { var stringComparer = StringComparer.OrdinalIgnoreCase; var nameHashCode = stringComparer.GetHashCode(_name); - if (AssemblyName is null) + if (AssemblyName == null) return nameHashCode; return Utils.CombineHashCodes(nameHashCode, stringComparer.GetHashCode(AssemblyName)); @@ -8456,12 +8456,12 @@ public sealed class GenericTypeName : ITypeName, ISupportsTypeCaching /// public GenericTypeName(IScriptExtent extent, ITypeName genericTypeName, IEnumerable genericArguments) { - if (genericTypeName is null || extent is null) + if (genericTypeName == null || extent == null) { - throw PSTraceSource.NewArgumentNullException(extent is null ? "extent" : "genericTypeName"); + throw PSTraceSource.NewArgumentNullException(extent == null ? "extent" : "genericTypeName"); } - if (genericArguments is null) + if (genericArguments == null) { throw PSTraceSource.NewArgumentException(nameof(genericArguments)); } @@ -8483,7 +8483,7 @@ public string FullName { get { - if (_cachedFullName is null) + if (_cachedFullName == null) { StringBuilder sb = new StringBuilder(); sb.Append(TypeName.Name); @@ -8579,7 +8579,7 @@ public string Name /// public Type GetReflectionType() { - if (_cachedType is null) + if (_cachedType == null) { Type generic = GetGenericType(TypeName.GetReflectionType()); @@ -8589,7 +8589,7 @@ public Type GetReflectionType() foreach (var arg in GenericArguments) { var type = arg.GetReflectionType(); - if (type is null) + if (type == null) return null; argumentList.Add(type); } @@ -8632,7 +8632,7 @@ public Type GetReflectionType() /// internal Type GetGenericType(Type generic) { - if (generic is null || !generic.ContainsGenericParameters) + if (generic == null || !generic.ContainsGenericParameters) { if (!TypeName.FullName.Contains('`')) { @@ -8656,10 +8656,10 @@ internal Type GetGenericType(Type generic) public Type GetReflectionAttributeType() { Type type = GetReflectionType(); - if (type is null) + if (type == null) { Type generic = TypeName.GetReflectionAttributeType(); - if (generic is null || !generic.ContainsGenericParameters) + if (generic == null || !generic.ContainsGenericParameters) { if (!TypeName.FullName.Contains('`')) { @@ -8691,7 +8691,7 @@ public override string ToString() public override bool Equals(object obj) { var other = obj as GenericTypeName; - if (other is null) + if (other == null) return false; if (!TypeName.Equals(other.TypeName)) @@ -8753,9 +8753,9 @@ public sealed class ArrayTypeName : ITypeName, ISupportsTypeCaching /// public ArrayTypeName(IScriptExtent extent, ITypeName elementType, int rank) { - if (extent is null || elementType is null) + if (extent == null || elementType == null) { - throw PSTraceSource.NewArgumentNullException(extent is null ? "extent" : "name"); + throw PSTraceSource.NewArgumentNullException(extent == null ? "extent" : "name"); } if (rank <= 0) @@ -8808,7 +8808,7 @@ public string FullName { get { - if (_cachedFullName is null) + if (_cachedFullName == null) { Interlocked.CompareExchange(ref _cachedFullName, GetName(includeAssemblyName: true), null); } @@ -8863,7 +8863,7 @@ public Type GetReflectionType() try { RuntimeHelpers.EnsureSufficientExecutionStack(); - if (_cachedType is null) + if (_cachedType == null) { Type elementType = ElementType.GetReflectionType(); if (elementType != null) @@ -8917,7 +8917,7 @@ public override string ToString() public override bool Equals(object obj) { var other = obj as ArrayTypeName; - if (other is null) + if (other == null) return false; return ElementType.Equals(other.ElementType) && Rank == other.Rank; @@ -8953,7 +8953,7 @@ public sealed class ReflectionTypeName : ITypeName, ISupportsTypeCaching /// public ReflectionTypeName(Type type) { - if (type is null) + if (type == null) { throw PSTraceSource.NewArgumentNullException(nameof(type)); } @@ -9019,7 +9019,7 @@ public override string ToString() public override bool Equals(object obj) { var other = obj as ReflectionTypeName; - if (other is null) + if (other == null) return false; return _type == other._type; } @@ -9054,7 +9054,7 @@ public class TypeExpressionAst : ExpressionAst public TypeExpressionAst(IScriptExtent extent, ITypeName typeName) : base(extent) { - if (typeName is null) + if (typeName == null) { throw PSTraceSource.NewArgumentNullException(nameof(typeName)); } @@ -9146,7 +9146,7 @@ internal VariableExpressionAst(VariableToken token) public VariableExpressionAst(IScriptExtent extent, VariablePath variablePath, bool splatted) : base(extent) { - if (variablePath is null) + if (variablePath == null) { throw PSTraceSource.NewArgumentNullException(nameof(variablePath)); } @@ -9441,7 +9441,7 @@ public class StringConstantExpressionAst : ConstantExpressionAst public StringConstantExpressionAst(IScriptExtent extent, string value, StringConstantType stringConstantType) : base(extent, value) { - if (value is null) + if (value == null) { throw PSTraceSource.NewArgumentNullException(nameof(value)); } @@ -9541,7 +9541,7 @@ public ExpandableStringExpressionAst(IScriptExtent extent, StringConstantType type) : base(extent) { - if (value is null) + if (value == null) { throw PSTraceSource.NewArgumentNullException(nameof(value)); } @@ -9688,7 +9688,7 @@ public class ScriptBlockExpressionAst : ExpressionAst public ScriptBlockExpressionAst(IScriptExtent extent, ScriptBlockAst scriptBlock) : base(extent) { - if (scriptBlock is null) + if (scriptBlock == null) { throw PSTraceSource.NewArgumentNullException(nameof(scriptBlock)); } @@ -9760,7 +9760,7 @@ public class ArrayLiteralAst : ExpressionAst, ISupportsAssignment public ArrayLiteralAst(IScriptExtent extent, IList elements) : base(extent) { - if (elements is null || elements.Count == 0) + if (elements == null || elements.Count == 0) { throw PSTraceSource.NewArgumentException(nameof(elements)); } @@ -9933,7 +9933,7 @@ public class ArrayExpressionAst : ExpressionAst public ArrayExpressionAst(IScriptExtent extent, StatementBlockAst statementBlock) : base(extent) { - if (statementBlock is null) + if (statementBlock == null) { throw PSTraceSource.NewArgumentNullException(nameof(statementBlock)); } @@ -9999,7 +9999,7 @@ public class ParenExpressionAst : ExpressionAst, ISupportsAssignment public ParenExpressionAst(IScriptExtent extent, PipelineBaseAst pipeline) : base(extent) { - if (pipeline is null) + if (pipeline == null) { throw PSTraceSource.NewArgumentNullException(nameof(pipeline)); } @@ -10065,7 +10065,7 @@ public class SubExpressionAst : ExpressionAst public SubExpressionAst(IScriptExtent extent, StatementBlockAst statementBlock) : base(extent) { - if (statementBlock is null) + if (statementBlock == null) { throw PSTraceSource.NewArgumentNullException(nameof(statementBlock)); } @@ -10125,7 +10125,7 @@ public class UsingExpressionAst : ExpressionAst public UsingExpressionAst(IScriptExtent extent, ExpressionAst expressionAst) : base(extent) { - if (expressionAst is null) + if (expressionAst == null) { throw PSTraceSource.NewArgumentNullException(nameof(expressionAst)); } @@ -10175,7 +10175,7 @@ public override Ast Copy() [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "We want to get the underlying variable only for the UsingExpressionAst.")] public static VariableExpressionAst ExtractUsingVariable(UsingExpressionAst usingExpressionAst) { - if (usingExpressionAst is null) + if (usingExpressionAst == null) { throw new ArgumentNullException(nameof(usingExpressionAst)); } @@ -10271,9 +10271,9 @@ public class IndexExpressionAst : ExpressionAst, ISupportsAssignment public IndexExpressionAst(IScriptExtent extent, ExpressionAst target, ExpressionAst index) : base(extent) { - if (target is null || index is null) + if (target == null || index == null) { - throw PSTraceSource.NewArgumentNullException(target is null ? "target" : "index"); + throw PSTraceSource.NewArgumentNullException(target == null ? "target" : "index"); } this.Target = target; diff --git a/src/System.Management.Automation/engine/parser/tokenizer.cs b/src/System.Management.Automation/engine/parser/tokenizer.cs index bbfb5e4c075..244930b4b21 100644 --- a/src/System.Management.Automation/engine/parser/tokenizer.cs +++ b/src/System.Management.Automation/engine/parser/tokenizer.cs @@ -165,7 +165,7 @@ public static bool ContainsKeyword(string name) /// public static void AddKeyword(DynamicKeyword keywordToAdd) { - if (keywordToAdd is null) + if (keywordToAdd == null) { PSArgumentNullException e = PSTraceSource.NewArgumentNullException(nameof(keywordToAdd)); throw e; @@ -1122,7 +1122,7 @@ private void NormalizeCRLF(char c) internal void CheckAstIsBeforeSignature(Ast ast) { - if (_beginSignatureExtent is null) + if (_beginSignatureExtent == null) return; if (_beginSignatureExtent.StartOffset < ast.Extent.StartOffset) @@ -1224,7 +1224,7 @@ private T SaveToken(T token) where T : Token // Don't remember these tokens, they aren't useful in $$ and $^. break; default: - if (FirstToken is null) + if (FirstToken == null) { FirstToken = token; } @@ -1725,7 +1725,7 @@ private void ScanToEndOfCommentLine(out bool sawBeginSig, out bool matchedRequir // about 4.45 ms with the more simplistic algorithm. string commentLineComparison = commentLine.ToString().ToLowerInvariant(); - if (_beginTokenSimilarity2dArray is null) + if (_beginTokenSimilarity2dArray == null) { // Create the 2 dimensional array for edit distance calculation if it hasn't been created yet. _beginTokenSimilarity2dArray = new int[beginTokenSimilarityUpperBound + 1, beginSignatureTextNoSpace.Length + 1]; @@ -1797,7 +1797,7 @@ private void ScanLineComment() } else if (matchedRequires && _nestedTokensAdjustment == 0) { - if (RequiresTokens is null) + if (RequiresTokens == null) RequiresTokens = new List(); RequiresTokens.Add(token); } @@ -1890,7 +1890,7 @@ private static int GetStringSimilarity(string first, string second, int[,] dista internal ScriptRequirements GetScriptRequirements() { - if (RequiresTokens is null) + if (RequiresTokens == null) return null; // Make sure a nested scan of the #requires lines don't affect our processing here. @@ -1935,7 +1935,7 @@ internal ScriptRequirements GetScriptRequirements() PSSnapinToken.StartsWith(parameter.ParameterName, StringComparison.OrdinalIgnoreCase)) { snapinSpecified = true; - if (requiredSnapins is null) + if (requiredSnapins == null) { requiredSnapins = new List(); } @@ -2026,7 +2026,7 @@ private void HandleRequiresParameter(CommandParameterAst parameter, return; } - if (argumentAst is null) + if (argumentAst == null) { ReportError(parameter.Extent, nameof(ParserStrings.ParameterRequiresArgument), @@ -2126,7 +2126,7 @@ private void HandleRequiresParameter(CommandParameterAst parameter, { var argumentText = argumentValue as string ?? argumentAst.Extent.Text; var version = Utils.StringToVersion(argumentText); - if (version is null) + if (version == null) { ReportError(argumentAst.Extent, nameof(ParserStrings.RequiresVersionInvalid), @@ -2204,7 +2204,7 @@ private void HandleRequiresParameter(CommandParameterAst parameter, return; } - if (requiredModules is null) + if (requiredModules == null) requiredModules = new List(); requiredModules.Add(moduleSpecification); } @@ -2228,7 +2228,7 @@ private List HandleRequiresAssemblyArgument(Ast argumentAst, object arg, } else { - if (requiredAssemblies is null) + if (requiredAssemblies == null) requiredAssemblies = new List(); if (!requiredAssemblies.Contains((string)arg)) @@ -2251,7 +2251,7 @@ private List HandleRequiresPSEditionArgument(Ast argumentAst, object arg } else { - if (requiredEditions is null) + if (requiredEditions == null) requiredEditions = new List(); var edition = (string)arg; @@ -3896,7 +3896,7 @@ private Token ScanNumber(char firstChar) string strNum = ScanNumberHelper(firstChar, out NumberFormat format, out NumberSuffixFlags suffix, out bool real, out long multiplier); // the token is not a number. i.e. 77z.exe - if (strNum is null) + if (strNum == null) { // Rescan the characters, this is simpler than keeping track of the suffix, multiplier, and 0x prefix. _currentIndex = _tokenStart; @@ -5013,7 +5013,7 @@ internal Token NextToken() _currentIndex = _tokenStart; c = GetChar(); - if (strNum is null) + if (strNum == null) { return ScanGenericToken(c); } diff --git a/src/System.Management.Automation/engine/pipeline.cs b/src/System.Management.Automation/engine/pipeline.cs index f82c012bafe..8b1779de882 100644 --- a/src/System.Management.Automation/engine/pipeline.cs +++ b/src/System.Management.Automation/engine/pipeline.cs @@ -148,7 +148,7 @@ internal void LogExecutionParameterBinding(InvocationInfo invocationInfo, string internal void LogExecutionError(InvocationInfo invocationInfo, ErrorRecord errorRecord) { - if (errorRecord is null) + if (errorRecord == null) return; string message = StringUtil.Format(PipelineStrings.PipelineExecutionNonTerminatingError, GetCommand(invocationInfo), errorRecord.ToString()); @@ -167,7 +167,7 @@ internal void LogExecutionException(Exception exception) _terminatingErrorLogged = true; - if (exception is null) + if (exception == null) return; string message = StringUtil.Format(PipelineStrings.PipelineExecutionTerminatingError, GetCommand(exception), exception.Message); @@ -176,7 +176,7 @@ internal void LogExecutionException(Exception exception) private string GetCommand(InvocationInfo invocationInfo) { - if (invocationInfo is null) + if (invocationInfo == null) return string.Empty; if (invocationInfo.MyCommand != null) @@ -220,7 +220,7 @@ private void Log(string logElement, InvocationInfo invocation, PipelineExecution } // Log the cmdlet invocation execution details if we didn't have an associated script line with it. - if ((invocation is null) || string.IsNullOrEmpty(invocation.Line)) + if ((invocation == null) || string.IsNullOrEmpty(invocation.Line)) { if (hostInterface != null) { @@ -240,7 +240,7 @@ internal void LogToEventLog() { // We check to see if the command is needs writing (or if there is anything in the buffer) // before we flush it. Flushing the empty buffer causes a measurable performance degradation. - if (_commands is null || _commands.Count == 0 || _eventLogBuffer.Count == 0) + if (_commands == null || _commands.Count == 0 || _eventLogBuffer.Count == 0) return; MshLog.LogPipelineExecutionDetailEvent(_commands[0].Command.Context, @@ -251,7 +251,7 @@ internal void LogToEventLog() private bool NeedToLog() { - if (_commands is null) + if (_commands == null) return false; foreach (CommandProcessorBase commandProcessor in _commands) @@ -286,8 +286,8 @@ internal int Add(CommandProcessorBase commandProcessor) internal void AddRedirectionPipe(PipelineProcessor pipelineProcessor) { - if (pipelineProcessor is null) throw PSTraceSource.NewArgumentNullException(nameof(pipelineProcessor)); - if (_redirectionPipes is null) + if (pipelineProcessor == null) throw PSTraceSource.NewArgumentNullException(nameof(pipelineProcessor)); + if (_redirectionPipes == null) _redirectionPipes = new List(); _redirectionPipes.Add(pipelineProcessor); } @@ -316,14 +316,14 @@ internal void AddRedirectionPipe(PipelineProcessor pipelineProcessor) /// internal int AddCommand(CommandProcessorBase commandProcessor, int readFromCommand, bool readErrorQueue) { - if (commandProcessor is null) + if (commandProcessor == null) { throw PSTraceSource.NewArgumentNullException(nameof(commandProcessor)); } - if (_commands is null) + if (_commands == null) { - // "_commands is null" + // "_commands == null" throw PSTraceSource.NewInvalidOperationException(); } @@ -367,17 +367,17 @@ internal int AddCommand(CommandProcessorBase commandProcessor, int readFromComma else { CommandProcessorBase prevcommandProcessor = _commands[readFromCommand - 1] as CommandProcessorBase; - if (prevcommandProcessor is null || prevcommandProcessor.CommandRuntime is null) + if (prevcommandProcessor == null || prevcommandProcessor.CommandRuntime == null) { - // "PipelineProcessor.AddCommand(): previous request object is null" + // "PipelineProcessor.AddCommand(): previous request object == null" throw PSTraceSource.NewInvalidOperationException(); } Pipe UpstreamPipe = (readErrorQueue) ? prevcommandProcessor.CommandRuntime.ErrorOutputPipe : prevcommandProcessor.CommandRuntime.OutputPipe; - if (UpstreamPipe is null) + if (UpstreamPipe == null) { - // "PipelineProcessor.AddCommand(): UpstreamPipe is null" + // "PipelineProcessor.AddCommand(): UpstreamPipe == null" throw PSTraceSource.NewInvalidOperationException(); } @@ -400,9 +400,9 @@ internal int AddCommand(CommandProcessorBase commandProcessor, int readFromComma for (int i = 0; i < _commands.Count; i++) { prevcommandProcessor = _commands[i]; - if (prevcommandProcessor is null || prevcommandProcessor.CommandRuntime is null) + if (prevcommandProcessor == null || prevcommandProcessor.CommandRuntime == null) { - // "PipelineProcessor.AddCommand(): previous request object is null" + // "PipelineProcessor.AddCommand(): previous request object == null" throw PSTraceSource.NewInvalidOperationException(); } // check whether the error output is already claimed @@ -516,7 +516,7 @@ internal Array SynchronousExecuteEnumerate(object input) _firstTerminatingError != null ? _firstTerminatingError.SourceException as StopUpstreamCommandsException : null; - if (stopUpstreamCommandsException is null) + if (stopUpstreamCommandsException == null) { throw; } @@ -597,7 +597,7 @@ private void DoCompleteCore(CommandProcessorBase commandRequestingUpstreamComman { CommandProcessorBase commandProcessor = _commands[i]; - if (commandProcessor is null) + if (commandProcessor == null) { // "null command " + i throw PSTraceSource.NewInvalidOperationException(); @@ -624,7 +624,7 @@ private void DoCompleteCore(CommandProcessorBase commandRequestingUpstreamComman _firstTerminatingError != null ? _firstTerminatingError.SourceException as StopUpstreamCommandsException : null; - if (stopUpstreamCommandsException is null) + if (stopUpstreamCommandsException == null) { throw; } @@ -660,7 +660,7 @@ private void DoCompleteCore(CommandProcessorBase commandRequestingUpstreamComman { // Only log the pipeline completion if this wasn't a nested pipeline, as // pipeline state in transcription is associated with the toplevel pipeline - if ((this.LocalPipeline is null) || (!this.LocalPipeline.IsNested)) + if ((this.LocalPipeline == null) || (!this.LocalPipeline.IsNested)) { lastCommandRuntime.PipelineProcessor.LogPipelineComplete(); } @@ -794,7 +794,7 @@ internal void Stop() // Retain copy of _commands in case Dispose() is called List commands = _commands; - if (commands is null) + if (commands == null) return; // Call StopProcessing() for all the commands. @@ -802,7 +802,7 @@ internal void Stop() { CommandProcessorBase commandProcessor = commands[i]; - if (commandProcessor is null) + if (commandProcessor == null) { throw PSTraceSource.NewInvalidOperationException(); } @@ -945,32 +945,32 @@ private void Start(bool incomingStream) if (_executionStarted) return; - if (_commands is null || 0 == _commands.Count) + if (_commands == null || 0 == _commands.Count) { throw PSTraceSource.NewInvalidOperationException( PipelineStrings.PipelineExecuteRequiresAtLeastOneCommand); } CommandProcessorBase firstcommandProcessor = _commands[0]; - if (firstcommandProcessor is null - || firstcommandProcessor.CommandRuntime is null) + if (firstcommandProcessor == null + || firstcommandProcessor.CommandRuntime == null) { throw PSTraceSource.NewInvalidOperationException( PipelineStrings.PipelineExecuteRequiresAtLeastOneCommand); } // Set the execution scope using the current scope - if (_executionScope is null) + if (_executionScope == null) { _executionScope = firstcommandProcessor.Context.EngineSessionState.CurrentScope; } // add ExternalSuccessOutput to the last command CommandProcessorBase LastCommandProcessor = _commands[_commands.Count - 1]; - if (LastCommandProcessor is null - || LastCommandProcessor.CommandRuntime is null) + if (LastCommandProcessor == null + || LastCommandProcessor.CommandRuntime == null) { - // "PipelineProcessor.Start(): LastCommandProcessor is null" + // "PipelineProcessor.Start(): LastCommandProcessor == null" throw PSTraceSource.NewInvalidOperationException(); } @@ -984,7 +984,7 @@ private void Start(bool incomingStream) // output is not yet claimed SetExternalErrorOutput(); - if (ExternalInput is null && !incomingStream) + if (ExternalInput == null && !incomingStream) { // no upstream cmdlet from the first command firstcommandProcessor.CommandRuntime.IsClosed = true; @@ -1008,7 +1008,7 @@ private void Start(bool incomingStream) for (int i = 0; i < _commands.Count; i++) { CommandProcessorBase commandProcessor = _commands[i]; - if (commandProcessor is null) + if (commandProcessor == null) { // "null command " + i throw PSTraceSource.NewInvalidOperationException(); @@ -1104,7 +1104,7 @@ private void SetupParameterVariables() for (int i = 0; i < _commands.Count; i++) { CommandProcessorBase commandProcessor = _commands[i]; - if (commandProcessor is null || commandProcessor.CommandRuntime is null) + if (commandProcessor == null || commandProcessor.CommandRuntime == null) { // "null command " + i throw PSTraceSource.NewInvalidOperationException(); @@ -1147,8 +1147,8 @@ private void Inject(object input, bool enumerate) { // Add any input to the first command. CommandProcessorBase firstcommandProcessor = _commands[0]; - if (firstcommandProcessor is null - || firstcommandProcessor.CommandRuntime is null) + if (firstcommandProcessor == null + || firstcommandProcessor.CommandRuntime == null) { throw PSTraceSource.NewInvalidOperationException( PipelineStrings.PipelineExecuteRequiresAtLeastOneCommand); @@ -1199,15 +1199,15 @@ private Array RetrieveResults() for (int i = 0; i < _commands.Count; i++) { CommandProcessorBase commandProcessor = _commands[i]; - if (commandProcessor is null - || commandProcessor.CommandRuntime is null) + if (commandProcessor == null + || commandProcessor.CommandRuntime == null) { // "null command or request or ErrorOutputPipe " + i throw PSTraceSource.NewInvalidOperationException(); } Pipe ErrorPipe = commandProcessor.CommandRuntime.ErrorOutputPipe; - if (ErrorPipe.DownstreamCmdlet is null && !ErrorPipe.Empty) + if (ErrorPipe.DownstreamCmdlet == null && !ErrorPipe.Empty) { // 2003/10/02-JonN // Do not return the same error results more than once @@ -1222,10 +1222,10 @@ private Array RetrieveResults() return MshCommandRuntime.StaticEmptyArray; CommandProcessorBase LastCommandProcessor = _commands[_commands.Count - 1]; - if (LastCommandProcessor is null - || LastCommandProcessor.CommandRuntime is null) + if (LastCommandProcessor == null + || LastCommandProcessor.CommandRuntime == null) { - // "PipelineProcessor.RetrieveResults(): LastCommandProcessor is null" + // "PipelineProcessor.RetrieveResults(): LastCommandProcessor == null" throw PSTraceSource.NewInvalidOperationException(); } @@ -1236,7 +1236,7 @@ private Array RetrieveResults() // Do not return the same results more than once LastCommandProcessor.CommandRuntime.OutputPipe.Clear(); - if (results is null) + if (results == null) return MshCommandRuntime.StaticEmptyArray; return results; } @@ -1252,10 +1252,10 @@ internal void LinkPipelineSuccessOutput(Pipe pipeToUse) Dbg.Assert(pipeToUse != null, "Caller should verify pipeToUse != null"); CommandProcessorBase LastCommandProcessor = _commands[_commands.Count - 1]; - if (LastCommandProcessor is null - || LastCommandProcessor.CommandRuntime is null) + if (LastCommandProcessor == null + || LastCommandProcessor.CommandRuntime == null) { - // "PipelineProcessor.RetrieveResults(): LastCommandProcessor is null" + // "PipelineProcessor.RetrieveResults(): LastCommandProcessor == null" throw PSTraceSource.NewInvalidOperationException(); } @@ -1270,14 +1270,14 @@ internal void LinkPipelineErrorOutput(Pipe pipeToUse) for (int i = 0; i < _commands.Count; i++) { CommandProcessorBase commandProcessor = _commands[i]; - if (commandProcessor is null - || commandProcessor.CommandRuntime is null) + if (commandProcessor == null + || commandProcessor.CommandRuntime == null) { // "null command or request or ErrorOutputPipe " + i throw PSTraceSource.NewInvalidOperationException(); } - if (commandProcessor.CommandRuntime.ErrorOutputPipe.DownstreamCmdlet is null) + if (commandProcessor.CommandRuntime.ErrorOutputPipe.DownstreamCmdlet == null) { commandProcessor.CommandRuntime.ErrorOutputPipe = pipeToUse; } @@ -1397,7 +1397,7 @@ internal bool RecordFailure(Exception e, InternalCommand command) bool wasStopping = false; lock (_stopReasonLock) { - if (_firstTerminatingError is null) + if (_firstTerminatingError == null) { _firstTerminatingError = ExceptionDispatchInfo.Capture(e); } diff --git a/src/System.Management.Automation/engine/regex.cs b/src/System.Management.Automation/engine/regex.cs index 5700cf7e464..c867f355158 100644 --- a/src/System.Management.Automation/engine/regex.cs +++ b/src/System.Management.Automation/engine/regex.cs @@ -105,7 +105,7 @@ public WildcardPattern(string pattern) : this(pattern, WildcardOptions.None) /// The constructed WildcardPattern object. public WildcardPattern(string pattern, WildcardOptions options) { - if (pattern is null) + if (pattern == null) { throw PSTraceSource.NewArgumentNullException(nameof(pattern)); } @@ -124,7 +124,7 @@ public WildcardPattern(string pattern, WildcardOptions options) /// public static WildcardPattern Get(string pattern, WildcardOptions options) { - if (pattern is null) + if (pattern == null) throw PSTraceSource.NewArgumentNullException(nameof(pattern)); if (pattern.Length == 1 && pattern[0] == '*') @@ -215,12 +215,12 @@ public bool IsMatch(string input) /// internal static string Escape(string pattern, char[] charsNotToEscape) { - if (pattern is null) + if (pattern == null) { throw PSTraceSource.NewArgumentNullException(nameof(pattern)); } - if (charsNotToEscape is null) + if (charsNotToEscape == null) { throw PSTraceSource.NewArgumentNullException(nameof(charsNotToEscape)); } @@ -329,7 +329,7 @@ public static bool ContainsWildcardCharacters(string pattern) /// public static string Unescape(string pattern) { - if (pattern is null) + if (pattern == null) { throw PSTraceSource.NewArgumentNullException(nameof(pattern)); } @@ -447,7 +447,7 @@ public class WildcardPatternException : RuntimeException internal WildcardPatternException(ErrorRecord errorRecord) : base(RetrieveMessage(errorRecord)) { - if (errorRecord is null) + if (errorRecord == null) { throw new ArgumentNullException(nameof(errorRecord)); } diff --git a/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs b/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs index 700c5d59ace..ba4e08c8f6f 100644 --- a/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs +++ b/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs @@ -135,7 +135,7 @@ internal static void Dispatch( private bool IsRunspacePushed(PSHost host) { IHostSupportsInteractiveSession host2 = host as IHostSupportsInteractiveSession; - if (host2 is null) { return false; } + if (host2 == null) { return false; } // IsRunspacePushed can throw (not implemented exception) try @@ -155,7 +155,7 @@ internal void Execute(PSDataCollectionStream errorStream) Action writeErrorAction = null; // If error-stream is null or we are in pushed-runspace - then write error directly to console. - if (errorStream is null || IsRunspacePushed(_clientHost)) + if (errorStream == null || IsRunspacePushed(_clientHost)) { writeErrorAction = delegate (ErrorRecord errorRecord) { diff --git a/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs b/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs index 6e6c56002a9..4f966f5bdba 100644 --- a/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs +++ b/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs @@ -239,7 +239,7 @@ internal void Initialize( this.outputstream = outputstream; this.settings = settings; - if (settings is null || settings.Host is null) + if (settings == null || settings.Host == null) { hostToUse = runspacePool.Host; } @@ -315,7 +315,7 @@ internal static void ExitHandler(object sender, RemoteDataEventArgsConnectCommandInfo specifying remote command. internal void ConnectAsync(ConnectCommandInfo connectCmdInfo) { - if (connectCmdInfo is null) + if (connectCmdInfo == null) { // Attempt to do a reconnect with the current PSRP client state. this.dataStructureHandler.ReconnectAsync(); @@ -851,7 +851,7 @@ private void HandleRobustConnectionNotification( break; } - if (connectionRetryStatusArgs is null) + if (connectionRetryStatusArgs == null) { return; } diff --git a/src/System.Management.Automation/engine/remoting/client/Job.cs b/src/System.Management.Automation/engine/remoting/client/Job.cs index fef63d2ed34..e8453457f47 100644 --- a/src/System.Management.Automation/engine/remoting/client/Job.cs +++ b/src/System.Management.Automation/engine/remoting/client/Job.cs @@ -331,7 +331,7 @@ public JobStateEventArgs(JobStateInfo jobStateInfo) /// The previous state of the job. public JobStateEventArgs(JobStateInfo jobStateInfo, JobStateInfo previousJobStateInfo) { - if (jobStateInfo is null) + if (jobStateInfo == null) { throw PSTraceSource.NewArgumentNullException(nameof(jobStateInfo)); } @@ -462,7 +462,7 @@ protected Job(string command, string name, IList childJobs) /// reuse of the Id. This is the only way to set either Id or instance Id. protected Job(string command, string name, JobIdentifier token) { - if (token is null) + if (token == null) throw PSTraceSource.NewArgumentNullException(nameof(token), RemotingErrorIdStrings.JobIdentifierNull); if (token.Id > s_jobIdSeed) { @@ -500,7 +500,7 @@ protected Job(string command, string name, Guid instanceId) internal static string GetCommandTextFromInvocationInfo(InvocationInfo invocationInfo) { - if (invocationInfo is null) + if (invocationInfo == null) { return null; } @@ -627,11 +627,11 @@ public IList ChildJobs { get { - if (_childJobs is null) + if (_childJobs == null) { lock (syncObject) { - if (_childJobs is null) + if (_childJobs == null) { _childJobs = new List(); } @@ -692,7 +692,7 @@ internal PSDataCollection Results set { - if (value is null) + if (value == null) { throw PSTraceSource.NewArgumentNullException("Results"); } @@ -720,7 +720,7 @@ internal PSDataCollection Results internal virtual void WriteObject(object outputObject) { - PSObject pso = (outputObject is null) ? null : PSObject.AsPSObject(outputObject); + PSObject pso = (outputObject == null) ? null : PSObject.AsPSObject(outputObject); this.Output.Add(pso); if (!SuppressOutputForwarding) @@ -751,16 +751,16 @@ private void WriteError(Cmdlet cmdlet, ErrorRecord errorRecord) private static Exception GetExceptionFromErrorRecord(ErrorRecord errorRecord) { RuntimeException runtimeException = errorRecord.Exception as RuntimeException; - if (runtimeException is null) + if (runtimeException == null) return null; RemoteException remoteException = runtimeException as RemoteException; - if (remoteException is null) + if (remoteException == null) return null; PSPropertyInfo wasThrownFromThrow = remoteException.SerializedRemoteException.Properties["WasThrownFromThrowStatement"]; - if (wasThrownFromThrow is null || !((bool)wasThrownFromThrow.Value)) + if (wasThrownFromThrow == null || !((bool)wasThrownFromThrow.Value)) return null; runtimeException.WasThrownFromThrowStatement = true; @@ -953,7 +953,7 @@ private T InvokeCmdletMethodAndWaitForResults(Func invokeCmdletMet lock (resultsLock) { - if (closureSafeExceptionThrownOnCmdletThread is null) // stateChangedEventHandler didn't set the results? = ok to clobber results? + if (closureSafeExceptionThrownOnCmdletThread == null) // stateChangedEventHandler didn't set the results? = ok to clobber results? { closureSafeExceptionThrownOnCmdletThread = methodInvoker.ExceptionThrownOnCmdletThread; methodResult = methodInvoker.MethodResult; @@ -1088,7 +1088,7 @@ public PSDataCollection Output set { - if (value is null) + if (value == null) { throw PSTraceSource.NewArgumentNullException("Output"); } @@ -1124,7 +1124,7 @@ public PSDataCollection Error set { - if (value is null) + if (value == null) { throw PSTraceSource.NewArgumentNullException("Error"); } @@ -1160,7 +1160,7 @@ public PSDataCollection Progress set { - if (value is null) + if (value == null) { throw PSTraceSource.NewArgumentNullException("Progress"); } @@ -1193,7 +1193,7 @@ public PSDataCollection Verbose set { - if (value is null) + if (value == null) { throw PSTraceSource.NewArgumentNullException("Verbose"); } @@ -1229,7 +1229,7 @@ public PSDataCollection Debug set { - if (value is null) + if (value == null) { throw PSTraceSource.NewArgumentNullException("Debug"); } @@ -1264,7 +1264,7 @@ public PSDataCollection Warning set { - if (value is null) + if (value == null) { throw PSTraceSource.NewArgumentNullException("Warning"); } @@ -1300,7 +1300,7 @@ public PSDataCollection Information set { - if (value is null) + if (value == null) { throw PSTraceSource.NewArgumentNullException("Information"); } @@ -1393,7 +1393,7 @@ internal void SetJobState(JobState state, Exception reason) if (state == JobState.Running) { // BeginTime is set only once. - if (PSBeginTime is null) + if (PSBeginTime == null) { PSBeginTime = DateTime.Now; } @@ -1403,7 +1403,7 @@ internal void SetJobState(JobState state, Exception reason) alldone = true; // EndTime is set only once. - if (PSEndTime is null) + if (PSEndTime == null) { PSEndTime = DateTime.Now; } @@ -1911,7 +1911,7 @@ internal List GetJobsForComputer(string computerName) foreach (Job j in ChildJobs) { PSRemotingChildJob child = j as PSRemotingChildJob; - if (child is null) continue; + if (child == null) continue; if (string.Equals(child.Runspace.ConnectionInfo.ComputerName, computerName, StringComparison.OrdinalIgnoreCase)) { @@ -1935,7 +1935,7 @@ internal List GetJobsForRunspace(PSSession runspace) foreach (Job j in ChildJobs) { PSRemotingChildJob child = j as PSRemotingChildJob; - if (child is null) continue; + if (child == null) continue; if (child.Runspace.InstanceId.Equals(runspace.InstanceId)) { returnJobList.Add(child); @@ -1959,7 +1959,7 @@ internal List GetJobsForOperation(IThrottleOperation operation) foreach (Job j in ChildJobs) { PSRemotingChildJob child = j as PSRemotingChildJob; - if (child is null) continue; + if (child == null) continue; if (child.Helper.Equals(helper)) { returnJobList.Add(child); @@ -2341,7 +2341,7 @@ private void SetStatusMessage() // for (int i = 0; i < ChildJobs.Count; i++) // { // PSRemotingChildJob childJob = ChildJobs[i] as PSRemotingChildJob; - // if (childJob is null) continue; + // if (childJob == null) continue; // if (childJob.ContainsErrors) // { // if (localErrors) @@ -2992,11 +2992,11 @@ public Debugger Debugger { get { - if (_jobDebugger is null) + if (_jobDebugger == null) { lock (this.SyncObject) { - if ((_jobDebugger is null) && + if ((_jobDebugger == null) && (Runspace.Debugger != null)) { _jobDebugger = new RemotingJobDebugger(Runspace.Debugger, Runspace, this.Name); @@ -3062,7 +3062,7 @@ private void HandleOutputReady(object sender, EventArgs eventArgs) dataObject.Properties.Add(new PSNoteProperty(RemotingConstants.RunspaceIdNoteProperty, reader.RunspaceId)); // PSShowComputerName is present for all the objects (from remoting)..this is to allow PSComputerName to be selected. // Ex: Invoke-Command localhost,blah { gps } | select PSComputerName should work. - if (dataObject.Properties[RemotingConstants.ShowComputerNameNoteProperty] is null) + if (dataObject.Properties[RemotingConstants.ShowComputerNameNoteProperty] == null) { PSNoteProperty showComputerNameNP = new PSNoteProperty(RemotingConstants.ShowComputerNameNoteProperty, !_hideComputerName); dataObject.Properties.Add(showComputerNameNP); @@ -3371,7 +3371,7 @@ protected void ProcessJobFailure(ExecutionCmdletHelper helper, out Exception fai } } - if (failureException is null) + if (failureException == null) { failureException = new RuntimeException( PSRemotingErrorInvariants.FormatResourceString( @@ -3871,12 +3871,12 @@ public RemotingJobDebugger( Runspace runspace, string jobName) { - if (debugger is null) + if (debugger == null) { throw new PSArgumentNullException(nameof(debugger)); } - if (runspace is null) + if (runspace == null) { throw new PSArgumentNullException(nameof(runspace)); } diff --git a/src/System.Management.Automation/engine/remoting/client/Job2.cs b/src/System.Management.Automation/engine/remoting/client/Job2.cs index b9626006897..32923806cce 100644 --- a/src/System.Management.Automation/engine/remoting/client/Job2.cs +++ b/src/System.Management.Automation/engine/remoting/client/Job2.cs @@ -89,11 +89,11 @@ public List StartParameters { get { - if (_parameters is null) + if (_parameters == null) { lock (_syncobject) { - if (_parameters is null) + if (_parameters == null) _parameters = new List(); } } @@ -103,7 +103,7 @@ public List StartParameters set { - if (value is null) + if (value == null) { throw PSTraceSource.NewArgumentNullException("value"); } @@ -551,11 +551,11 @@ private ManualResetEvent JobRunning { get { - if (_jobRunning is null) + if (_jobRunning == null) { lock (_syncObject) { - if (_jobRunning is null) + if (_jobRunning == null) { // this assert is required so that a wait handle // is not created after the object is disposed @@ -576,11 +576,11 @@ private ManualResetEvent JobSuspendedOrAborted { get { - if (_jobSuspendedOrAborted is null) + if (_jobSuspendedOrAborted == null) { lock (_syncObject) { - if (_jobSuspendedOrAborted is null) + if (_jobSuspendedOrAborted == null) { // this assert is required so that a wait handle // is not created after the object is disposed @@ -707,7 +707,7 @@ public ContainerParentJob(string command, string name, string jobType) public void AddChildJob(Job2 childJob) { AssertNotDisposed(); - if (childJob is null) + if (childJob == null) { throw new ArgumentNullException(nameof(childJob)); } @@ -789,7 +789,7 @@ public override void StartJob() foreach (Job2 job in this.ChildJobs) { - if (job is null) throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.JobActionInvalidWithNullChild); + if (job == null) throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.JobActionInvalidWithNullChild); } // If there is only one child job, call the synchronous method on the child to avoid use of another thread. @@ -906,7 +906,7 @@ public override void StartJobAsync() s_structuredTracer.BeginContainerParentJobExecution(InstanceId); foreach (Job2 job in this.ChildJobs) { - if (job is null) throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.JobActionInvalidWithNullChild); + if (job == null) throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.JobActionInvalidWithNullChild); } // Count of StartJobCompleted events from children. @@ -974,7 +974,7 @@ public override void ResumeJob() foreach (Job2 job in this.ChildJobs) { - if (job is null) throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.JobActionInvalidWithNullChild); + if (job == null) throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.JobActionInvalidWithNullChild); } // If there is only one child job, call the synchronous method on the child to avoid use of another thread. @@ -1072,7 +1072,7 @@ public override void ResumeJobAsync() _tracer.WriteMessage(TraceClassName, "ResumeJobAsync", Guid.Empty, this, "Entering method", null); foreach (Job2 job in this.ChildJobs) { - if (job is null) throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.JobActionInvalidWithNullChild); + if (job == null) throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.JobActionInvalidWithNullChild); } // Count of ResumeJobCompleted events from children. @@ -1214,7 +1214,7 @@ public override void UnblockJob() foreach (Job2 job in this.ChildJobs) { - if (job is null) throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.JobActionInvalidWithNullChild); + if (job == null) throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.JobActionInvalidWithNullChild); } // If there is only one child job, call the synchronous method on the child to avoid use of another thread. @@ -1311,7 +1311,7 @@ public override void UnblockJobAsync() _tracer.WriteMessage(TraceClassName, "UnblockJobAsync", Guid.Empty, this, "Entering method", null); foreach (Job2 job in this.ChildJobs) { - if (job is null) throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.JobActionInvalidWithNullChild); + if (job == null) throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.JobActionInvalidWithNullChild); } // count of UnblockJobCompleted events from children. @@ -1382,7 +1382,7 @@ private void SuspendJobInternal(bool? force, string reason) foreach (Job2 job in this.ChildJobs) { - if (job is null) throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.JobActionInvalidWithNullChild); + if (job == null) throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.JobActionInvalidWithNullChild); } // If there is only one child job, call the synchronous method on the child to avoid use of another thread. @@ -1488,7 +1488,7 @@ private void SuspendJobAsyncInternal(bool? force, string reason) _tracer.WriteMessage(TraceClassName, "SuspendJobAsync", Guid.Empty, this, "Entering method", null); foreach (Job2 job in this.ChildJobs) { - if (job is null) throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.JobActionInvalidWithNullChild); + if (job == null) throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.JobActionInvalidWithNullChild); } // Count of SuspendJobCompleted events from children. @@ -1558,7 +1558,7 @@ private void StopJobInternal(bool? force, string reason) foreach (Job2 job in this.ChildJobs) { - if (job is null) throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.JobActionInvalidWithNullChild); + if (job == null) throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.JobActionInvalidWithNullChild); } // If there is only one child job, call the synchronous method on the child to avoid use of another thread. @@ -1666,7 +1666,7 @@ private void StopJobAsyncInternal(bool? force, string reason) foreach (Job2 job in this.ChildJobs) { - if (job is null) throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.JobActionInvalidWithNullChild); + if (job == null) throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.JobActionInvalidWithNullChild); } // count of StopJobCompleted events from children. @@ -2036,7 +2036,7 @@ protected override void Dispose(bool disposing) private string ConstructLocation() { - if (ChildJobs is null || ChildJobs.Count == 0) + if (ChildJobs == null || ChildJobs.Count == 0) return string.Empty; string location = ChildJobs.Select((job) => job.Location).Aggregate((s1, s2) => s1 + ',' + s2); return location; @@ -2044,7 +2044,7 @@ private string ConstructLocation() private string ConstructStatusMessage() { - if (ChildJobs is null || ChildJobs.Count == 0) + if (ChildJobs == null || ChildJobs.Count == 0) return string.Empty; StringBuilder sb = new StringBuilder(); @@ -2091,7 +2091,7 @@ private void UnregisterJobEvent(Job job) private void UnregisterAllJobEvents() { - if (EventManager is null) + if (EventManager == null) { _tracer.WriteMessage("No events subscribed, skipping event unregistrations"); return; @@ -2185,7 +2185,7 @@ protected JobFailedException(SerializationInfo serializationInfo, StreamingConte /// The standard StreaminContext. public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) throw new ArgumentNullException(nameof(info)); base.GetObjectData(info, context); diff --git a/src/System.Management.Automation/engine/remoting/client/JobManager.cs b/src/System.Management.Automation/engine/remoting/client/JobManager.cs index 7adea9a2eb5..6ef47c19752 100644 --- a/src/System.Management.Automation/engine/remoting/client/JobManager.cs +++ b/src/System.Management.Automation/engine/remoting/client/JobManager.cs @@ -176,7 +176,7 @@ internal static void SaveJobId(Guid instanceId, int id, string typeName) /// public Job2 NewJob(JobDefinition definition) { - if (definition is null) + if (definition == null) { throw new ArgumentNullException(nameof(definition)); } @@ -216,12 +216,12 @@ public Job2 NewJob(JobDefinition definition) /// public Job2 NewJob(JobInvocationInfo specification) { - if (specification is null) + if (specification == null) { throw new ArgumentNullException(nameof(specification)); } - if (specification.Definition is null) + if (specification.Definition == null) { throw new ArgumentException(RemotingErrorIdStrings.NewJobSpecificationError, nameof(specification)); } @@ -261,12 +261,12 @@ public Job2 NewJob(JobInvocationInfo specification) /// Job definition containing source adapter information. public void PersistJob(Job2 job, JobDefinition definition) { - if (job is null) + if (job == null) { throw new PSArgumentNullException(nameof(job)); } - if (definition is null) + if (definition == null) { throw new PSArgumentNullException(nameof(definition)); } @@ -593,7 +593,7 @@ private List GetFilteredJobs( } #pragma warning restore 56500 - if (jobs is null) continue; + if (jobs == null) continue; allJobs.AddRange(jobs); } } @@ -619,7 +619,7 @@ private List GetFilteredJobs( private bool CheckTypeNames(JobSourceAdapter sourceAdapter, string[] jobSourceAdapterTypes) { // If no type names were specified then allow all adapter types. - if (jobSourceAdapterTypes is null || + if (jobSourceAdapterTypes == null || jobSourceAdapterTypes.Length == 0) { return true; @@ -758,7 +758,7 @@ private Job2 GetJobThroughId(Guid guid, int id, Cmdlet cmdlet, bool writeErro WriteErrorOrWarning(writeErrorOnException, cmdlet, exception, "JobSourceAdapterGetJobByInstanceIdError", sourceAdapter); } - if (job is null) continue; + if (job == null) continue; if (writeObject) { @@ -939,7 +939,7 @@ internal bool RemoveJob(Job2 job, Cmdlet cmdlet, bool writeErrorOnException, boo } #pragma warning restore 56500 - if (foundJob is null) continue; + if (foundJob == null) continue; jobFound = true; RemoveJobIdForReuse(foundJob); diff --git a/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs b/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs index a2840335739..f38ac4a39d0 100644 --- a/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs +++ b/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs @@ -187,7 +187,7 @@ public string Name set { - if (value is null) + if (value == null) throw new PSArgumentNullException("value"); _name = value; } @@ -296,10 +296,10 @@ public JobInvocationInfo(JobDefinition definition, Dictionary pa public JobInvocationInfo(JobDefinition definition, IEnumerable> parameterCollectionList) { _definition = definition; - if (parameterCollectionList is null) return; + if (parameterCollectionList == null) return; foreach (var parameterCollection in parameterCollectionList) { - if (parameterCollection is null) continue; + if (parameterCollection == null) continue; CommandParameterCollection convertedCollection = ConvertDictionaryToParameterCollection(parameterCollection); if (convertedCollection != null) { @@ -325,7 +325,7 @@ public JobInvocationInfo(JobDefinition definition, CommandParameterCollection pa public JobInvocationInfo(JobDefinition definition, IEnumerable parameters) { _definition = definition; - if (parameters is null) return; + if (parameters == null) return; foreach (var parameter in parameters) { Parameters.Add(parameter); @@ -357,7 +357,7 @@ public virtual void GetObjectData(SerializationInfo info, StreamingContext conte /// The converted collection. private static CommandParameterCollection ConvertDictionaryToParameterCollection(IEnumerable> parameters) { - if (parameters is null) + if (parameters == null) return null; CommandParameterCollection paramCollection = new CommandParameterCollection(); foreach (CommandParameter paramItem in @@ -403,7 +403,7 @@ protected JobIdentifier RetrieveJobIdForReuse(Guid instanceId) [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Only jobs that derive from Job2 should have reusable IDs.")] public void StoreJobIdForReuse(Job2 job, bool recurse) { - if (job is null) + if (job == null) { PSTraceSource.NewArgumentNullException(nameof(job), RemotingErrorIdStrings.JobSourceAdapterCannotSaveNullJob); } @@ -416,7 +416,7 @@ public void StoreJobIdForReuse(Job2 job, bool recurse) foreach (Job child in job.ChildJobs) { Job2 childJob = child as Job2; - if (childJob is null) continue; + if (childJob == null) continue; StoreJobIdForReuseHelper(duplicateDetector, childJob, true); } } @@ -429,11 +429,11 @@ private void StoreJobIdForReuseHelper(Hashtable duplicateDetector, Job2 job, boo JobManager.SaveJobId(job.InstanceId, job.Id, this.GetType().Name); - if (!recurse || job.ChildJobs is null) return; + if (!recurse || job.ChildJobs == null) return; foreach (Job child in job.ChildJobs) { Job2 childJob = child as Job2; - if (childJob is null) continue; + if (childJob == null) continue; StoreJobIdForReuseHelper(duplicateDetector, childJob, recurse); } } diff --git a/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs b/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs index ff8fb949759..7c2aceec7d4 100644 --- a/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs +++ b/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs @@ -69,7 +69,7 @@ internal RemoteRunspacePoolInternal(int minRunspaces, int maxRunspaces, TypeTable typeTable, PSHost host, PSPrimitiveDictionary applicationArguments, RunspaceConnectionInfo connectionInfo, string name = null) : base(minRunspaces, maxRunspaces) { - if (connectionInfo is null) + if (connectionInfo == null) { throw PSTraceSource.NewArgumentNullException("WSManConnectionInfo"); } @@ -116,12 +116,12 @@ internal RemoteRunspacePoolInternal(Guid instanceId, string name, bool isDisconn throw PSTraceSource.NewArgumentNullException("RunspacePool Guid"); } - if (connectCommands is null) + if (connectCommands == null) { throw PSTraceSource.NewArgumentNullException("ConnectCommandInfo[]"); } - if (connectionInfo is null) + if (connectionInfo == null) { throw PSTraceSource.NewArgumentNullException("WSManConnectionInfo"); } @@ -290,7 +290,7 @@ internal override bool ResetRunspaceState() // Version check. Reset Runspace is supported only on PSRP protocol // version 2.3 or greater. Version remoteProtocolVersionDeclaredByServer = PSRemotingProtocolVersion; - if ((remoteProtocolVersionDeclaredByServer is null) || + if ((remoteProtocolVersionDeclaredByServer == null) || (remoteProtocolVersionDeclaredByServer < RemotingConstants.ProtocolVersionWin10RTM)) { throw PSTraceSource.NewInvalidOperationException(RunspacePoolStrings.ResetRunspaceStateNotSupportedOnServer); @@ -577,7 +577,7 @@ internal void HandleStateInfoReceived(object sender, // if closeAsyncResult is null, BeginClose is not called. That means // we are getting close event from server, in this case release the // local resources - if (_closeAsyncResult is null) + if (_closeAsyncResult == null) { // Close the local resources. DataStructureHandler.CloseRunspacePoolAsync(); @@ -1059,14 +1059,14 @@ public override IAsyncResult BeginDisconnect(AsyncCallback callback, object stat /// IAsyncResult object. public override void EndDisconnect(IAsyncResult asyncResult) { - if (asyncResult is null) + if (asyncResult == null) { throw PSTraceSource.NewArgumentNullException(nameof(asyncResult)); } RunspacePoolAsyncResult rsAsyncResult = asyncResult as RunspacePoolAsyncResult; - if ((rsAsyncResult is null) || + if ((rsAsyncResult == null) || (rsAsyncResult.OwnerId != instanceId) || (rsAsyncResult.IsAssociatedWithAsyncOpen)) { @@ -1169,14 +1169,14 @@ public override IAsyncResult BeginConnect(AsyncCallback callback, object state) /// IAsyncResult object. public override void EndConnect(IAsyncResult asyncResult) { - if (asyncResult is null) + if (asyncResult == null) { throw PSTraceSource.NewArgumentNullException(nameof(asyncResult)); } RunspacePoolAsyncResult rsAsyncResult = asyncResult as RunspacePoolAsyncResult; - if ((rsAsyncResult is null) || + if ((rsAsyncResult == null) || (rsAsyncResult.OwnerId != instanceId) || (rsAsyncResult.IsAssociatedWithAsyncOpen)) { @@ -1198,7 +1198,7 @@ public override Collection CreateDisconnectedPowerShells(RunspacePoo { Collection psCollection = new Collection(); - if (ConnectCommands is null) + if (ConnectCommands == null) { // Throw error indicating that this runspacepool is not configured for // reconstructing commands. @@ -1240,7 +1240,7 @@ internal static RunspacePool[] GetRemoteRunspacePools(RunspaceConnectionInfo con WSManConnectionInfo wsmanConnectionInfoParam = connectionInfo as WSManConnectionInfo; // Disconnect-Connect currently only supported by WSMan. - if (wsmanConnectionInfoParam is null) + if (wsmanConnectionInfoParam == null) { throw new NotSupportedException(); } @@ -1259,7 +1259,7 @@ internal static RunspacePool[] GetRemoteRunspacePools(RunspaceConnectionInfo con PSPropertyInfo pspName = rsObject.Properties["Name"]; PSPropertyInfo pspResourceUri = rsObject.Properties["ResourceUri"]; - if (pspShellId is null || pspState is null || pspName is null || pspResourceUri is null) + if (pspShellId == null || pspState == null || pspName == null || pspResourceUri == null) { continue; } @@ -1315,7 +1315,7 @@ internal static RunspacePool[] GetRemoteRunspacePools(RunspaceConnectionInfo con PSPropertyInfo pspCommandId = cmdObject.Properties["CommandId"]; PSPropertyInfo pspCommandLine = cmdObject.Properties["CommandLine"]; - if (pspCommandId is null) + if (pspCommandId == null) { Dbg.Assert(false, "Should not get an empty command Id from a remote runspace pool."); continue; diff --git a/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs b/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs index 8e478f0b36b..7a7a70f9296 100644 --- a/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs +++ b/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs @@ -61,7 +61,7 @@ private RemotingErrorRecord(ErrorRecord errorRecord, OriginInfo originInfo, Exce [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) { throw PSTraceSource.NewArgumentNullException(nameof(info)); } @@ -143,7 +143,7 @@ public RemotingProgressRecord(ProgressRecord progressRecord, OriginInfo originIn private static ProgressRecord Validate(ProgressRecord progressRecord) { - if (progressRecord is null) throw new ArgumentNullException(nameof(progressRecord)); + if (progressRecord == null) throw new ArgumentNullException(nameof(progressRecord)); return progressRecord; } } diff --git a/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs b/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs index e164e1e5bf3..11ce70dd186 100644 --- a/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs +++ b/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs @@ -239,7 +239,7 @@ internal void CreatePowerShellOnServerAndInvoke(ClientRemotePowerShell shell) throw new PSRemotingDataStructureException(RemotingErrorIdStrings.EndpointDoesNotSupportDisconnect); } - if (RemoteSession is null) + if (RemoteSession == null) { throw new ObjectDisposedException("ClientRunspacePoolDataStructureHandler"); } @@ -518,7 +518,7 @@ private void HandleClientRemoteSessionStateChanged( { // use the first reason which caused the error Exception reason = _closingReason; - if (reason is null) + if (reason == null) { reason = e.SessionStateInfo.Reason; _closingReason = reason; @@ -542,7 +542,7 @@ private void HandleClientRemoteSessionStateChanged( { // use the first reason which caused the error Exception reason = _closingReason; - if (reason is null) + if (reason == null) { reason = e.SessionStateInfo.Reason; _closingReason = reason; @@ -726,7 +726,7 @@ private void PrepareForAndStartDisconnect() // Create and fill list of active transportmanager objects to be disconnected. // Add ready-for-disconnect callback handler to DSHandler transportmanager objects. - Dbg.Assert(_preparingForDisconnectList is null, "Cannot prepare for disconnect while disconnect is pending."); + Dbg.Assert(_preparingForDisconnectList == null, "Cannot prepare for disconnect while disconnect is pending."); _preparingForDisconnectList = new List(); foreach (ClientPowerShellDataStructureHandler dsHandler in _associatedPowerShellDSHandlers.Values) { @@ -785,7 +785,7 @@ private void PrepareForConnect() /// private void HandleReadyForDisconnect(object sender, EventArgs args) { - if (sender is null) + if (sender == null) { return; } @@ -795,7 +795,7 @@ private void HandleReadyForDisconnect(object sender, EventArgs args) lock (_associationSyncObject) { // Ignore extra event calls after disconnect is started. - if (_preparingForDisconnectList is null) + if (_preparingForDisconnectList == null) { return; } diff --git a/src/System.Management.Automation/engine/remoting/client/RunspaceRef.cs b/src/System.Management.Automation/engine/remoting/client/RunspaceRef.cs index eb3dcf49492..270e24eb1bd 100644 --- a/src/System.Management.Automation/engine/remoting/client/RunspaceRef.cs +++ b/src/System.Management.Automation/engine/remoting/client/RunspaceRef.cs @@ -127,7 +127,7 @@ internal PSCommand CreatePsCommand(string line, bool isScript, bool? useNewScope PSCommand psCommand = ParsePsCommandUsingScriptBlock(line, useNewScope); // If that didn't work fall back to traditional approach. - if (psCommand is null) + if (psCommand == null) { return CreatePsCommandNotOverridden(line, isScript, useNewScope); } @@ -208,7 +208,7 @@ internal Pipeline CreatePipeline(string line, bool addToHistory, bool useNestedP } // If that didn't work out fall-back to the traditional approach. - if (pipeline is null) + if (pipeline == null) { pipeline = useNestedPipelines ? _runspaceRef.Value.CreateNestedPipeline(line, addToHistory) : diff --git a/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs b/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs index 76c2fd1cf60..efb47508bcc 100644 --- a/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs +++ b/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs @@ -298,7 +298,7 @@ internal void AddChildJobAndPotentiallyBlock( { using (var jobGotEnqueued = new ManualResetEventSlim(initialState: false)) { - if (childJob is null) throw new ArgumentNullException(nameof(childJob)); + if (childJob == null) throw new ArgumentNullException(nameof(childJob)); this.AddChildJobWithoutBlocking(childJob, flags, jobGotEnqueued.Set); jobGotEnqueued.Wait(); @@ -312,7 +312,7 @@ internal void AddChildJobAndPotentiallyBlock( { using (var forwardingCancellation = new CancellationTokenSource()) { - if (childJob is null) throw new ArgumentNullException(nameof(childJob)); + if (childJob == null) throw new ArgumentNullException(nameof(childJob)); this.AddChildJobWithoutBlocking(childJob, flags, forwardingCancellation.Cancel); this.ForwardAllResultsToCmdlet(cmdlet, forwardingCancellation.Token); @@ -375,7 +375,7 @@ internal void DisableFlowControlForPendingCmdletActionsQueue() /// internal void AddChildJobWithoutBlocking(StartableJob childJob, ChildJobFlags flags, Action jobEnqueuedAction = null) { - if (childJob is null) throw new ArgumentNullException(nameof(childJob)); + if (childJob == null) throw new ArgumentNullException(nameof(childJob)); if (childJob.JobStateInfo.State != JobState.NotStarted) throw new ArgumentException(RemotingErrorIdStrings.ThrottlingJobChildAlreadyRunning, nameof(childJob)); this.AssertNotDisposed(); @@ -1104,7 +1104,7 @@ internal static void ProcessCliXmlTestabilityHook(PSStreamObject streamObject) return; } - if (streamObject.Value is null) + if (streamObject.Value == null) { return; } diff --git a/src/System.Management.Automation/engine/remoting/client/clientremotesession.cs b/src/System.Management.Automation/engine/remoting/client/clientremotesession.cs index 5bc2d7ffefa..a2875f819fe 100644 --- a/src/System.Management.Automation/engine/remoting/client/clientremotesession.cs +++ b/src/System.Management.Automation/engine/remoting/client/clientremotesession.cs @@ -147,7 +147,7 @@ internal RemoteRunspacePoolInternal RemoteRunspacePoolInternal set { - Dbg.Assert(_remoteRunspacePool is null, @"RunspacePool should be + Dbg.Assert(_remoteRunspacePool == null, @"RunspacePool should be attached only once to the session"); _remoteRunspacePool = value; } @@ -295,7 +295,7 @@ private void HandleConnectionStateChanged(object sender, RemoteSessionStateEvent { using (s_trace.TraceEventHandlers()) { - if (arg is null) + if (arg == null) { throw PSTraceSource.NewArgumentNullException(nameof(arg)); } @@ -450,12 +450,12 @@ private void HandleNegotiationReceived(object sender, RemoteSessionNegotiationEv { using (s_trace.TraceEventHandlers()) { - if (arg is null) + if (arg == null) { throw PSTraceSource.NewArgumentNullException(nameof(arg)); } - if (arg.RemoteSessionCapability is null) + if (arg.RemoteSessionCapability == null) { throw PSTraceSource.NewArgumentException(nameof(arg)); } diff --git a/src/System.Management.Automation/engine/remoting/client/clientremotesessionprotocolstatemachine.cs b/src/System.Management.Automation/engine/remoting/client/clientremotesessionprotocolstatemachine.cs index 9e56f65f203..ec55f22fc22 100644 --- a/src/System.Management.Automation/engine/remoting/client/clientremotesessionprotocolstatemachine.cs +++ b/src/System.Management.Automation/engine/remoting/client/clientremotesessionprotocolstatemachine.cs @@ -188,7 +188,7 @@ private void SetStateHandler(object sender, RemoteSessionStateMachineEventArgs e { Dbg.Assert(eventArgs.RemoteSessionCapability != null, "State can be set to NegotiationReceived only when RemoteSessionCapability is not null"); - if (eventArgs.RemoteSessionCapability is null) + if (eventArgs.RemoteSessionCapability == null) { throw PSTraceSource.NewArgumentException(nameof(eventArgs)); } @@ -460,7 +460,7 @@ internal ClientRemoteSessionDSHandlerStateMachine() { for (int j = 0; j < _stateMachineHandle.GetLength(1); j++) { - if (_stateMachineHandle[i, j] is null) + if (_stateMachineHandle[i, j] == null) { _stateMachineHandle[i, j] += DoClose; } @@ -552,7 +552,7 @@ internal void RaiseEvent(RemoteSessionStateMachineEventArgs arg, bool clearQueue /// private void RaiseEventPrivate(RemoteSessionStateMachineEventArgs arg) { - if (arg is null) + if (arg == null) { throw PSTraceSource.NewArgumentNullException(nameof(arg)); } diff --git a/src/System.Management.Automation/engine/remoting/client/remotepipeline.cs b/src/System.Management.Automation/engine/remoting/client/remotepipeline.cs index 56a2c88f60f..58931499610 100644 --- a/src/System.Management.Automation/engine/remoting/client/remotepipeline.cs +++ b/src/System.Management.Automation/engine/remoting/client/remotepipeline.cs @@ -137,7 +137,7 @@ internal RemotePipeline(RemoteRunspace runspace, string command, bool addToHisto internal RemotePipeline(RemoteRunspace runspace) : this(runspace, false, false) { - if (runspace.RemoteCommand is null) + if (runspace.RemoteCommand == null) { throw new InvalidOperationException(PipelineStrings.InvalidRemoteCommand); } @@ -169,7 +169,7 @@ private RemotePipeline(RemotePipeline pipeline) : // NTRAID#Windows Out Of Band Releases-915851-2005/09/13 // the above comment copied from RemotePipelineBase which // originally copied it from PipelineBase - if (pipeline is null) + if (pipeline == null) { throw PSTraceSource.NewArgumentNullException(nameof(pipeline)); } @@ -423,7 +423,7 @@ internal override void InvokeAsyncAndDisconnect() /// public override Collection Invoke(System.Collections.IEnumerable input) { - if (input is null) + if (input == null) { this.InputStream.Close(); } @@ -866,7 +866,7 @@ protected void RaisePipelineStateEvents() /// Invoke and Disconnect. private void InitPowerShell(bool syncCall, bool invokeAndDisconnect = false) { - if (_commands is null || _commands.Count == 0) + if (_commands == null || _commands.Count == 0) { throw PSTraceSource.NewInvalidOperationException( RunspaceStrings.NoCommandInPipeline); @@ -921,7 +921,7 @@ private void InitPowerShellForConnect(bool syncCall) } // Initialize the PowerShell object if it hasn't been initialized before. - if ((_powershell.RemotePowerShell) is null || !_powershell.RemotePowerShell.Initialized) + if ((_powershell.RemotePowerShell) == null || !_powershell.RemotePowerShell.Initialized) { PSInvocationSettings settings = new PSInvocationSettings(); settings.AddToHistory = _addToHistory; @@ -1050,7 +1050,7 @@ internal void DoConcurrentCheck(bool syncCall) if (_isNested == false) { - if (currentPipeline is null && + if (currentPipeline == null && ((RemoteRunspace)_runspace).RunspaceAvailability != RunspaceAvailability.Busy && ((RemoteRunspace)_runspace).RunspaceAvailability != RunspaceAvailability.RemoteDebug) { @@ -1059,7 +1059,7 @@ internal void DoConcurrentCheck(bool syncCall) return; } - if (currentPipeline is null && + if (currentPipeline == null && ((RemoteRunspace)_runspace).RemoteCommand != null && _connectCmdInfo != null && Guid.Equals(((RemoteRunspace)_runspace).RemoteCommand.CommandId, _connectCmdInfo.CommandId)) @@ -1099,7 +1099,7 @@ internal void DoConcurrentCheck(bool syncCall) RunspaceStrings.NestedPipelineInvokeAsync); } - if (currentPipeline is null) + if (currentPipeline == null) { if (!_isSteppable) { diff --git a/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs b/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs index 31f633c9b50..a927b49481f 100644 --- a/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs +++ b/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs @@ -443,7 +443,7 @@ internal ConnectCommandInfo RemoteCommand { get { - if (RunspacePool.RemoteRunspacePoolInternal.ConnectCommands is null) + if (RunspacePool.RemoteRunspacePoolInternal.ConnectCommands == null) { return null; } @@ -910,7 +910,7 @@ public override void ConnectAsync() /// Pipeline object in disconnected state. public override Pipeline CreateDisconnectedPipeline() { - if (RemoteCommand is null) + if (RemoteCommand == null) { throw PSTraceSource.NewInvalidOperationException(RunspaceStrings.NoDisconnectedCommand); } @@ -925,7 +925,7 @@ public override Pipeline CreateDisconnectedPipeline() /// PowerShell object in disconnected state. public override PowerShell CreateDisconnectedPowerShell() { - if (RemoteCommand is null) + if (RemoteCommand == null) { throw PSTraceSource.NewInvalidOperationException(RunspaceStrings.NoDisconnectedCommand); } @@ -1027,7 +1027,7 @@ public override Pipeline CreatePipeline() /// public override Pipeline CreatePipeline(string command) { - if (command is null) + if (command == null) { throw PSTraceSource.NewArgumentNullException(nameof(command)); } @@ -1048,7 +1048,7 @@ public override Pipeline CreatePipeline(string command) /// public override Pipeline CreatePipeline(string command, bool addToHistory) { - if (command is null) + if (command == null) { throw PSTraceSource.NewArgumentNullException(nameof(command)); } @@ -1083,7 +1083,7 @@ public override Pipeline CreateNestedPipeline() /// scenarios public override Pipeline CreateNestedPipeline(string command, bool addToHistory) { - if (command is null) + if (command == null) { throw PSTraceSource.NewArgumentNullException(nameof(command)); } @@ -1234,7 +1234,7 @@ private void HandleRunspacePoolStateChanged(object sender, RunspacePoolStateChan // Application private data containing server debug state is updated on // a *reconstruct* connect operation when _applicationPrivateData is null. // Pass new information to the debugger. - if (_applicationPrivateData is null) + if (_applicationPrivateData == null) { _applicationPrivateData = GetApplicationPrivateData(); SetDebugInfo(_applicationPrivateData); @@ -1340,7 +1340,7 @@ private bool SetDebugInfo(PSPrimitiveDictionary psApplicationPrivateData) { // Server supports remote debugging. Create Debugger object for // this remote runspace. - Dbg.Assert(_remoteDebugger is null, "Remote runspace should not have a debugger yet."); + Dbg.Assert(_remoteDebugger == null, "Remote runspace should not have a debugger yet."); _remoteDebugger = new RemoteDebugger(this); // Set initial debugger state. @@ -1672,7 +1672,7 @@ internal bool IsAnotherInvokeCommandExecuting(InvokeCommandCommand invokeCommand // this invoke command is running may be // running in the same pipeline as another // invoke command - if (_currentInvokeCommand is null) + if (_currentInvokeCommand == null) { // this is the first invoke-command, just // set the reference @@ -1839,7 +1839,7 @@ private RemoteDebugger() { } /// Associated remote runspace. public RemoteDebugger(RemoteRunspace runspace) { - if (runspace is null) + if (runspace == null) { throw new PSArgumentNullException(nameof(runspace)); } @@ -1868,12 +1868,12 @@ public override DebuggerCommandResults ProcessCommand(PSCommand command, PSDataC CheckForValidateState(); _detachCommand = false; - if (command is null) + if (command == null) { throw new PSArgumentNullException(nameof(command)); } - if (output is null) + if (output == null) { throw new PSArgumentNullException(nameof(output)); } @@ -1905,7 +1905,7 @@ public override DebuggerCommandResults ProcessCommand(PSCommand command, PSDataC { foreach (var item in internalOutput.ReadAll()) { - if (item is null) { return; } + if (item == null) { return; } DebuggerCommand dbgCmd = item.BaseObject as DebuggerCommand; if (dbgCmd != null) @@ -2177,7 +2177,7 @@ public override bool RemoveBreakpoint(Breakpoint breakpoint, int? runspaceId) // This is supported only for PowerShell versions >= 7.0 CheckRemoteBreakpointManagementSupport(RemoteDebuggingCommands.RemoveBreakpoint); - if (breakpoint is null) + if (breakpoint == null) { return false; } @@ -2206,7 +2206,7 @@ public override Breakpoint EnableBreakpoint(Breakpoint breakpoint, int? runspace // This is supported only for PowerShell versions >= 7.0 CheckRemoteBreakpointManagementSupport(RemoteDebuggingCommands.EnableBreakpoint); - if (breakpoint is null) + if (breakpoint == null) { return null; } @@ -2235,7 +2235,7 @@ public override Breakpoint DisableBreakpoint(Breakpoint breakpoint, int? runspac // This is supported only for PowerShell versions >= 7.0 CheckRemoteBreakpointManagementSupport(RemoteDebuggingCommands.DisableBreakpoint); - if (breakpoint is null) + if (breakpoint == null) { return null; } @@ -2295,7 +2295,7 @@ public override DebuggerStopEventArgs GetDebuggerStopArgs() Collection output = ps.Invoke(); foreach (var item in output) { - if (item is null) { continue; } + if (item == null) { continue; } rtnArgs = item.BaseObject as DebuggerStopEventArgs; if (rtnArgs != null) { break; } @@ -2603,7 +2603,7 @@ private static bool TryGetRemoteDebuggerException( out Exception exception) { exception = null; - if (item is null) + if (item == null) { return false; } @@ -2910,7 +2910,7 @@ private T InvokeRemoteBreakpointFunction(string functionName, Dictionary public override void SetVariable(string name, object value) { - if (name is null) + if (name == null) { throw PSTraceSource.NewArgumentNullException(nameof(name)); } @@ -3025,7 +3025,7 @@ public override void SetVariable(string name, object value) /// public override object GetVariable(string name) { - if (name is null) + if (name == null) { throw PSTraceSource.NewArgumentNullException(nameof(name)); } diff --git a/src/System.Management.Automation/engine/remoting/client/remoterunspaceinfo.cs b/src/System.Management.Automation/engine/remoting/client/remoterunspaceinfo.cs index 013dd348794..1a975f5a785 100644 --- a/src/System.Management.Automation/engine/remoting/client/remoterunspaceinfo.cs +++ b/src/System.Management.Automation/engine/remoting/client/remoterunspaceinfo.cs @@ -226,7 +226,7 @@ public override string ToString() /// Boolean indicating if runspace was inserted. internal bool InsertRunspace(RemoteRunspace remoteRunspace) { - if (remoteRunspace is null || + if (remoteRunspace == null || remoteRunspace.InstanceId != _remoteRunspace.InstanceId) { return false; diff --git a/src/System.Management.Automation/engine/remoting/client/remotingprotocolimplementation.cs b/src/System.Management.Automation/engine/remoting/client/remotingprotocolimplementation.cs index 70b97784a3f..8615bf3398a 100644 --- a/src/System.Management.Automation/engine/remoting/client/remotingprotocolimplementation.cs +++ b/src/System.Management.Automation/engine/remoting/client/remotingprotocolimplementation.cs @@ -65,7 +65,7 @@ internal ClientRemoteSessionDSHandlerImpl(ClientRemoteSession session, { Dbg.Assert(_maxUriRedirectionCount >= 0, "maxUriRedirectionCount cannot be less than 0."); - if (session is null) + if (session == null) { throw PSTraceSource.NewArgumentNullException(nameof(session)); } @@ -277,7 +277,7 @@ internal override void SendNegotiationAsync(RemoteSessionState sessionState) private void HandleStateChanged(object sender, RemoteSessionStateEventArgs arg) { - if (arg is null) + if (arg == null) { throw PSTraceSource.NewArgumentNullException(nameof(arg)); } @@ -539,14 +539,14 @@ internal void HandleTransportError(object sender, TransportErrorOccuredEventArgs /// internal void DispatchInputQueueData(object sender, RemoteDataEventArgs dataArg) { - if (dataArg is null) + if (dataArg == null) { throw PSTraceSource.NewArgumentNullException(nameof(dataArg)); } RemoteDataObject rcvdData = dataArg.ReceivedData; - if (rcvdData is null) + if (rcvdData == null) { throw PSTraceSource.NewArgumentException(nameof(dataArg)); } @@ -609,7 +609,7 @@ internal void DispatchInputQueueData(object sender, RemoteDataEventArgs dataArg) /// private void ProcessSessionMessages(RemoteDataEventArgs arg) { - if (arg is null || arg.ReceivedData is null) + if (arg == null || arg.ReceivedData == null) { throw PSTraceSource.NewArgumentNullException(nameof(arg)); } @@ -683,7 +683,7 @@ private void ProcessSessionMessages(RemoteDataEventArgs arg) internal void ProcessNonSessionMessages(RemoteDataObject rcvdData) { // TODO: Consider changing to Dbg.Assert() - if (rcvdData is null) + if (rcvdData == null) { throw PSTraceSource.NewArgumentNullException(nameof(rcvdData)); } diff --git a/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs b/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs index 42e0b8bcb6f..5f66afdfac1 100644 --- a/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs +++ b/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs @@ -622,7 +622,7 @@ private void StateCallBackHandler(object sender, RunspaceStateEventArgs eArgs) // Check to see if failure is due to stale PSSession error and // add to retry list if this is the case. bool writeError = true; - if (_queryRunspaces is null) + if (_queryRunspaces == null) { PSRemotingTransportException transportException = eArgs.RunspaceStateInfo.Reason as PSRemotingTransportException; if (transportException != null && diff --git a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs index 602e7e429af..dde4422de45 100644 --- a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs +++ b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs @@ -837,7 +837,7 @@ private string ConstructPluginContent(out string srcConfigFilePath, out string d ThrowTerminatingError(er); } - if (configTable is null) + if (configTable == null) { string message = StringUtil.Format(RemotingErrorIdStrings.InvalidPSSessionConfigurationFile, filePath); InvalidOperationException ioe = new InvalidOperationException(message); @@ -1197,7 +1197,7 @@ private string ConstructPluginContent(out string srcConfigFilePath, out string d string.Empty)); } - if (transportOption is null) + if (transportOption == null) { transportOption = new WSManConfigurationOption(); } @@ -1460,7 +1460,7 @@ internal static Version ConstructVersionFormatForConfigXml(Version psVersion) /// internal static string GetRunAsVirtualAccountGroupsString(string[] groups) { - if (groups is null) { return string.Empty; } + if (groups == null) { return string.Empty; } return string.Join(";", groups); } @@ -1754,7 +1754,7 @@ internal static string CreateConditionalACEFromConfig( StringBuilder conditionalACE = new StringBuilder(); Hashtable requiredGroupsHash = configTable[ConfigFileConstants.RequiredGroups] as Hashtable; - if (requiredGroupsHash is null) + if (requiredGroupsHash == null) { throw new PSInvalidOperationException(RemotingErrorIdStrings.RequiredGroupsNotHashTable); } @@ -2209,7 +2209,7 @@ public string SecurityDescriptorSddl CommonSecurityDescriptor c = new CommonSecurityDescriptor(false, false, value); // this will never be the case..as constructor either constructs or throws. // this is used here to avoid FxCop violation. - if (c is null) + if (c == null) { throw new NotSupportedException(); } @@ -3397,7 +3397,7 @@ protected override void ProcessRecord() { ps.AddScript(string.Format(CultureInfo.InvariantCulture, getSessionTypeFormat, CodeGeneration.EscapeSingleQuotedStringContent(Name))); Collection psObjectCollection = ps.Invoke(new object[] { Name }) as Collection; - if (psObjectCollection is null || psObjectCollection.Count != 1) + if (psObjectCollection == null || psObjectCollection.Count != 1) { Dbg.Assert(false, "This should never happen. ps.Invoke always return a Collection"); } @@ -3524,7 +3524,7 @@ protected override void ProcessRecord() private void SetRunAs() { - if (this.runAsCredential is null) + if (this.runAsCredential == null) { if (string.IsNullOrEmpty(_gmsaAccount)) { return; } @@ -3588,7 +3588,7 @@ private void SetQuotas() { ps.AddScript(string.Format(CultureInfo.InvariantCulture, getCurrentIdleTimeoutmsFormat, CodeGeneration.EscapeSingleQuotedStringContent(Name))); Collection psObjectCollection = ps.Invoke(new object[] { Name }) as Collection; - if (psObjectCollection is null || psObjectCollection.Count != 1) + if (psObjectCollection == null || psObjectCollection.Count != 1) { Dbg.Assert(false, "This should never happen. ps.Invoke always return a Collection"); } @@ -3682,12 +3682,12 @@ private void SetSessionConfigurationTypeOptions() { ps.AddScript(string.Format(CultureInfo.InvariantCulture, getSessionConfigurationDataSbFormat, CodeGeneration.EscapeSingleQuotedStringContent(Name))); Collection psObjectCollection = ps.Invoke(new object[] { Name }) as Collection; - if (psObjectCollection is null || psObjectCollection.Count != 1) + if (psObjectCollection == null || psObjectCollection.Count != 1) { Dbg.Assert(false, "This should never happen. Plugin must exist because caller code has already checked this."); } - PSSessionConfigurationData scd = PSSessionConfigurationData.Create(psObjectCollection[0] is null ? string.Empty : PSSessionConfigurationData.Unescape(psObjectCollection[0].BaseObject.ToString())); + PSSessionConfigurationData scd = PSSessionConfigurationData.Create(psObjectCollection[0] == null ? string.Empty : PSSessionConfigurationData.Unescape(psObjectCollection[0].BaseObject.ToString())); PSSessionTypeOption original = sessionTypeOption.ConstructObjectFromPrivateData(scd.PrivateData); original.CopyUpdatedValuesFrom(sessionTypeOption); @@ -3697,7 +3697,7 @@ private void SetSessionConfigurationTypeOptions() bool unsetModulePath = false; if (modulePathSpecified) { - if (modulesToImport is null || + if (modulesToImport == null || modulesToImport.Length == 0 || (modulesToImport.Length == 1 && modulesToImport[0] is string && ((string)modulesToImport[0]).Equals(string.Empty, StringComparison.OrdinalIgnoreCase))) { @@ -3713,7 +3713,7 @@ private void SetSessionConfigurationTypeOptions() // we use the original module path if (!unsetModulePath && string.IsNullOrEmpty(modulePathParameter)) { - modulePathParameter = (scd.ModulesToImportInternal is null) ? null : PSSessionConfigurationCommandUtilities.GetModulePathAsString(scd.ModulesToImportInternal.ToArray()).Trim(); + modulePathParameter = (scd.ModulesToImportInternal == null) ? null : PSSessionConfigurationCommandUtilities.GetModulePathAsString(scd.ModulesToImportInternal.ToArray()).Trim(); } // 1. unsetModulePath is true. In this case, modulePathParameter is definitely null @@ -3856,12 +3856,12 @@ private PSObject ConstructPropertiesForUpdate() result.Properties.Add(new PSNoteProperty(ConfigurationDataFromXML.MAXPSVERSIONTOKEN, PSSessionConfigurationCommandUtilities.ConstructVersionFormatForConfigXml(MaxPSVersion))); } - if (modulePathSpecified && sessionTypeOption is null) + if (modulePathSpecified && sessionTypeOption == null) { bool unsetModulePath = false; string modulePathParameter = null; - if (modulesToImport is null || modulesToImport.Length == 0 || + if (modulesToImport == null || modulesToImport.Length == 0 || (modulesToImport.Length == 1 && modulesToImport[0] is string && ((string)modulesToImport[0]).Equals(string.Empty, StringComparison.OrdinalIgnoreCase))) { unsetModulePath = true; @@ -3878,7 +3878,7 @@ private PSObject ConstructPropertiesForUpdate() // Get the SessionConfigurationDataFormat ps.AddScript(string.Format(CultureInfo.InvariantCulture, getSessionConfigurationDataSbFormat, CodeGeneration.EscapeSingleQuotedStringContent(Name))); Collection psObjectCollection = ps.Invoke(new object[] { Name }) as Collection; - if (psObjectCollection is null || psObjectCollection.Count != 1) + if (psObjectCollection == null || psObjectCollection.Count != 1) { Dbg.Assert(false, "This should never happen. ps.Invoke always return a Collection"); } @@ -3886,7 +3886,7 @@ private PSObject ConstructPropertiesForUpdate() StringBuilder sessionConfigurationData = new StringBuilder(); // SessionConfigurationData doesn't exist in InitializationParameters - if (psObjectCollection[0] is null) + if (psObjectCollection[0] == null) { // if unsetModulePath is false, we set the new sessionConfigurationData to contain the specified module path if (!unsetModulePath) @@ -3975,7 +3975,7 @@ private PSObject ConstructPropertiesForUpdate() foreach (object currentKey in configTable.Keys) { - if (result.Properties[currentKey.ToString()] is null) + if (result.Properties[currentKey.ToString()] == null) { result.Properties.Add(new PSNoteProperty(currentKey.ToString(), configTable[currentKey])); } @@ -4289,7 +4289,7 @@ public string SecurityDescriptorSddl CommonSecurityDescriptor c = new CommonSecurityDescriptor(false, false, value); // this will never be the case..as constructor either constructs or throws. // this is used here to avoid FxCop violation. - if (c is null) + if (c == null) { throw new NotSupportedException(); } @@ -5328,7 +5328,7 @@ protected override void BeginProcessing() // If we could not get the config file, throw an error that it's not a configuration created with // config file-based session configurations. - if (configFilePath is null) + if (configFilePath == null) { string configurationName = (string)foundConfiguration.Properties["Name"].Value; string message = StringUtil.Format(RemotingErrorIdStrings.SessionConfigurationMustBeFileBased, configurationName); diff --git a/src/System.Management.Automation/engine/remoting/commands/DebugJob.cs b/src/System.Management.Automation/engine/remoting/commands/DebugJob.cs index 01f3824c26c..979912619f2 100644 --- a/src/System.Management.Automation/engine/remoting/commands/DebugJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/DebugJob.cs @@ -138,7 +138,7 @@ protected override void EndProcessing() } Runspace runspace = LocalRunspace.DefaultRunspace; - if (runspace is null || runspace.Debugger is null) + if (runspace == null || runspace.Debugger == null) { ThrowTerminatingError( new ErrorRecord( @@ -160,7 +160,7 @@ protected override void EndProcessing() ); } - if (this.Host is null || this.Host.UI is null) + if (this.Host == null || this.Host.UI == null) { ThrowTerminatingError( new ErrorRecord( @@ -417,7 +417,7 @@ private Job GetJobById(int id) // Search jobs in job manager. Job job2 = JobManager.GetJobById(id, this, false, false, false); - if ((jobs1.Count == 0) && (job2 is null)) + if ((jobs1.Count == 0) && (job2 == null)) { ThrowTerminatingError( new ErrorRecord( diff --git a/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs b/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs index 3099417ac33..0b9cfeb2d6e 100644 --- a/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs +++ b/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs @@ -176,7 +176,7 @@ protected override void ProcessRecord() // Get all remote runspaces to disconnect. if (ParameterSetName == DisconnectPSSessionCommand.SessionParameterSet) { - if (Session is null || Session.Length == 0) + if (Session == null || Session.Length == 0) { return; } diff --git a/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs b/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs index 6bd3650b0f0..e99f77db796 100644 --- a/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs @@ -142,7 +142,7 @@ protected override void EndProcessing() // Check for host that supports interactive remote sessions. _interactiveHost = this.Host as IHostSupportsInteractiveSession; - if (_interactiveHost is null) + if (_interactiveHost == null) { WriteError( new ErrorRecord( @@ -456,7 +456,7 @@ public sealed class ExitPSHostProcessCommand : PSCmdlet protected override void ProcessRecord() { var _interactiveHost = this.Host as IHostSupportsInteractiveSession; - if (_interactiveHost is null) + if (_interactiveHost == null) { WriteError( new ErrorRecord( @@ -587,7 +587,7 @@ private int[] GetProcIdsFromProcs(Process[] processes) private int[] GetProcIdsFromNames(string[] names) { - if ((names is null) || (names.Length == 0)) + if ((names == null) || (names.Length == 0)) { return null; } @@ -691,7 +691,7 @@ internal static IReadOnlyCollection GetAppDomainNamesFromProc // Do nothing if the process no longer exists } - if (process is null) + if (process == null) { try { diff --git a/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs b/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs index 6d62ea7438d..daef292017f 100644 --- a/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs @@ -822,7 +822,7 @@ protected override void BeginProcessing() // Adjust RemoteDebug value based on current state var hostDebugger = GetHostDebugger(); - if (hostDebugger is null) + if (hostDebugger == null) { // Do not allow RemoteDebug if there is no host debugger available. Otherwise script will not respond indefinitely. RemoteDebug = false; @@ -1008,7 +1008,7 @@ protected override void BeginProcessing() foreach (IThrottleOperation operation in Operations) { ExecutionCmdletHelperRunspace ecHelper = operation as ExecutionCmdletHelperRunspace; - if (ecHelper is null) + if (ecHelper == null) { // either all the operations will be of type ExecutionCmdletHelperRunspace // or not...there is no mix. @@ -1132,7 +1132,7 @@ protected override void ProcessRecord() if (InputObject != AutomationNull.Value && !_inputStreamClosed) { - if ((ParameterSetName.Equals(InvokeCommandCommand.InProcParameterSet) && (_steppablePipeline is null)) || + if ((ParameterSetName.Equals(InvokeCommandCommand.InProcParameterSet) && (_steppablePipeline == null)) || _needToCollect) { _input.Add(InputObject); @@ -1392,7 +1392,7 @@ private void CreateAndRunSyncJob() _throttleManager.ThrottleComplete += HandleThrottleComplete; _operationsComplete.Reset(); - Dbg.Assert(_disconnectComplete is null, "disconnectComplete event should only be used once."); + Dbg.Assert(_disconnectComplete == null, "disconnectComplete event should only be used once."); _disconnectComplete = new ManualResetEvent(false); _job = new PSInvokeExpressionSyncJob(Operations, _throttleManager); _job.HideComputerName = _hideComputerName; @@ -1451,7 +1451,7 @@ private void HandleJobStateChanged(object sender, JobStateEventArgs e) private void AddConnectionRetryHandler(PSInvokeExpressionSyncJob job) { - if (job is null) + if (job == null) { return; } @@ -1471,7 +1471,7 @@ private void RemoveConnectionRetryHandler(PSInvokeExpressionSyncJob job) // Ensure progress bar is removed. StopProgressBar(0); - if (job is null) + if (job == null) { return; } @@ -1666,7 +1666,7 @@ private void WriteInput(object inputValue) /// Write in a non-blocking manner. private void WriteJobResults(bool nonblocking) { - if (_job is null) + if (_job == null) { return; } @@ -2124,7 +2124,7 @@ public void StartProgress( int secondsTotal, System.Management.Automation.Host.PSHost psHost) { - if (psHost is null) + if (psHost == null) { return; } diff --git a/src/System.Management.Automation/engine/remoting/commands/JobRepository.cs b/src/System.Management.Automation/engine/remoting/commands/JobRepository.cs index e6d395cb56c..d06eabf25a3 100644 --- a/src/System.Management.Automation/engine/remoting/commands/JobRepository.cs +++ b/src/System.Management.Automation/engine/remoting/commands/JobRepository.cs @@ -19,7 +19,7 @@ public abstract class Repository where T : class /// Object to add. public void Add(T item) { - if (item is null) + if (item == null) { throw new ArgumentNullException(_identifier); } @@ -45,7 +45,7 @@ public void Add(T item) /// Object to remove. public void Remove(T item) { - if (item is null) + if (item == null) { throw new ArgumentNullException(_identifier); } diff --git a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs index c4825484c57..8a7a9b88b88 100644 --- a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs +++ b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs @@ -787,7 +787,7 @@ protected override void ProcessRecord() resultData, streamWriter, (_scriptsToProcess.Length == 0))); // Role definitions - if (_roleDefinitions is null) + if (_roleDefinitions == null) { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.RoleDefinitions, RemotingErrorIdStrings.DISCRoleDefinitionsComment, "@{ 'CONTOSO\\SqlAdmins' = @{ RoleCapabilities = 'SqlAdministration' }; 'CONTOSO\\SqlManaged' = @{ RoleCapabilityFiles = 'C:\\RoleCapability\\SqlManaged.psrc' }; 'CONTOSO\\ServerMonitors' = @{ VisibleCmdlets = 'Get-Process' } } ", streamWriter, true)); @@ -803,7 +803,7 @@ protected override void ProcessRecord() // Required groups if (ShouldGenerateConfigurationSnippet("RequiredGroups")) { - if (_requiredGroups is null) + if (_requiredGroups == null) { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.RequiredGroups, RemotingErrorIdStrings.DISCRequiredGroupsComment, "@{ And = @{ Or = 'CONTOSO\\SmartCard-Logon1', 'CONTOSO\\SmartCard-Logon2' }, 'Administrators' }", streamWriter, true)); @@ -842,7 +842,7 @@ protected override void ProcessRecord() if (ShouldGenerateConfigurationSnippet("PowerShellVersion")) { - if (_powerShellVersion is null) + if (_powerShellVersion == null) { isExample = true; _powerShellVersion = PSVersionInfo.PSVersion; @@ -853,7 +853,7 @@ protected override void ProcessRecord() } // Modules to import - if (_modulesToImport is null) + if (_modulesToImport == null) { if (Full) { @@ -875,7 +875,7 @@ protected override void ProcessRecord() } // Visible cmdlets - if ((_visibleCmdlets is null) || (_visibleCmdlets.Length == 0)) + if ((_visibleCmdlets == null) || (_visibleCmdlets.Length == 0)) { if (Full) { @@ -890,7 +890,7 @@ protected override void ProcessRecord() } // Visible functions - if ((_visibleFunctions is null) || (_visibleFunctions.Length == 0)) + if ((_visibleFunctions == null) || (_visibleFunctions.Length == 0)) { if (Full) { @@ -919,7 +919,7 @@ protected override void ProcessRecord() } // Alias definitions - if ((_aliasDefinitions is null) || (_aliasDefinitions.Length == 0)) + if ((_aliasDefinitions == null) || (_aliasDefinitions.Length == 0)) { if (Full) { @@ -934,7 +934,7 @@ protected override void ProcessRecord() } // Function definitions - if (_functionDefinitions is null) + if (_functionDefinitions == null) { if (Full) { @@ -967,7 +967,7 @@ protected override void ProcessRecord() ThrowTerminatingError(e.ErrorRecord); } - if ((hashtable[ConfigFileConstants.FunctionValueToken] as ScriptBlock) is null) + if ((hashtable[ConfigFileConstants.FunctionValueToken] as ScriptBlock) == null) { PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCKeyMustBeScriptBlock, ConfigFileConstants.FunctionValueToken, ConfigFileConstants.FunctionDefinitions, _path)); @@ -996,7 +996,7 @@ protected override void ProcessRecord() } // Variable definitions - if (_variableDefinitions is null) + if (_variableDefinitions == null) { if (Full) { @@ -1060,7 +1060,7 @@ protected override void ProcessRecord() } // Environment variables - if (_environmentVariables is null) + if (_environmentVariables == null) { if (Full) { @@ -1095,7 +1095,7 @@ protected override void ProcessRecord() if (ShouldGenerateConfigurationSnippet("AssembliesToLoad")) { isExample = false; - if ((_assembliesToLoad is null) || (_assembliesToLoad.Length == 0)) + if ((_assembliesToLoad == null) || (_assembliesToLoad.Length == 0)) { isExample = true; _assembliesToLoad = new string[] { "System.Web", "System.OtherAssembly, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" }; @@ -1619,7 +1619,7 @@ protected override void ProcessRecord() SessionConfigurationUtils.QuoteName(_copyright), streamWriter, false)); // Modules to import - if (_modulesToImport is null) + if (_modulesToImport == null) { string exampleModulesToImport = "'MyCustomModule', @{ ModuleName = 'MyCustomModule'; ModuleVersion = '1.0.0.0'; GUID = '4d30d5f0-cb16-4898-812d-f20a6c596bdf' }"; result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.ModulesToImport, RemotingErrorIdStrings.DISCModulesToImportComment, exampleModulesToImport, streamWriter, true)); @@ -1635,7 +1635,7 @@ protected override void ProcessRecord() SessionConfigurationUtils.GetVisibilityDefault(_visibleAliases, streamWriter, this), streamWriter, _visibleAliases.Length == 0)); // Visible cmdlets - if ((_visibleCmdlets is null) || (_visibleCmdlets.Length == 0)) + if ((_visibleCmdlets == null) || (_visibleCmdlets.Length == 0)) { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleCmdlets, RemotingErrorIdStrings.DISCVisibleCmdletsComment, "'Invoke-Cmdlet1', @{ Name = 'Invoke-Cmdlet2'; Parameters = @{ Name = 'Parameter1'; ValidateSet = 'Item1', 'Item2' }, @{ Name = 'Parameter2'; ValidatePattern = 'L*' } }", streamWriter, true)); @@ -1647,7 +1647,7 @@ protected override void ProcessRecord() } // Visible functions - if ((_visibleFunctions is null) || (_visibleFunctions.Length == 0)) + if ((_visibleFunctions == null) || (_visibleFunctions.Length == 0)) { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VisibleFunctions, RemotingErrorIdStrings.DISCVisibleFunctionsComment, "'Invoke-Function1', @{ Name = 'Invoke-Function2'; Parameters = @{ Name = 'Parameter1'; ValidateSet = 'Item1', 'Item2' }, @{ Name = 'Parameter2'; ValidatePattern = 'L*' } }", streamWriter, true)); @@ -1672,7 +1672,7 @@ protected override void ProcessRecord() resultData, streamWriter, (_scriptsToProcess.Length == 0))); // Alias definitions - if ((_aliasDefinitions is null) || (_aliasDefinitions.Length == 0)) + if ((_aliasDefinitions == null) || (_aliasDefinitions.Length == 0)) { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.AliasDefinitions, RemotingErrorIdStrings.DISCAliasDefinitionsComment, "@{ Name = 'Alias1'; Value = 'Invoke-Alias1'}, @{ Name = 'Alias2'; Value = 'Invoke-Alias2'}", streamWriter, true)); @@ -1684,7 +1684,7 @@ protected override void ProcessRecord() } // Function definitions - if (_functionDefinitions is null) + if (_functionDefinitions == null) { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.FunctionDefinitions, RemotingErrorIdStrings.DISCFunctionDefinitionsComment, "@{ Name = 'MyFunction'; ScriptBlock = { param($MyInput) $MyInput } }", streamWriter, true)); @@ -1714,7 +1714,7 @@ protected override void ProcessRecord() ThrowTerminatingError(e.ErrorRecord); } - if ((hashtable[ConfigFileConstants.FunctionValueToken] as ScriptBlock) is null) + if ((hashtable[ConfigFileConstants.FunctionValueToken] as ScriptBlock) == null) { PSArgumentException e = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCKeyMustBeScriptBlock, ConfigFileConstants.FunctionValueToken, ConfigFileConstants.FunctionDefinitions, _path)); @@ -1743,7 +1743,7 @@ protected override void ProcessRecord() } // Variable definitions - if (_variableDefinitions is null) + if (_variableDefinitions == null) { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VariableDefinitions, RemotingErrorIdStrings.DISCVariableDefinitionsComment, "@{ Name = 'Variable1'; Value = { 'Dynamic' + 'InitialValue' } }, @{ Name = 'Variable2'; Value = 'StaticInitialValue' }", streamWriter, true)); @@ -1804,7 +1804,7 @@ protected override void ProcessRecord() } // Environment variables - if (_environmentVariables is null) + if (_environmentVariables == null) { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.EnvironmentVariables, RemotingErrorIdStrings.DISCEnvironmentVariablesComment, "@{ Variable1 = 'Value1'; Variable2 = 'Value2' }", @@ -1828,7 +1828,7 @@ protected override void ProcessRecord() // Assemblies to load bool isExample = false; - if ((_assembliesToLoad is null) || (_assembliesToLoad.Length == 0)) + if ((_assembliesToLoad == null) || (_assembliesToLoad.Length == 0)) { isExample = true; _assembliesToLoad = new string[] { "System.Web", "System.OtherAssembly, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" }; @@ -1883,7 +1883,7 @@ internal static string ConfigFragment(string key, string resourceString, string /// The quoted string. internal static string QuoteName(object name) { - if (name is null) + if (name == null) return "''"; return "'" + System.Management.Automation.Language.CodeGeneration.EscapeSingleQuotedStringContent(name.ToString()) + "'"; } @@ -1895,7 +1895,7 @@ internal static string QuoteName(object name) /// The wrapped string. internal static string WrapScriptBlock(object sb) { - if (sb is null) + if (sb == null) return "{}"; return "{" + sb.ToString() + "}"; } @@ -2117,7 +2117,7 @@ internal static string CombineHashTableOrStringArray(object[] values, StreamWrit else { Hashtable hashVal = values[i] as Hashtable; - if (hashVal is null) + if (hashVal == null) { string message = StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeStringOrHashtableArray, ConfigFileConstants.ModulesToImport); diff --git a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs index b3a794db76b..de046236536 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs @@ -63,7 +63,7 @@ internal void WriteStreamObject(Action action) /// Resolved array of machine names. protected void ResolveComputerNames(string[] computerNames, out string[] resolvedComputerNames) { - if (computerNames is null) + if (computerNames == null) { resolvedComputerNames = new string[1]; @@ -657,10 +657,10 @@ public virtual PSSessionOption SessionOption { get { - if (_sessionOption is null) + if (_sessionOption == null) { object tmp = this.SessionState.PSVariable.GetValue(DEFAULT_SESSION_OPTION); - if (tmp is null || !LanguagePrimitives.TryConvertTo(tmp, out _sessionOption)) + if (tmp == null || !LanguagePrimitives.TryConvertTo(tmp, out _sessionOption)) { _sessionOption = new PSSessionOption(); } @@ -1091,7 +1091,7 @@ private static string GetSSHConnectionStringParameter(object param) /// Parameter value as integer. private static int GetSSHConnectionIntParameter(object param) { - if (param is null) + if (param == null) { throw new PSArgumentException(RemotingErrorIdStrings.InvalidSSHConnectionParameter); } @@ -1888,7 +1888,7 @@ private string GetRemoteServerPsVersion(RemoteRunspace remoteRunspace) } PSPrimitiveDictionary psApplicationPrivateData = remoteRunspace.GetApplicationPrivateData(); - if (psApplicationPrivateData is null) + if (psApplicationPrivateData == null) { // The remote runspace is not opened yet, or it's disconnected before the private data is retrieved. // In this case we cannot validate if the remote server is running PSv5 or later, so for safety purpose, @@ -2256,7 +2256,7 @@ private System.Management.Automation.PowerShell GetPowerShellForPSv3OrLater(stri if (serverPsVersion == PSv3Orv4) { usingValuesInArray = ScriptBlockToPowerShellConverter.GetUsingValuesAsArray(_scriptBlock, allowUsingExpressions, Context, null); - if (usingValuesInArray is null) + if (usingValuesInArray == null) { // 'usingValuesInArray' will be null only if there are UsingExpressions used in different scopes. // PSv3 and PSv4 remote server cannot handle this, so we revert back to the approach we use for PSv2 remote end. @@ -2337,7 +2337,7 @@ private string GetConvertedScript(out List newParameterNames, out List usingVariables = GetUsingVariables(_scriptBlock); - if (usingVariables is null || usingVariables.Count == 0) + if (usingVariables == null || usingVariables.Count == 0) { // No using variable is used, then we don't change the script textOfScriptBlock = this.MyInvocation.ExpectingInput @@ -2429,7 +2429,7 @@ private List GetUsingVariableValues(List paramUsi /// A list of UsingExpressionAsts ordered by the StartOffset. private List GetUsingVariables(ScriptBlock localScriptBlock) { - if (localScriptBlock is null) + if (localScriptBlock == null) { throw new ArgumentNullException(nameof(localScriptBlock), "Caller needs to make sure the parameter value is not null"); } @@ -2725,7 +2725,7 @@ internal Dictionary GetAllRunspaces(bool writeobject, private Dictionary GetMatchingRunspacesByComputerName(bool writeobject, bool writeErrorOnNoMatch) { - if (_computerNames is null || _computerNames.Length == 0) + if (_computerNames == null || _computerNames.Length == 0) { return GetAllRunspaces(writeobject, writeErrorOnNoMatch); } @@ -3003,9 +3003,9 @@ private Dictionary GetMatchingRunspacesByVMNameContainerId(bool var matchingRunspaceInfos = remoteRunspaceInfos .Where(session => (supportWildChar ? inputNamePattern.IsMatch(session.VMName) : inputName.Equals(session.ContainerId)) && - ((sessionNamePattern is null) ? true : sessionNamePattern.IsMatch(session.Name)) && + ((sessionNamePattern == null) ? true : sessionNamePattern.IsMatch(session.Name)) && QueryRunspaces.TestRunspaceState(session.Runspace, filterState) && - ((configurationNamePattern is null) ? true : configurationNamePattern.IsMatch(session.ConfigurationName)) && + ((configurationNamePattern == null) ? true : configurationNamePattern.IsMatch(session.ConfigurationName)) && (session.ComputerType == computerType)) .ToList(); @@ -3063,7 +3063,7 @@ private Dictionary GetMatchingRunspacesByVMNameContainerIdSessi : inputName.Equals(session.ContainerId)) && sessionInstanceId.Equals(session.InstanceId) && QueryRunspaces.TestRunspaceState(session.Runspace, filterState) && - ((configurationNamePattern is null) ? true : configurationNamePattern.IsMatch(session.ConfigurationName)) && + ((configurationNamePattern == null) ? true : configurationNamePattern.IsMatch(session.ConfigurationName)) && (session.ComputerType == computerType)) .ToList(); @@ -3106,9 +3106,9 @@ private Dictionary GetMatchingRunspacesByVMId(bool writeobject, var matchingRunspaceInfos = remoteRunspaceInfos .Where(session => vmId.Equals(session.VMId) && - ((sessionNamePattern is null) ? true : sessionNamePattern.IsMatch(session.Name)) && + ((sessionNamePattern == null) ? true : sessionNamePattern.IsMatch(session.Name)) && QueryRunspaces.TestRunspaceState(session.Runspace, filterState) && - ((configurationNamePattern is null) ? true : configurationNamePattern.IsMatch(session.ConfigurationName)) && + ((configurationNamePattern == null) ? true : configurationNamePattern.IsMatch(session.ConfigurationName)) && (session.ComputerType == TargetMachineType.VirtualMachine)) .ToList(); @@ -3143,7 +3143,7 @@ private Dictionary GetMatchingRunspacesByVMIdSessionInstanceId( .Where(session => vmId.Equals(session.VMId) && sessionInstanceId.Equals(session.InstanceId) && QueryRunspaces.TestRunspaceState(session.Runspace, filterState) && - ((configurationNamePattern is null) ? true : configurationNamePattern.IsMatch(session.ConfigurationName)) && + ((configurationNamePattern == null) ? true : configurationNamePattern.IsMatch(session.ConfigurationName)) && (session.ComputerType == TargetMachineType.VirtualMachine)) .ToList(); @@ -3265,7 +3265,7 @@ internal Runspace PipelineRunspace internal void ConfigureRunspaceDebugging(Runspace runspace) { - if (!RunspaceDebuggingEnabled || (runspace is null) || (runspace.Debugger is null)) { return; } + if (!RunspaceDebuggingEnabled || (runspace == null) || (runspace.Debugger == null)) { return; } runspace.Debugger.DebuggerStop += HandleDebuggerStop; @@ -3285,7 +3285,7 @@ internal void ConfigureRunspaceDebugging(Runspace runspace) internal void CleanupRunspaceDebugging(Runspace runspace) { - if ((runspace is null) || (runspace.Debugger is null)) { return; } + if ((runspace == null) || (runspace.Debugger == null)) { return; } runspace.Debugger.DebuggerStop -= HandleDebuggerStop; } @@ -4083,8 +4083,8 @@ internal static string ExtractMessage( { errorCode = 0; - if (e is null || - e.Message is null) + if (e == null || + e.Message == null) { return string.Empty; } @@ -4194,11 +4194,11 @@ internal static TypeTable BuiltInTypesTable { get { - if (s_TypeTable is null) + if (s_TypeTable == null) { lock (s_SyncObject) { - if (s_TypeTable is null) + if (s_TypeTable == null) { s_TypeTable = TypeTable.LoadDefaultTypeFiles(); } diff --git a/src/System.Management.Automation/engine/remoting/commands/PopRunspaceCommand.cs b/src/System.Management.Automation/engine/remoting/commands/PopRunspaceCommand.cs index 086a7bc8b84..5f80dfb5d0c 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PopRunspaceCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PopRunspaceCommand.cs @@ -23,7 +23,7 @@ protected override void ProcessRecord() { // Pop it off the local host. IHostSupportsInteractiveSession host = this.Host as IHostSupportsInteractiveSession; - if (host is null) + if (host == null) { WriteError( new ErrorRecord( diff --git a/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs b/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs index 26f05c3e603..a7751e0138d 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs @@ -235,7 +235,7 @@ protected override void ProcessRecord() { // Push the remote runspace on the local host. IHostSupportsInteractiveSession host = this.Host as IHostSupportsInteractiveSession; - if (host is null) + if (host == null) { WriteError( new ErrorRecord( @@ -314,7 +314,7 @@ protected override void ProcessRecord() } // If runspace is null then the error record has already been written and we can exit. - if (remoteRunspace is null) { return; } + if (remoteRunspace == null) { return; } // If the runspace is in a disconnected state try to connect. bool runspaceConnected = false; @@ -532,7 +532,7 @@ protected override void StopProcessing() } IHostSupportsInteractiveSession host = this.Host as IHostSupportsInteractiveSession; - if (host is null) + if (host == null) { WriteError( new ErrorRecord( diff --git a/src/System.Management.Automation/engine/remoting/commands/ReceiveJob.cs b/src/System.Management.Automation/engine/remoting/commands/ReceiveJob.cs index 01109b0036d..aa804f68691 100644 --- a/src/System.Management.Automation/engine/remoting/commands/ReceiveJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/ReceiveJob.cs @@ -353,7 +353,7 @@ protected override void ProcessRecord() PSRemotingJob remoteJob = job as PSRemotingJob; - if (remoteJob is null) + if (remoteJob == null) { string message = GetMessage(RemotingErrorIdStrings.RunspaceParamNotSupported); @@ -387,7 +387,7 @@ protected override void ProcessRecord() job as PSRemotingJob; // ComputerName parameter can only be used with remoting jobs - if (remoteJob is null) + if (remoteJob == null) { string message = GetMessage(RemotingErrorIdStrings.ComputerNameParamNotSupported); @@ -416,7 +416,7 @@ protected override void ProcessRecord() case "Location": { - if (_locations is null) + if (_locations == null) { // WriteAll(); jobsToWrite.AddRange(_jobs); @@ -728,7 +728,7 @@ private static void DoUnblockJob(Job job) /// private void WriteJobResults(Job job) { - if (job is null) return; + if (job == null) return; // Q: Why do we need to unblock the job, before getting // the results @@ -794,7 +794,7 @@ private void WriteJobResults(Job job) foreach (PSObject o in output) { - if (o is null) continue; + if (o == null) continue; WriteObject(o); } @@ -802,7 +802,7 @@ private void WriteJobResults(Job job) foreach (ErrorRecord e in errorRecords) { - if (e is null) continue; + if (e == null) continue; MshCommandRuntime mshCommandRuntime = CommandRuntime as MshCommandRuntime; if (mshCommandRuntime != null) { @@ -815,7 +815,7 @@ private void WriteJobResults(Job job) foreach (VerboseRecord v in verboseRecords) { - if (v is null) continue; + if (v == null) continue; MshCommandRuntime mshCommandRuntime = CommandRuntime as MshCommandRuntime; if (mshCommandRuntime != null) { @@ -827,7 +827,7 @@ private void WriteJobResults(Job job) foreach (DebugRecord d in debugRecords) { - if (d is null) continue; + if (d == null) continue; MshCommandRuntime mshCommandRuntime = CommandRuntime as MshCommandRuntime; if (mshCommandRuntime != null) { @@ -839,7 +839,7 @@ private void WriteJobResults(Job job) foreach (WarningRecord w in warningRecords) { - if (w is null) continue; + if (w == null) continue; MshCommandRuntime mshCommandRuntime = CommandRuntime as MshCommandRuntime; if (mshCommandRuntime != null) { @@ -851,7 +851,7 @@ private void WriteJobResults(Job job) foreach (ProgressRecord p in progressRecords) { - if (p is null) continue; + if (p == null) continue; MshCommandRuntime mshCommandRuntime = CommandRuntime as MshCommandRuntime; if (mshCommandRuntime != null) { @@ -863,7 +863,7 @@ private void WriteJobResults(Job job) foreach (InformationRecord p in informationRecords) { - if (p is null) continue; + if (p == null) continue; MshCommandRuntime mshCommandRuntime = CommandRuntime as MshCommandRuntime; if (mshCommandRuntime != null) { @@ -904,7 +904,7 @@ private void WriteReasonError(Job job) // location information. if ((exceptionWithLocation != null) && (exceptionWithLocation.DisplayScriptPosition != null)) { - if (errorRecord.InvocationInfo is null) + if (errorRecord.InvocationInfo == null) { errorRecord.SetInvocationInfo(new InvocationInfo(null, null)); } @@ -1055,11 +1055,11 @@ private void AggregateResultsFromJob(Job job) if (job.MonitorOutputProcessing) { - if (_outputProcessingNotification is null) + if (_outputProcessingNotification == null) { lock (_syncObject) { - if (_outputProcessingNotification is null) + if (_outputProcessingNotification == null) { _outputProcessingNotification = new OutputProcessingState(); } diff --git a/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs b/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs index aa2130596d9..500c5032a49 100644 --- a/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs +++ b/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs @@ -484,7 +484,7 @@ private void QueryForAndConnectCommands(string name, Guid instanceId) // Check the local repository for an existing viable session. PSSession locSession = this.RunspaceRepository.GetItem(runspace.InstanceId); - // Connect the session here. If it fails (connectedSession is null) revert to the + // Connect the session here. If it fails (connectedSession == null) revert to the // reconstruct method. Exception ex; PSSession connectedSession = ConnectSession(locSession, out ex); @@ -640,7 +640,7 @@ private void GetAndConnectSessionCommand() else if (ParameterSetName == ReceivePSSessionCommand.IdParameterSet) { session = GetSessionById(Id); - if (session is null) + if (session == null) { WriteInvalidArgumentError(PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedSessionId, RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedSessionId, @@ -652,7 +652,7 @@ private void GetAndConnectSessionCommand() else if (ParameterSetName == ReceivePSSessionCommand.NameParameterSet) { session = GetSessionByName(Name); - if (session is null) + if (session == null) { WriteInvalidArgumentError(PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedName, RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedName, @@ -664,7 +664,7 @@ private void GetAndConnectSessionCommand() else if (ParameterSetName == ReceivePSSessionCommand.InstanceIdParameterSet) { session = GetSessionByInstanceId(InstanceId); - if (session is null) + if (session == null) { WriteInvalidArgumentError(PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedRunspaceId, RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedRunspaceId, @@ -692,14 +692,14 @@ private void GetAndConnectSessionCommand() if (ShouldProcess(session.Name, VerbsCommunications.Receive)) { Exception ex; - if (ConnectSession(session, out ex) is null) + if (ConnectSession(session, out ex) == null) { // Unable to connect runspace. If this was a *reconnect* runspace then try // obtaining a connectable runspace directly from the server and do a // *reconstruct* connect. PSSession oldSession = session; session = TryGetSessionFromServer(oldSession); - if (session is null) + if (session == null) { // No luck. Return error. string message = StringUtil.Format(RemotingErrorIdStrings.RunspaceCannotBeConnected, oldSession.Name); @@ -883,7 +883,7 @@ private void ConnectSessionToHost(PSSession session, PSRemotingJob job = null) // Otherwise this must be a new disconnected session object that has a running command // associated with it. - if (remoteRunspace.RemoteCommand is null) + if (remoteRunspace.RemoteCommand == null) { // There is no associated running command for this runspace, so we cannot proceed. // Check to see if session is in debug mode. @@ -1032,23 +1032,23 @@ private void WriteRemoteObject( PSObject psObject, PSSession session) { - if (psObject is null) + if (psObject == null) { return; } // Add note properties for this session if they don't already exist. - if (psObject.Properties[RemotingConstants.ComputerNameNoteProperty] is null) + if (psObject.Properties[RemotingConstants.ComputerNameNoteProperty] == null) { psObject.Properties.Add(new PSNoteProperty(RemotingConstants.ComputerNameNoteProperty, session.ComputerName)); } - if (psObject.Properties[RemotingConstants.RunspaceIdNoteProperty] is null) + if (psObject.Properties[RemotingConstants.RunspaceIdNoteProperty] == null) { psObject.Properties.Add(new PSNoteProperty(RemotingConstants.RunspaceIdNoteProperty, session.InstanceId)); } - if (psObject.Properties[RemotingConstants.ShowComputerNameNoteProperty] is null) + if (psObject.Properties[RemotingConstants.ShowComputerNameNoteProperty] == null) { psObject.Properties.Add(new PSNoteProperty(RemotingConstants.ShowComputerNameNoteProperty, true)); } @@ -1069,7 +1069,7 @@ private void ConnectSessionToJob(PSSession session, PSRemotingJob job = null) // Otherwise create a new job object in the disconnected state for this // session and then connect it. bool newJobCreated = false; - if (job is null) + if (job == null) { // The PSRemoting job object uses helper objects to track remote command execution. List helpers = new List(); @@ -1119,7 +1119,7 @@ private PSSession ConnectSession(PSSession session, out Exception ex) { ex = null; - if (session is null || + if (session == null || (session.Runspace.RunspaceStateInfo.State != RunspaceState.Opened && session.Runspace.RunspaceStateInfo.State != RunspaceState.Disconnected)) { @@ -1147,7 +1147,7 @@ private PSSession ConnectSession(PSSession session, out Exception ex) ex = e; } - return (ex is null) ? session : null; + return (ex == null) ? session : null; } /// @@ -1159,7 +1159,7 @@ private PSSession ConnectSession(PSSession session, out Exception ex) private PSSession TryGetSessionFromServer(PSSession session) { RemoteRunspace remoteRunspace = session.Runspace as RemoteRunspace; - if (remoteRunspace is null) + if (remoteRunspace == null) { return null; } @@ -1196,7 +1196,7 @@ private PSRemotingJob FindJobForSession(PSSession session) PSRemotingJob job = null; RemoteRunspace remoteSessionRunspace = session.Runspace as RemoteRunspace; - if (remoteSessionRunspace is null || + if (remoteSessionRunspace == null || remoteSessionRunspace.RemoteCommand != null) { // The provided session is created for *reconstruction* and we diff --git a/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs b/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs index 12c92f286bf..2eed427a6ff 100644 --- a/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs @@ -61,7 +61,7 @@ internal List FindJobsMatchingByName( List matches = new List(); Hashtable duplicateDetector = new Hashtable(); - if (_names is null) return matches; + if (_names == null) return matches; foreach (string name in _names) { @@ -191,7 +191,7 @@ internal List FindJobsMatchingByInstanceId(bool recurse, bool writeobject, Hashtable duplicateDetector = new Hashtable(); - if (_instanceIds is null) return matches; + if (_instanceIds == null) return matches; foreach (Guid id in _instanceIds) { @@ -306,7 +306,7 @@ internal List FindJobsMatchingBySessionId(bool recurse, bool writeobject, b { List matches = new List(); - if (_sessionIds is null) return matches; + if (_sessionIds == null) return matches; Hashtable duplicateDetector = new Hashtable(); @@ -408,7 +408,7 @@ internal List FindJobsMatchingByCommand( { List matches = new List(); - if (_commands is null) return matches; + if (_commands == null) return matches; List jobs = new List(); @@ -558,7 +558,7 @@ private bool FindJobsMatchingByFilterHelper(List matches, List jobsToS internal List CopyJobsToList(Job[] jobs, bool writeobject, bool checkIfJobCanBeRemoved) { List matches = new List(); - if (jobs is null) return matches; + if (jobs == null) return matches; foreach (Job job in jobs) { diff --git a/src/System.Management.Automation/engine/remoting/commands/StartJob.cs b/src/System.Management.Automation/engine/remoting/commands/StartJob.cs index 79173c681dc..29e6640279f 100644 --- a/src/System.Management.Automation/engine/remoting/commands/StartJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/StartJob.cs @@ -608,7 +608,7 @@ protected override void BeginProcessing() ThrowTerminatingError(errorRecord); } - if (WorkingDirectory is null) + if (WorkingDirectory == null) { try { diff --git a/src/System.Management.Automation/engine/remoting/commands/TestPSSessionConfigurationFile.cs b/src/System.Management.Automation/engine/remoting/commands/TestPSSessionConfigurationFile.cs index 2bead07eaa3..3e013caa05b 100644 --- a/src/System.Management.Automation/engine/remoting/commands/TestPSSessionConfigurationFile.cs +++ b/src/System.Management.Automation/engine/remoting/commands/TestPSSessionConfigurationFile.cs @@ -77,7 +77,7 @@ protected override void ProcessRecord() } // Make sure at least one file was found... - if (filePaths is null || filePaths.Count < 1) + if (filePaths == null || filePaths.Count < 1) { string message = StringUtil.Format(RemotingErrorIdStrings.PSSessionConfigurationFileNotFound, _path); FileNotFoundException fnf = new FileNotFoundException(message); @@ -116,7 +116,7 @@ protected override void ProcessRecord() return; } - if (configTable is null) + if (configTable == null) { WriteObject(false); return; diff --git a/src/System.Management.Automation/engine/remoting/commands/WaitJob.cs b/src/System.Management.Automation/engine/remoting/commands/WaitJob.cs index 8755570d9ac..f023ca168a7 100644 --- a/src/System.Management.Automation/engine/remoting/commands/WaitJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/WaitJob.cs @@ -85,7 +85,7 @@ private void SetEndProcessingAction(Action endProcessingAction) Dbg.Assert(endProcessingAction != null, "Caller should verify endProcessingAction != null"); lock (_endProcessingActionLock) { - if (_endProcessingAction is null) + if (_endProcessingAction == null) { Dbg.Assert(!_endProcessingActionIsReady.IsSet, "This line should execute only once"); _endProcessingAction = endProcessingAction; diff --git a/src/System.Management.Automation/engine/remoting/commands/getrunspacecommand.cs b/src/System.Management.Automation/engine/remoting/commands/getrunspacecommand.cs index b80715973d9..2a3c92dfcf3 100644 --- a/src/System.Management.Automation/engine/remoting/commands/getrunspacecommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/getrunspacecommand.cs @@ -331,7 +331,7 @@ protected override void BeginProcessing() { base.BeginProcessing(); - if (ConfigurationName is null) + if (ConfigurationName == null) { ConfigurationName = string.Empty; } @@ -344,7 +344,7 @@ protected override void BeginProcessing() /// protected override void ProcessRecord() { - if ((ParameterSetName == GetPSSessionCommand.NameParameterSet) && ((Name is null) || (Name.Length == 0))) + if ((ParameterSetName == GetPSSessionCommand.NameParameterSet) && ((Name == null) || (Name.Length == 0))) { // that means Get-PSSession (with no parameters)..so retrieve all the runspaces. GetAllRunspaces(true, true); diff --git a/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs b/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs index e1ec5167777..5645272bbe2 100644 --- a/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs @@ -412,12 +412,12 @@ private void HandleURIDirectionReported(object sender, RemoteDataEventArgs /// the event which triggered this method private void HandleRunspaceStateChanged(object sender, OperationStateEventArgs stateEventArgs) { - if (sender is null) + if (sender == null) { throw PSTraceSource.NewArgumentNullException(nameof(sender)); } - if (stateEventArgs is null) + if (stateEventArgs == null) { throw PSTraceSource.NewArgumentNullException(nameof(stateEventArgs)); } @@ -527,7 +527,7 @@ private void HandleRunspaceStateChanged(object sender, OperationStateEventArgs s } } - if (reason is null) + if (reason == null) { reason = new RuntimeException(this.GetMessage(RemotingErrorIdStrings.RemoteRunspaceOpenUnknownState, state)); } @@ -640,7 +640,7 @@ private List CreateRunspacesWhenRunspaceParameterSpecified() int rsIndex = 0; foreach (PSSession remoteRunspaceInfo in _remoteRunspaceInfos) { - if (remoteRunspaceInfo is null || remoteRunspaceInfo.Runspace is null) + if (remoteRunspaceInfo == null || remoteRunspaceInfo.Runspace == null) { ThrowTerminatingError(new ErrorRecord( new ArgumentNullException("PSSession"), "PSSessionArgumentNull", diff --git a/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs b/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs index 7b0f9659f96..ad233ccb481 100644 --- a/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs +++ b/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs @@ -34,7 +34,7 @@ internal static class RemotingCommandUtil { internal static bool HasRepeatingRunspaces(PSSession[] runspaceInfos) { - if (runspaceInfos is null) + if (runspaceInfos == null) { throw PSTraceSource.NewArgumentNullException(nameof(runspaceInfos)); } @@ -63,7 +63,7 @@ internal static bool HasRepeatingRunspaces(PSSession[] runspaceInfos) internal static bool ExceedMaximumAllowableRunspaces(PSSession[] runspaceInfos) { - if (runspaceInfos is null) + if (runspaceInfos == null) { throw PSTraceSource.NewArgumentNullException(nameof(runspaceInfos)); } diff --git a/src/System.Management.Automation/engine/remoting/common/DispatchTable.cs b/src/System.Management.Automation/engine/remoting/common/DispatchTable.cs index 50f49621367..035d39ac84e 100644 --- a/src/System.Management.Automation/engine/remoting/common/DispatchTable.cs +++ b/src/System.Management.Automation/engine/remoting/common/DispatchTable.cs @@ -104,7 +104,7 @@ internal T GetResponse(long callId, T defaultValue) // return caller specified value in case there is no response // from remote end. - if (remoteHostResponse is null) + if (remoteHostResponse == null) { return defaultValue; } diff --git a/src/System.Management.Automation/engine/remoting/common/ObjectRef.cs b/src/System.Management.Automation/engine/remoting/common/ObjectRef.cs index d65a05b026a..25534b59a30 100644 --- a/src/System.Management.Automation/engine/remoting/common/ObjectRef.cs +++ b/src/System.Management.Automation/engine/remoting/common/ObjectRef.cs @@ -40,7 +40,7 @@ internal T Value { get { - if (_newValue is null) + if (_newValue == null) { return _oldValue; } diff --git a/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs b/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs index f0e562ac18c..730a4aa9a2d 100644 --- a/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs +++ b/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs @@ -62,7 +62,7 @@ public Guid ServiceId public override EndPoint Create(SocketAddress SockAddr) { - if (SockAddr is null || + if (SockAddr == null || SockAddr.Family != AF_HYPERV || SockAddr.Size != 34) { @@ -83,7 +83,7 @@ public override bool Equals(object obj) { HyperVSocketEndPoint endpoint = (HyperVSocketEndPoint)obj; - if (endpoint is null) + if (endpoint == null) { return false; } @@ -223,7 +223,7 @@ public RemoteSessionHyperVSocketServer(bool LoopbackMode) sockInfo.Options = SocketInformationOptions.Connected; socket = new Socket(sockInfo); - if (socket is null) + if (socket == null) { Dbg.Assert(false, "Unexpected error in RemoteSessionHyperVSocketServer."); diff --git a/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs b/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs index 2aba46e2a9d..3a75567c10f 100644 --- a/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs +++ b/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs @@ -93,7 +93,7 @@ internal static string CreateProcessPipeName( System.Diagnostics.Process proc, string appDomainName) { - if (proc is null) + if (proc == null) { throw new PSArgumentNullException(nameof(proc)); } @@ -450,7 +450,7 @@ internal static RemoteSessionNamedPipeServer CreateRemoteSessionNamedPipeServer( internal RemoteSessionNamedPipeServer( string pipeName) { - if (pipeName is null) + if (pipeName == null) { throw new PSArgumentNullException(nameof(pipeName)); } @@ -480,11 +480,11 @@ private NamedPipeServerStream CreateNamedPipe( string coreName, CommonSecurityDescriptor securityDesc) { - if (serverName is null) { throw new PSArgumentNullException(nameof(serverName)); } + if (serverName == null) { throw new PSArgumentNullException(nameof(serverName)); } - if (namespaceName is null) { throw new PSArgumentNullException(nameof(namespaceName)); } + if (namespaceName == null) { throw new PSArgumentNullException(nameof(namespaceName)); } - if (coreName is null) { throw new PSArgumentNullException(nameof(coreName)); } + if (coreName == null) { throw new PSArgumentNullException(nameof(coreName)); } #if !UNIX string fullPipeName = @"\\" + serverName + @"\" + namespaceName + @"\" + coreName; @@ -679,7 +679,7 @@ public static void CreateCustomNamedPipeServer(string pipeName) internal void StartListening( Action clientConnectCallback) { - if (clientConnectCallback is null) + if (clientConnectCallback == null) { throw new PSArgumentNullException(nameof(clientConnectCallback)); } @@ -850,7 +850,7 @@ private void ProcessListeningThread(object state) PSKeyword.UseAlwaysOperational, processId, appDomainName, userName); - if (ex is null) + if (ex == null) { // Normal listener exit. _tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty, @@ -899,7 +899,7 @@ internal static void RunServerMode(string configurationName) IPCNamedPipeServerEnabled = true; CreateIPCNamedPipeServerSingleton(); - if (IPCNamedPipeServer is null) + if (IPCNamedPipeServer == null) { throw new RuntimeException(RemotingErrorIdStrings.NamedPipeServerCannotStart); } @@ -929,7 +929,7 @@ internal static void CreateIPCNamedPipeServerSingleton() { if (!IPCNamedPipeServerEnabled) { return; } - if (IPCNamedPipeServer is null || IPCNamedPipeServer.IsDisposed) + if (IPCNamedPipeServer == null || IPCNamedPipeServer.IsDisposed) { try { @@ -1174,7 +1174,7 @@ public RemoteSessionNamedPipeClient( internal RemoteSessionNamedPipeClient( string pipeName) { - if (pipeName is null) + if (pipeName == null) { throw new PSArgumentNullException(nameof(pipeName)); } @@ -1182,7 +1182,7 @@ internal RemoteSessionNamedPipeClient( _pipeName = pipeName; // Defer creating the .Net NamedPipeClientStream object until we connect. - // _clientPipeStream is null. + // _clientPipeStream == null. } /// @@ -1196,16 +1196,16 @@ internal RemoteSessionNamedPipeClient( string namespaceName, string coreName) { - if (serverName is null) { throw new PSArgumentNullException(nameof(serverName)); } + if (serverName == null) { throw new PSArgumentNullException(nameof(serverName)); } - if (namespaceName is null) { throw new PSArgumentNullException(nameof(namespaceName)); } + if (namespaceName == null) { throw new PSArgumentNullException(nameof(namespaceName)); } - if (coreName is null) { throw new PSArgumentNullException(nameof(coreName)); } + if (coreName == null) { throw new PSArgumentNullException(nameof(coreName)); } _pipeName = @"\\" + serverName + @"\" + namespaceName + @"\" + coreName; // Defer creating the .Net NamedPipeClientStream object until we connect. - // _clientPipeStream is null. + // _clientPipeStream == null. } #endregion diff --git a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs index c1063b1f47e..7f46151a857 100644 --- a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs +++ b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs @@ -166,7 +166,7 @@ public CultureInfo Culture set { - if (value is null) + if (value == null) { throw new ArgumentNullException("value"); } @@ -189,7 +189,7 @@ public CultureInfo UICulture set { - if (value is null) + if (value == null) { throw new ArgumentNullException("value"); } @@ -279,7 +279,7 @@ public int OpenTimeout /// public virtual void SetSessionOptions(PSSessionOption options) { - if (options is null) + if (options == null) { throw new ArgumentNullException(nameof(options)); } @@ -398,7 +398,7 @@ public Uri ConnectionUri set { - if (value is null) + if (value == null) { throw PSTraceSource.NewArgumentNullException("value"); } @@ -602,7 +602,7 @@ public override string CertificateThumbprint set { - if (value is null) + if (value == null) { throw PSTraceSource.NewArgumentNullException("value"); } @@ -893,7 +893,7 @@ public WSManConnectionInfo() [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", Scope = "member", Target = "System.Management.Automation.Runspaces.WSManConnectionInfo.#.ctor(System.Uri,System.String,System.Management.Automation.PSCredential)", MessageId = "1#")] public WSManConnectionInfo(Uri uri, string shellUri, PSCredential credential) { - if (uri is null) + if (uri == null) { // if the uri is null..apply wsman default logic for port // resolution..BUG 542726 @@ -973,7 +973,7 @@ public WSManConnectionInfo(Uri uri) /// public override void SetSessionOptions(PSSessionOption options) { - if (options is null) + if (options == null) { throw new ArgumentNullException(nameof(options)); } @@ -1125,7 +1125,7 @@ internal static T ExtractPropertyAsWsManConnectionInfo(RunspaceConnectionInfo string property, T defaultValue) { WSManConnectionInfo wsCI = rsCI as WSManConnectionInfo; - if (wsCI is null) + if (wsCI == null) { return defaultValue; } @@ -1438,7 +1438,7 @@ internal bool IsLocalhostAndNetworkAccess get { return (EnableNetworkAccess && // Interactive token requested - (Credential is null && // No credential provided + (Credential == null && // No credential provided (ComputerName.Equals(DefaultComputerName, StringComparison.OrdinalIgnoreCase) || // Localhost computer name !ComputerName.Contains('.')))); // Not FQDN computer name } @@ -1751,7 +1751,7 @@ public NamedPipeConnectionInfo( string customPipeName, int openTimeout) { - if (customPipeName is null) + if (customPipeName == null) { throw new PSArgumentNullException(nameof(customPipeName)); } @@ -1914,7 +1914,7 @@ public SSHConnectionInfo( string computerName, string keyFilePath) { - if (computerName is null) { throw new PSArgumentNullException(nameof(computerName)); } + if (computerName == null) { throw new PSArgumentNullException(nameof(computerName)); } this.UserName = userName; this.ComputerName = computerName; @@ -2453,7 +2453,7 @@ private static int StartSSHProcessImpl( catch (System.ComponentModel.Win32Exception e) { ex = e; } if ((ex != null) || - (sshProcess is null) || + (sshProcess == null) || (sshProcess.HasExited)) { throw new InvalidOperationException( @@ -3241,10 +3241,10 @@ private static void GetHostComputeInteropTypes(out Type computeSystemPropertiesT // The type name was changed in newer version of Windows so we check for new one first, // then fallback to previous type name to support older versions of Windows computeSystemPropertiesType = schemaAssembly.GetType("HCS.Compute.System.Properties"); - if (computeSystemPropertiesType is null) + if (computeSystemPropertiesType == null) { computeSystemPropertiesType = schemaAssembly.GetType("Microsoft.HyperV.Schema.Compute.System.Properties"); - if (computeSystemPropertiesType is null) + if (computeSystemPropertiesType == null) { throw new PSInvalidOperationException(RemotingErrorIdStrings.CannotGetHostInteropTypes); } @@ -3252,7 +3252,7 @@ private static void GetHostComputeInteropTypes(out Type computeSystemPropertiesT Assembly hostComputeInteropAssembly = Assembly.Load(new AssemblyName("Microsoft.HostCompute.Interop, Version=10.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")); hostComputeInteropType = hostComputeInteropAssembly.GetType("Microsoft.HostCompute.Interop.HostComputeInterop"); - if (hostComputeInteropType is null) + if (hostComputeInteropType == null) { throw new PSInvalidOperationException(RemotingErrorIdStrings.CannotGetHostInteropTypes); } @@ -3430,7 +3430,7 @@ private void GetContainerPropertiesInternal() else { var propertyInfo = computeSystemPropertiesType.GetProperty("RuntimeId"); - if (propertyInfo is null) + if (propertyInfo == null) { throw new PSInvalidOperationException(RemotingErrorIdStrings.CannotGetHostInteropTypes); } diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs index b29f6045424..85ba02b2e7b 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs @@ -595,9 +595,9 @@ internal static void AddNoteProperty(PSObject pso, string propertyName, Value PSEventId.Serializer_PropertyGetterFailed, PSOpcode.Exception, PSTask.Serialization, PSKeyword.Serializer | PSKeyword.UseAlwaysAnalytic, propertyName, - valueGetter.Target is null ? string.Empty : valueGetter.Target.GetType().FullName, + valueGetter.Target == null ? string.Empty : valueGetter.Target.GetType().FullName, e.ToString(), - e.InnerException is null ? string.Empty : e.InnerException.ToString()); + e.InnerException == null ? string.Empty : e.InnerException.ToString()); } try @@ -1103,7 +1103,7 @@ internal static RemoteDataObject GenerateCreatePowerShell(ClientRemotePowerShell dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.PowerShell, powerShell.ToPSObjectForRemoting())); dataAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.NoInput, shell.NoInput)); - if (settings is null) + if (settings == null) { hostInfo = new HostInfo(null); hostInfo.UseRunspaceHost = true; @@ -1116,7 +1116,7 @@ internal static RemoteDataObject GenerateCreatePowerShell(ClientRemotePowerShell else { hostInfo = new HostInfo(settings.Host); - if (settings.Host is null) + if (settings.Host == null) { hostInfo.UseRunspaceHost = true; } @@ -1412,7 +1412,7 @@ internal static RemoteDataObject GeneratePowerShellInformational(object data, internal static RemoteDataObject GeneratePowerShellInformational(ProgressRecord progressRecord, Guid clientRunspacePoolId, Guid clientPowerShellId) { - if (progressRecord is null) + if (progressRecord == null) { throw PSTraceSource.NewArgumentNullException(nameof(progressRecord)); } @@ -1445,7 +1445,7 @@ internal static RemoteDataObject GeneratePowerShellInformational(ProgressRecord internal static RemoteDataObject GeneratePowerShellInformational(InformationRecord informationRecord, Guid clientRunspacePoolId, Guid clientPowerShellId) { - if (informationRecord is null) + if (informationRecord == null) { throw PSTraceSource.NewArgumentNullException(nameof(informationRecord)); } @@ -1635,7 +1635,7 @@ internal static class RemotingDecoder { private static T ConvertPropertyValueTo(string propertyName, object propertyValue) { - if (propertyName is null) // comes from internal caller + if (propertyName == null) // comes from internal caller { throw PSTraceSource.NewArgumentNullException(nameof(propertyName)); } @@ -1678,7 +1678,7 @@ private static T ConvertPropertyValueTo(string propertyName, object propertyV } else if (typeof(T).Equals(typeof(PSObject))) { - if (propertyValue is null) + if (propertyValue == null) { return default(T); // => "return null" for PSObject } @@ -1687,7 +1687,7 @@ private static T ConvertPropertyValueTo(string propertyName, object propertyV return (T)(object)PSObject.AsPSObject(propertyValue); } } - else if (propertyValue is null) + else if (propertyValue == null) { if (!typeof(T).IsValueType) { @@ -1743,19 +1743,19 @@ private static T ConvertPropertyValueTo(string propertyName, object propertyV private static PSPropertyInfo GetProperty(PSObject psObject, string propertyName) { - if (psObject is null) + if (psObject == null) { throw PSTraceSource.NewArgumentNullException(nameof(psObject)); } - if (propertyName is null) + if (propertyName == null) { throw PSTraceSource.NewArgumentNullException(nameof(propertyName)); } PSPropertyInfo property = psObject.Properties[propertyName]; - if (property is null) + if (property == null) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.MissingProperty, propertyName); } @@ -1765,12 +1765,12 @@ private static PSPropertyInfo GetProperty(PSObject psObject, string propertyName internal static T GetPropertyValue(PSObject psObject, string propertyName) { - if (psObject is null) + if (psObject == null) { throw PSTraceSource.NewArgumentNullException(nameof(psObject)); } - if (propertyName is null) + if (propertyName == null) { throw PSTraceSource.NewArgumentNullException(nameof(propertyName)); } @@ -1782,12 +1782,12 @@ internal static T GetPropertyValue(PSObject psObject, string propertyName) internal static IEnumerable EnumerateListProperty(PSObject psObject, string propertyName) { - if (psObject is null) + if (psObject == null) { throw PSTraceSource.NewArgumentNullException(nameof(psObject)); } - if (propertyName is null) + if (propertyName == null) { throw PSTraceSource.NewArgumentNullException(nameof(propertyName)); } @@ -1804,12 +1804,12 @@ internal static IEnumerable EnumerateListProperty(PSObject psObject, strin internal static IEnumerable> EnumerateHashtableProperty(PSObject psObject, string propertyName) { - if (psObject is null) + if (psObject == null) { throw PSTraceSource.NewArgumentNullException(nameof(psObject)); } - if (propertyName is null) + if (propertyName == null) { throw PSTraceSource.NewArgumentNullException(nameof(propertyName)); } @@ -1834,7 +1834,7 @@ internal static IEnumerable> EnumerateHashtable /// RunspacePoolStateInfo. internal static RunspacePoolStateInfo GetRunspacePoolStateInfo(PSObject dataAsPSObject) { - if (dataAsPSObject is null) + if (dataAsPSObject == null) { throw PSTraceSource.NewArgumentNullException(nameof(dataAsPSObject)); } @@ -1853,7 +1853,7 @@ internal static RunspacePoolStateInfo GetRunspacePoolStateInfo(PSObject dataAsPS /// Application private data. internal static PSPrimitiveDictionary GetApplicationPrivateData(PSObject dataAsPSObject) { - if (dataAsPSObject is null) + if (dataAsPSObject == null) { throw PSTraceSource.NewArgumentNullException(nameof(dataAsPSObject)); } @@ -1868,7 +1868,7 @@ internal static PSPrimitiveDictionary GetApplicationPrivateData(PSObject dataAsP /// Public key as string. internal static string GetPublicKey(PSObject dataAsPSObject) { - if (dataAsPSObject is null) + if (dataAsPSObject == null) { throw PSTraceSource.NewArgumentNullException(nameof(dataAsPSObject)); } @@ -1883,7 +1883,7 @@ internal static string GetPublicKey(PSObject dataAsPSObject) /// Encrypted session key as string. internal static string GetEncryptedSessionKey(PSObject dataAsPSObject) { - if (dataAsPSObject is null) + if (dataAsPSObject == null) { throw PSTraceSource.NewArgumentNullException(nameof(dataAsPSObject)); } @@ -1899,7 +1899,7 @@ internal static string GetEncryptedSessionKey(PSObject dataAsPSObject) /// RunspacePoolStateInfo. internal static PSEventArgs GetPSEventArgs(PSObject dataAsPSObject) { - if (dataAsPSObject is null) + if (dataAsPSObject == null) { throw PSTraceSource.NewArgumentNullException(nameof(dataAsPSObject)); } @@ -1924,7 +1924,7 @@ internal static PSEventArgs GetPSEventArgs(PSObject dataAsPSObject) sourceIdentifier, sender, sourceArgs.ToArray(), - messageData is null ? null : PSObject.AsPSObject(messageData)); + messageData == null ? null : PSObject.AsPSObject(messageData)); eventArgs.TimeGenerated = GetPropertyValue(dataAsPSObject, RemoteDataNameStrings.PSEventArgsTimeGenerated); @@ -1939,7 +1939,7 @@ internal static PSEventArgs GetPSEventArgs(PSObject dataAsPSObject) /// Minimum runspaces. internal static int GetMinRunspaces(PSObject dataAsPSObject) { - if (dataAsPSObject is null) + if (dataAsPSObject == null) { throw PSTraceSource.NewArgumentNullException(nameof(dataAsPSObject)); } @@ -1955,7 +1955,7 @@ internal static int GetMinRunspaces(PSObject dataAsPSObject) /// Maximum runspaces. internal static int GetMaxRunspaces(PSObject dataAsPSObject) { - if (dataAsPSObject is null) + if (dataAsPSObject == null) { throw PSTraceSource.NewArgumentNullException(nameof(dataAsPSObject)); } @@ -1971,7 +1971,7 @@ internal static int GetMaxRunspaces(PSObject dataAsPSObject) /// Thread options. internal static PSPrimitiveDictionary GetApplicationArguments(PSObject dataAsPSObject) { - if (dataAsPSObject is null) + if (dataAsPSObject == null) { throw PSTraceSource.NewArgumentNullException(nameof(dataAsPSObject)); } @@ -1988,7 +1988,7 @@ internal static PSPrimitiveDictionary GetApplicationArguments(PSObject dataAsPSO /// RunspacePoolInitInfo generated. internal static RunspacePoolInitInfo GetRunspacePoolInitInfo(PSObject dataAsPSObject) { - if (dataAsPSObject is null) + if (dataAsPSObject == null) { throw PSTraceSource.NewArgumentNullException(nameof(dataAsPSObject)); } @@ -2007,7 +2007,7 @@ internal static RunspacePoolInitInfo GetRunspacePoolInitInfo(PSObject dataAsPSOb /// Thread options. internal static PSThreadOptions GetThreadOptions(PSObject dataAsPSObject) { - if (dataAsPSObject is null) + if (dataAsPSObject == null) { throw PSTraceSource.NewArgumentNullException(nameof(dataAsPSObject)); } @@ -2023,7 +2023,7 @@ internal static PSThreadOptions GetThreadOptions(PSObject dataAsPSObject) /// Host information. internal static HostInfo GetHostInfo(PSObject dataAsPSObject) { - if (dataAsPSObject is null) + if (dataAsPSObject == null) { throw PSTraceSource.NewArgumentNullException(nameof(dataAsPSObject)); } @@ -2058,7 +2058,7 @@ internal static Exception GetExceptionFromSerializedErrorRecord(object serialize { ErrorRecord er = ErrorRecord.FromPSObjectForRemoting(PSObject.AsPSObject(serializedErrorRecord)); - if (er is null) + if (er == null) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.DecodingErrorForErrorRecord); } @@ -2089,7 +2089,7 @@ internal static object GetPowerShellOutput(object data) internal static PSInvocationStateInfo GetPowerShellStateInfo(object data) { PSObject dataAsPSObject = data as PSObject; - if (dataAsPSObject is null) + if (dataAsPSObject == null) { throw new PSRemotingDataStructureException( RemotingErrorIdStrings.DecodingErrorForPowerShellStateInfo); @@ -2107,7 +2107,7 @@ internal static PSInvocationStateInfo GetPowerShellStateInfo(object data) /// Error record. internal static ErrorRecord GetPowerShellError(object data) { - if (data is null) + if (data == null) { throw PSTraceSource.NewArgumentNullException(nameof(data)); } @@ -2124,7 +2124,7 @@ internal static ErrorRecord GetPowerShellError(object data) /// internal static WarningRecord GetPowerShellWarning(object data) { - if (data is null) + if (data == null) { throw PSTraceSource.NewArgumentNullException(nameof(data)); } @@ -2137,7 +2137,7 @@ internal static WarningRecord GetPowerShellWarning(object data) /// internal static VerboseRecord GetPowerShellVerbose(object data) { - if (data is null) + if (data == null) { throw PSTraceSource.NewArgumentNullException(nameof(data)); } @@ -2150,7 +2150,7 @@ internal static VerboseRecord GetPowerShellVerbose(object data) /// internal static DebugRecord GetPowerShellDebug(object data) { - if (data is null) + if (data == null) { throw PSTraceSource.NewArgumentNullException(nameof(data)); } @@ -2164,7 +2164,7 @@ internal static DebugRecord GetPowerShellDebug(object data) internal static ProgressRecord GetPowerShellProgress(object data) { PSObject dataAsPSObject = PSObject.AsPSObject(data); - if (dataAsPSObject is null) + if (dataAsPSObject == null) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.CantCastRemotingDataToPSObject, data.GetType().FullName); } @@ -2178,7 +2178,7 @@ internal static ProgressRecord GetPowerShellProgress(object data) internal static InformationRecord GetPowerShellInformation(object data) { PSObject dataAsPSObject = PSObject.AsPSObject(data); - if (dataAsPSObject is null) + if (dataAsPSObject == null) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.CantCastRemotingDataToPSObject, data.GetType().FullName); } @@ -2194,7 +2194,7 @@ internal static InformationRecord GetPowerShellInformation(object data) internal static PowerShell GetPowerShell(object data) { PSObject dataAsPSObject = PSObject.AsPSObject(data); - if (dataAsPSObject is null) + if (dataAsPSObject == null) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.CantCastRemotingDataToPSObject, data.GetType().FullName); } @@ -2211,7 +2211,7 @@ internal static PowerShell GetPowerShell(object data) internal static PowerShell GetCommandDiscoveryPipeline(object data) { PSObject dataAsPSObject = PSObject.AsPSObject(data); - if (dataAsPSObject is null) + if (dataAsPSObject == null) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.CantCastRemotingDataToPSObject, data.GetType().FullName); } @@ -2286,7 +2286,7 @@ internal static bool GetNoInput(object data) { PSObject dataAsPSObject = PSObject.AsPSObject(data); - if (dataAsPSObject is null) + if (dataAsPSObject == null) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.CantCastRemotingDataToPSObject, data.GetType().FullName); } @@ -2303,7 +2303,7 @@ internal static bool GetAddToHistory(object data) { PSObject dataAsPSObject = PSObject.AsPSObject(data); - if (dataAsPSObject is null) + if (dataAsPSObject == null) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.CantCastRemotingDataToPSObject, data.GetType().FullName); } @@ -2320,7 +2320,7 @@ internal static bool GetIsNested(object data) { PSObject dataAsPSObject = PSObject.AsPSObject(data); - if (dataAsPSObject is null) + if (dataAsPSObject == null) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.CantCastRemotingDataToPSObject, data.GetType().FullName); } @@ -2359,7 +2359,7 @@ internal static RemoteSessionCapability GetSessionCapability(object data) { PSObject dataAsPSObject = data as PSObject; - if (dataAsPSObject is null) + if (dataAsPSObject == null) { throw new PSRemotingDataStructureException( RemotingErrorIdStrings.CantCastRemotingDataToPSObject, data.GetType().FullName); @@ -2402,7 +2402,7 @@ internal static RemoteSessionCapability GetSessionCapability(object data) /// True if batch invocation is supported, false if not. internal static bool ServerSupportsBatchInvocation(Runspace runspace) { - if (runspace is null || runspace.RunspaceStateInfo.State == RunspaceState.BeforeOpen) + if (runspace == null || runspace.RunspaceStateInfo.State == RunspaceState.BeforeOpen) { return false; } diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteDebuggingCapability.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteDebuggingCapability.cs index b1b7f93f1c9..8314337b77a 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteDebuggingCapability.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteDebuggingCapability.cs @@ -37,7 +37,7 @@ private RemoteDebuggingCapability(Version powerShellVersion) _supportedCommands.Add(RemoteDebuggingCommands.SetDebuggerAction); _supportedCommands.Add(RemoteDebuggingCommands.SetDebugMode); - if (PSVersion is null) + if (PSVersion == null) { return; } 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 f8818d8ddf2..414676dffed 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHost.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHost.cs @@ -86,7 +86,7 @@ private static PSObject EncodeParameters(object[] parameters) ArrayList parameterList = new ArrayList(); for (int i = 0; i < parameters.Length; ++i) { - object parameter = parameters[i] is null ? null : RemoteHostEncoder.EncodeObject(parameters[i]); + object parameter = parameters[i] == null ? null : RemoteHostEncoder.EncodeObject(parameters[i]); parameterList.Add(parameter); } @@ -104,7 +104,7 @@ private static object[] DecodeParameters(PSObject parametersPSObject, Type[] par Dbg.Assert(parameters.Count == parameterTypes.Length, "Expected parameters.Count == parameterTypes.Length"); for (int i = 0; i < parameters.Count; ++i) { - object parameter = parameters[i] is null ? null : RemoteHostEncoder.DecodeObject(parameters[i], parameterTypes[i]); + object parameter = parameters[i] == null ? null : RemoteHostEncoder.DecodeObject(parameters[i], parameterTypes[i]); decodedParameters.Add(parameter); } @@ -170,7 +170,7 @@ internal void ExecuteVoidMethod(PSHost clientHost) { // The clientHost can be null if the user creates a runspace object without providing // a host parameter. - if (clientHost is null) + if (clientHost == null) { return; } @@ -204,14 +204,14 @@ private RemoteRunspace GetRemoteRunspaceToClose(PSHost clientHost) // Are we a Start-PSSession enabled host? IHostSupportsInteractiveSession host = clientHost as IHostSupportsInteractiveSession; - if (host is null || !host.IsRunspacePushed) + if (host == null || !host.IsRunspacePushed) { return null; } // Now inspect the runspace. RemoteRunspace remoteRunspace = host.Runspace as RemoteRunspace; - if (remoteRunspace is null || !remoteRunspace.ShouldCloseOnPop) + if (remoteRunspace == null || !remoteRunspace.ShouldCloseOnPop) { return null; } @@ -238,7 +238,7 @@ internal RemoteHostResponse ExecuteNonVoidMethod(PSHost clientHost) { // The clientHost can be null if the user creates a runspace object without providing // a host parameter. - if (clientHost is null) + if (clientHost == null) { throw RemoteHostExceptions.NewNullClientHostException(); } @@ -283,7 +283,7 @@ private RemoteHostResponse ExecuteNonVoidMethodOnObject(object instance) /// private object SelectTargetObject(PSHost host) { - if (host is null || host.UI is null) { return null; } + if (host == null || host.UI == null) { return null; } if (_methodInfo.InterfaceType == typeof(PSHost)) { return host; } @@ -588,7 +588,7 @@ internal object SimulateExecution() private static void EncodeAndAddReturnValue(PSObject psObject, object returnValue) { // Do nothing if the return value is null. - if (returnValue is null) { return; } + if (returnValue == null) { return; } // Otherwise add the property. RemoteHostEncoder.EncodeAndAddAsProperty(psObject, RemoteDataNameStrings.MethodReturnValue, returnValue); @@ -617,7 +617,7 @@ private static void EncodeAndAddException(PSObject psObject, Exception exception private static Exception DecodeException(PSObject psObject) { object result = RemoteHostEncoder.DecodePropertyValue(psObject, RemoteDataNameStrings.MethodException, typeof(Exception)); - if (result is null) { return null; } + if (result == null) { return null; } if (result is Exception) { return (Exception)result; } diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHostEncoder.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHostEncoder.cs index 0c9528b7c80..8a60ce277a8 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHostEncoder.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHostEncoder.cs @@ -70,7 +70,7 @@ private static PSObject EncodeClassOrStruct(object obj) foreach (FieldInfo fieldInfo in fieldInfos) { object fieldValue = fieldInfo.GetValue(obj); - if (fieldValue is null) + if (fieldValue == null) { continue; } @@ -93,10 +93,10 @@ private static object DecodeClassOrStruct(PSObject psObject, Type type) foreach (PSPropertyInfo propertyInfo in psObject.Properties) { FieldInfo fieldInfo = type.GetField(propertyInfo.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); - if (propertyInfo.Value is null) { throw RemoteHostExceptions.NewDecodingFailedException(); } + if (propertyInfo.Value == null) { throw RemoteHostExceptions.NewDecodingFailedException(); } object fieldValue = DecodeObject(propertyInfo.Value, fieldInfo.FieldType); - if (fieldValue is null) { throw RemoteHostExceptions.NewDecodingFailedException(); } + if (fieldValue == null) { throw RemoteHostExceptions.NewDecodingFailedException(); } fieldInfo.SetValue(obj, fieldValue); } @@ -257,7 +257,7 @@ private static PSObject EncodeException(Exception exception) ErrorRecord errorRecord = null; IContainsErrorRecord containsErrorRecord = exception as IContainsErrorRecord; - if (containsErrorRecord is null) + if (containsErrorRecord == null) { // If this is a .NET exception then wrap in an ErrorRecord. errorRecord = new ErrorRecord(exception, "RemoteHostExecutionException", ErrorCategory.NotSpecified, null); @@ -281,7 +281,7 @@ private static PSObject EncodeException(Exception exception) private static Exception DecodeException(PSObject psObject) { ErrorRecord errorRecord = ErrorRecord.FromPSObjectForRemoting(psObject); - if (errorRecord is null) + if (errorRecord == null) { throw RemoteHostExceptions.NewDecodingErrorForErrorRecordException(); } @@ -318,7 +318,7 @@ private static FieldDescription UpcastFieldDescriptionSubclassAndDropAttributes( /// internal static object EncodeObject(object obj) { - if (obj is null) + if (obj == null) { return null; } @@ -407,7 +407,7 @@ internal static object EncodeObject(object obj) /// internal static object DecodeObject(object obj, Type type) { - if (obj is null) + if (obj == null) { return null; } @@ -512,7 +512,7 @@ internal static void EncodeAndAddAsProperty(PSObject psObject, string propertyNa { Dbg.Assert(psObject != null, "Expected psObject != null"); Dbg.Assert(propertyName != null, "Expected propertyName != null"); - if (propertyValue is null) + if (propertyValue == null) { return; } @@ -573,7 +573,7 @@ private static object[] DecodeObjectArray(PSObject psObject) /// private static PSObject EncodeObjectWithType(object obj) { - if (obj is null) + if (obj == null) { return null; } @@ -589,7 +589,7 @@ private static PSObject EncodeObjectWithType(object obj) /// private static object DecodeObjectWithType(object obj) { - if (obj is null) + if (obj == null) { return null; } @@ -744,7 +744,7 @@ private static IDictionary DecodeObjectDictionary(PSObject psObject, Type dictio /// private static T SafelyGetBaseObject(PSObject psObject) { - if (psObject is null || psObject.BaseObject is null || !(psObject.BaseObject is T)) + if (psObject == null || psObject.BaseObject == null || !(psObject.BaseObject is T)) { throw RemoteHostExceptions.NewDecodingFailedException(); } @@ -771,7 +771,7 @@ private static T SafelyCastObject(object obj) private static T SafelyGetPropertyValue(PSObject psObject, string key) { PSPropertyInfo propertyInfo = psObject.Properties[key]; - if (propertyInfo is null || propertyInfo.Value is null || !(propertyInfo.Value is T)) + if (propertyInfo == null || propertyInfo.Value == null || !(propertyInfo.Value is T)) { throw RemoteHostExceptions.NewDecodingFailedException(); } 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 b2d6e5d3e8b..bc5d47c8a83 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs @@ -99,7 +99,7 @@ internal static RemoteSessionCapability CreateServerCapability() /// internal static byte[] GetCurrentTimeZoneInByteFormat() { - if (_timeZoneInByteFormat is null) + if (_timeZoneInByteFormat == null) { Exception e = null; try @@ -231,7 +231,7 @@ internal object GetValue(HostDefaultDataId id) /// internal static HostDefaultData Create(PSHostRawUserInterface hostRawUI) { - if (hostRawUI is null) + if (hostRawUI == null) { return null; } @@ -432,7 +432,7 @@ private static void CheckHostChain(PSHost host, ref bool isHostNull, ref bool is isHostRawUINull = true; // Unwrap the host: remove outer InternalHost object. - if (host is null) + if (host == null) { // If host is null then the bools are correct. Nothing further to do here. return; @@ -447,12 +447,12 @@ private static void CheckHostChain(PSHost host, ref bool isHostNull, ref bool is isHostNull = false; // Verify that the UI is not null. - if (host.UI is null) { return; } + if (host.UI == null) { return; } isHostUINull = false; // Verify that the raw UI is not null. - if (host.UI.RawUI is null) { return; } + if (host.UI.RawUI == null) { return; } isHostRawUINull = false; } diff --git a/src/System.Management.Automation/engine/remoting/common/fragmentor.cs b/src/System.Management.Automation/engine/remoting/common/fragmentor.cs index 0fc927fe3f2..2ebe434ea04 100644 --- a/src/System.Management.Automation/engine/remoting/common/fragmentor.cs +++ b/src/System.Management.Automation/engine/remoting/common/fragmentor.cs @@ -693,7 +693,7 @@ public override int Read(byte[] buffer, int offset, int count) while (dataWritten < count) { - if (_readStream is null) + if (_readStream == null) { if (_queuedStreams.Count > 0) { @@ -781,7 +781,7 @@ private void WriteCurrentFragmentAndReset() return; } - if (_writeStream is null) + if (_writeStream == null) { _writeStream = new MemoryStream(_fragmentSize); s_trace.WriteLine("Created write stream: {0}", _writeStream.GetHashCode()); @@ -1106,7 +1106,7 @@ internal PSObject DeserializeToPSObject(Stream serializedDataStream) deserializer.Done(); } - if (result is null) + if (result == null) { // cannot be null. throw new PSRemotingDataStructureException(RemotingErrorIdStrings.DeserializedObjectIsNull); diff --git a/src/System.Management.Automation/engine/remoting/common/misc.cs b/src/System.Management.Automation/engine/remoting/common/misc.cs index 5afa294acda..e5b1f1edc04 100644 --- a/src/System.Management.Automation/engine/remoting/common/misc.cs +++ b/src/System.Management.Automation/engine/remoting/common/misc.cs @@ -15,7 +15,7 @@ internal RemoteSessionNegotiationEventArgs(RemoteSessionCapability remoteSession { Dbg.Assert(remoteSessionCapability != null, "caller should validate the parameter"); - if (remoteSessionCapability is null) + if (remoteSessionCapability == null) { throw PSTraceSource.NewArgumentNullException(nameof(remoteSessionCapability)); } @@ -48,7 +48,7 @@ internal RemoteDataEventArgs(RemoteDataObject receivedData) { Dbg.Assert(receivedData != null, "caller should validate the parameter"); - if (receivedData is null) + if (receivedData == null) { throw PSTraceSource.NewArgumentNullException(nameof(receivedData)); } @@ -312,7 +312,7 @@ internal RemoteSessionStateEventArgs(RemoteSessionStateInfo remoteSessionStateIn { Dbg.Assert(remoteSessionStateInfo != null, "caller should validate the parameter"); - if (remoteSessionStateInfo is null) + if (remoteSessionStateInfo == null) { PSTraceSource.NewArgumentNullException(nameof(remoteSessionStateInfo)); } diff --git a/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs b/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs index af48748cba8..fa1bcb7da86 100644 --- a/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs +++ b/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs @@ -244,7 +244,7 @@ private static void GetIdentifierInfo(string message, out Guid jobInstanceId, ou jobInstanceId = Guid.Empty; computerName = string.Empty; - if (message is null) return; + if (message == null) return; string[] parts = message.Split(Utils.Separators.Colon, 3); if (parts.Length != 3) return; @@ -286,7 +286,7 @@ internal void WriteStreamObject(Cmdlet cmdlet, Guid instanceId, bool overrideInq ErrorRecord errorRecord = (ErrorRecord)this.Value; RemotingErrorRecord remoteErrorRecord = errorRecord as RemotingErrorRecord; - if (remoteErrorRecord is null) + if (remoteErrorRecord == null) { // if we get a base ErrorRecord object, check if the computerName is // populated in the RecommendedAction field @@ -348,7 +348,7 @@ internal void WriteStreamObject(Cmdlet cmdlet, Guid instanceId, bool overrideInq ProgressRecord progressRecord = (ProgressRecord)Value; RemotingProgressRecord remotingProgressRecord = progressRecord as RemotingProgressRecord; - if (remotingProgressRecord is null) + if (remotingProgressRecord == null) { Guid jobInstanceId; string computerName; @@ -389,7 +389,7 @@ internal void WriteStreamObject(Cmdlet cmdlet, Guid instanceId, bool overrideInq InformationRecord informationRecord = (InformationRecord)this.Value; RemotingInformationRecord remoteInformationRecord = informationRecord as RemotingInformationRecord; - if (remoteInformationRecord is null) + if (remoteInformationRecord == null) { // if we get a base InformationRecord object, check if the computerName is // populated in the Source field @@ -496,8 +496,8 @@ internal static string CreateInformationalMessage(Guid instanceId, string messag internal static ErrorRecord AddSourceTagToError(ErrorRecord errorRecord, Guid sourceId) { - if (errorRecord is null) return null; - if (errorRecord.ErrorDetails is null) errorRecord.ErrorDetails = new ErrorDetails(string.Empty); + if (errorRecord == null) return null; + if (errorRecord.ErrorDetails == null) errorRecord.ErrorDetails = new ErrorDetails(string.Empty); errorRecord.ErrorDetails.RecommendedAction = CreateInformationalMessage(sourceId, errorRecord.ErrorDetails.RecommendedAction); return errorRecord; } diff --git a/src/System.Management.Automation/engine/remoting/common/remotingexceptions.cs b/src/System.Management.Automation/engine/remoting/common/remotingexceptions.cs index e227be6631a..72f404bce10 100644 --- a/src/System.Management.Automation/engine/remoting/common/remotingexceptions.cs +++ b/src/System.Management.Automation/engine/remoting/common/remotingexceptions.cs @@ -473,7 +473,7 @@ internal PSRemotingTransportException(Exception innerException, string resourceS protected PSRemotingTransportException(SerializationInfo info, StreamingContext context) : base(info, context) { - if (info is null) + if (info == null) { throw new PSArgumentNullException(nameof(info)); } @@ -492,7 +492,7 @@ protected PSRemotingTransportException(SerializationInfo info, StreamingContext [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) { throw new PSArgumentNullException(nameof(info)); } @@ -616,7 +616,7 @@ internal PSRemotingTransportRedirectException(Exception innerException, string r protected PSRemotingTransportRedirectException(SerializationInfo info, StreamingContext context) : base(info, context) { - if (info is null) + if (info == null) { throw new PSArgumentNullException(nameof(info)); } @@ -657,7 +657,7 @@ internal PSRemotingTransportRedirectException(string redirectLocation, PSRemotin [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) { throw new PSArgumentNullException(nameof(info)); } diff --git a/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs b/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs index 80d19320bda..9fa2233153f 100644 --- a/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs +++ b/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs @@ -726,7 +726,7 @@ internal event EventHandler EventHandler { add { - bool firstEntry = (InternalEvent is null); + bool firstEntry = (InternalEvent == null); InternalEvent += value; diff --git a/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs index a6dd940a4fc..e0dfba1cd07 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs @@ -1292,7 +1292,7 @@ internal void SendDataToClient(RemoteDataObject data, bool flush, bool rep data.Data); if (_isSerializing) { - if (_dataToBeSentQueue is null) + if (_dataToBeSentQueue == null) { _dataToBeSentQueue = new Queue>(); } @@ -1511,7 +1511,7 @@ internal static class ServerOperationHelpers /// The extracted tag converted from a base-64 string. internal static byte[] ExtractEncodedXmlElement(string xmlBuffer, string xmlTag) { - if (xmlBuffer is null || xmlTag is null) + if (xmlBuffer == null || xmlTag == null) return new byte[1]; // the inboundShellInformation is in Xml format as per the SOAP WSMan spec. diff --git a/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs b/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs index 0860207ab83..1a9642ca7c2 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs @@ -278,12 +278,12 @@ internal static ConfigurationDataFromXML Create(string initializationParameters) } // assign defaults after parsing the xml content. - if (result.MaxReceivedObjectSizeMB is null) + if (result.MaxReceivedObjectSizeMB == null) { result.MaxReceivedObjectSizeMB = BaseTransportManager.MaximumReceivedObjectSize; } - if (result.MaxReceivedCommandSizeMB is null) + if (result.MaxReceivedCommandSizeMB == null) { result.MaxReceivedCommandSizeMB = BaseTransportManager.MaximumReceivedDataSize; } @@ -526,7 +526,7 @@ private static Type LoadAndAnalyzeAssembly(string shellId, string applicationBas assemblyName, shellId); assembly = LoadSsnStateProviderAssembly(applicationBase, assemblyName); - if (assembly is null) + if (assembly == null) { throw PSTraceSource.NewArgumentException(nameof(assemblyName), RemotingErrorIdStrings.UnableToLoadAssembly, assemblyName, ConfigurationDataFromXML.INITPARAMETERSTOKEN); @@ -543,7 +543,7 @@ private static Type LoadAndAnalyzeAssembly(string shellId, string applicationBas typeToLoad, shellId); Type type = assembly.GetType(typeToLoad, true, true); - if (type is null) + if (type == null) { throw PSTraceSource.NewArgumentException(nameof(typeToLoad), RemotingErrorIdStrings.UnableToLoadType, typeToLoad, ConfigurationDataFromXML.INITPARAMETERSTOKEN); @@ -763,7 +763,7 @@ private static string Dbg.Assert(registryKey != null, "Caller should validate the registryKey parameter"); object value = registryKey.GetValue(name); - if (value is null && mandatory) + if (value == null && mandatory) { s_tracer.TraceError("Mandatory property {0} not specified for registry key {1}", name, registryKey.Name); @@ -813,13 +813,13 @@ public override InitialSessionState GetInitialSessionState(PSSenderInfo senderIn public override InitialSessionState GetInitialSessionState(PSSessionConfigurationData sessionConfigurationData, PSSenderInfo senderInfo, string configProviderId) { - if (sessionConfigurationData is null) + if (sessionConfigurationData == null) throw new ArgumentNullException(nameof(sessionConfigurationData)); - if (senderInfo is null) + if (senderInfo == null) throw new ArgumentNullException(nameof(senderInfo)); - if (configProviderId is null) + if (configProviderId == null) throw new ArgumentNullException(nameof(configProviderId)); InitialSessionState sessionState = InitialSessionState.CreateDefault2(); @@ -1122,7 +1122,7 @@ private static bool HashtableTypeValidationCallback(string key, object obj, PSCm { Hashtable hash = obj as Hashtable; - if (hash is null) + if (hash == null) { cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeHashtable, key, path)); return false; @@ -1142,7 +1142,7 @@ private static bool AliasDefinitionsTypeValidationCallback(string key, object ob { Hashtable[] hashtables = DISCPowerShellConfiguration.TryGetHashtableArray(obj); - if (hashtables is null) + if (hashtables == null) { cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeHashtableArray, key, path)); return false; @@ -1189,7 +1189,7 @@ private static bool FunctionDefinitionsTypeValidationCallback(string key, object { Hashtable[] hashtables = DISCPowerShellConfiguration.TryGetHashtableArray(obj); - if (hashtables is null) + if (hashtables == null) { cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeHashtableArray, key, path)); return false; @@ -1209,7 +1209,7 @@ private static bool FunctionDefinitionsTypeValidationCallback(string key, object return false; } - if ((hashtable[FunctionValueToken] as ScriptBlock) is null) + if ((hashtable[FunctionValueToken] as ScriptBlock) == null) { cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCKeyMustBeScriptBlock, FunctionValueToken, key, path)); return false; @@ -1241,7 +1241,7 @@ private static bool VariableDefinitionsTypeValidationCallback(string key, object { Hashtable[] hashtables = DISCPowerShellConfiguration.TryGetHashtableArray(obj); - if (hashtables is null) + if (hashtables == null) { cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeHashtableArray, key, path)); return false; @@ -1304,7 +1304,7 @@ private static bool StringTypeValidationCallback(string key, object obj, PSCmdle /// private static bool StringArrayTypeValidationCallback(string key, object obj, PSCmdlet cmdlet, string path) { - if (DISCPowerShellConfiguration.TryGetStringArray(obj) is null) + if (DISCPowerShellConfiguration.TryGetStringArray(obj) == null) { cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeStringArray, key, path)); return false; @@ -1345,7 +1345,7 @@ private static bool IntegerTypeValidationCallback(string key, object obj, PSCmdl /// private static bool StringOrHashtableArrayTypeValidationCallback(string key, object obj, PSCmdlet cmdlet, string path) { - if (DISCPowerShellConfiguration.TryGetObjectsOfType(obj, new Type[] { typeof(string), typeof(Hashtable) }) is null) + if (DISCPowerShellConfiguration.TryGetObjectsOfType(obj, new Type[] { typeof(string), typeof(Hashtable) }) == null) { cmdlet.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeStringOrHashtableArrayInFile, key, path)); return false; @@ -1498,7 +1498,7 @@ internal static bool VerifyConfigTable(Hashtable table, PSCmdlet cmdlet, string /// private static void ValidatePS1XMLExtension(string key, string[] paths, string filePath) { - if (paths is null) + if (paths == null) { return; } @@ -1525,7 +1525,7 @@ private static void ValidatePS1XMLExtension(string key, string[] paths, string f /// private static void ValidatePS1OrPSM1Extension(string key, string[] paths, string filePath) { - if (paths is null) + if (paths == null) { return; } @@ -1605,7 +1605,7 @@ internal static void ValidateAbsolutePaths(SessionState state, Hashtable table, /// internal static void ValidateAbsolutePath(SessionState state, string key, string[] paths, string filePath) { - if (paths is null) + if (paths == null) { return; } @@ -1647,7 +1647,7 @@ internal static void ValidateRoleDefinitions(IDictionary roleDefinitions) // IDictionary roleDefinition = roleDefinitions[roleKey] as IDictionary; - if (roleDefinition is null) + if (roleDefinition == null) { var invalidOperationEx = new PSInvalidOperationException( StringUtil.Format(RemotingErrorIdStrings.InvalidRoleValue, roleKey)); @@ -1659,7 +1659,7 @@ internal static void ValidateRoleDefinitions(IDictionary roleDefinitions) { // Ensure each role capability key is valid. string roleCapabilityKey = key as string; - if (roleCapabilityKey is null) + if (roleCapabilityKey == null) { var invalidOperationEx = new PSInvalidOperationException( string.Format(RemotingErrorIdStrings.InvalidRoleCapabilityKeyType, key.GetType().FullName)); @@ -1709,7 +1709,7 @@ internal Hashtable ConfigHash internal DISCPowerShellConfiguration(string configFile, Func roleVerifier) { _configFile = configFile; - if (roleVerifier is null) + if (roleVerifier == null) { roleVerifier = (role) => false; } @@ -1752,7 +1752,7 @@ private void MergeRoleRulesIntoConfigHash(Func roleVerifier) { // Extract the 'Roles' hashtable IDictionary roleEntry = _configHash[ConfigFileConstants.RoleDefinitions] as IDictionary; - if (roleEntry is null) + if (roleEntry == null) { string message = StringUtil.Format(RemotingErrorIdStrings.InvalidRoleEntry, _configHash["Roles"].GetType().FullName); PSInvalidOperationException ioe = new PSInvalidOperationException(message); @@ -1772,7 +1772,7 @@ private void MergeRoleRulesIntoConfigHash(Func roleVerifier) // Extract their specific configuration IDictionary roleCustomizations = roleEntry[role] as IDictionary; - if (roleCustomizations is null) + if (roleCustomizations == null) { string message = StringUtil.Format(RemotingErrorIdStrings.InvalidRoleValue, role.ToString()); PSInvalidOperationException ioe = new PSInvalidOperationException(message); @@ -2043,7 +2043,7 @@ public override InitialSessionState GetInitialSessionState(PSSenderInfo senderIn { object[] modules = TryGetObjectsOfType(_configHash[ConfigFileConstants.ModulesToImport], new Type[] { typeof(string), typeof(Hashtable) }); - if ((_configHash[ConfigFileConstants.ModulesToImport] != null) && (modules is null)) + if ((_configHash[ConfigFileConstants.ModulesToImport] != null) && (modules == null)) { string message = StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeStringOrHashtableArray, ConfigFileConstants.ModulesToImport); @@ -2106,7 +2106,7 @@ public override InitialSessionState GetInitialSessionState(PSSenderInfo senderIn object[] cmdlets = TryGetObjectsOfType(_configHash[ConfigFileConstants.VisibleCmdlets], new Type[] { typeof(string), typeof(Hashtable) }); - if (cmdlets is null) + if (cmdlets == null) { string message = StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeStringOrHashtableArray, ConfigFileConstants.VisibleCmdlets); @@ -2199,7 +2199,7 @@ public override InitialSessionState GetInitialSessionState(PSSenderInfo senderIn object[] functions = TryGetObjectsOfType(_configHash[ConfigFileConstants.VisibleFunctions], new Type[] { typeof(string), typeof(Hashtable) }); - if (functions is null) + if (functions == null) { string message = StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeStringOrHashtableArray, ConfigFileConstants.VisibleFunctions); @@ -2460,7 +2460,7 @@ private static void ProcessVisibleCommands(InitialSessionState iss, object[] com foreach (object commandObject in commands) { - if (commandObject is null) + if (commandObject == null) { continue; } @@ -2516,7 +2516,7 @@ private static void ProcessCommandModification(Dictionary com } // Validate that we got the Name and Parameters keys - if ((commandName is null) || (parameters is null)) + if ((commandName == null) || (parameters == null)) { string hashtableKey = commandName; if (string.IsNullOrEmpty(hashtableKey)) @@ -2547,7 +2547,7 @@ private static void ProcessCommandModification(Dictionary com // Ensure we have the hashtable representing the current parameter being modified string parameterName = parameter["Name"].ToString(); Hashtable currentParameterModification = parameterModifications[parameterName] as Hashtable; - if (currentParameterModification is null) + if (currentParameterModification == null) { currentParameterModification = new Hashtable(StringComparer.OrdinalIgnoreCase); parameterModifications[parameterName] = currentParameterModification; @@ -2748,7 +2748,7 @@ private bool IsNonDefaultVisibilitySpecified(string configFileKey) string[] commands = DISCPowerShellConfiguration.TryGetStringArray(_configHash[configFileKey]); - if ((commands is null) || (commands.Length == 0)) + if ((commands == null) || (commands.Length == 0)) { return false; } @@ -2793,7 +2793,7 @@ internal static Hashtable[] TryGetHashtableArray(object hashObj) // 1. Direct conversion Hashtable[] hashArray = hashObj as Hashtable[]; - if (hashArray is null) + if (hashArray == null) { // 2. Convert from object array object[] objArray = hashObj as object[]; @@ -2806,7 +2806,7 @@ internal static Hashtable[] TryGetHashtableArray(object hashObj) { Hashtable hash = objArray[i] as Hashtable; - if (hash is null) + if (hash == null) { return null; } @@ -2828,7 +2828,7 @@ internal static string[] TryGetStringArray(object hashObj) { object[] objs = hashObj as object[]; - if (objs is null) + if (objs == null) { // Scalar case object obj = hashObj as object; @@ -2856,7 +2856,7 @@ internal static string[] TryGetStringArray(object hashObj) internal static T[] TryGetObjectsOfType(object hashObj, IEnumerable types) where T : class { object[] objs = hashObj as object[]; - if (objs is null) + if (objs == null) { // Scalar case object obj = hashObj; diff --git a/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs index a692267cc6d..bc39b8f6937 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs @@ -553,7 +553,7 @@ internal override void CloseAsync() // will know that we are closing. isClosed = true; - if (stdInWriter is null) + if (stdInWriter == null) { // this will happen if CloseAsync() is called // before ConnectAsync()..in which case we @@ -965,7 +965,7 @@ private void OnCommandCreationPacketReceived(Guid psGuid) private void OnCommandCreationAckReceived(Guid psGuid) { OutOfProcessClientCommandTransportManager cmdTM = GetCommandTransportManager(psGuid); - if (cmdTM is null) + if (cmdTM == null) { throw new PSRemotingTransportException(PSRemotingErrorId.IPCUnknownCommandGuid, RemotingErrorIdStrings.IPCUnknownCommandGuid, @@ -1263,7 +1263,7 @@ protected override void CleanupConnection() private void KillServerProcess() { - if (_serverProcess is null) + if (_serverProcess == null) { // this can happen if Dispose is called before ConnectAsync() return; @@ -1371,7 +1371,7 @@ protected void ProcessReaderThread(object state) while (true) { string data = reader.ReadLine(); - if (data is null) + if (data == null) { // End of stream indicates the target process was lost. // Raise transport exception to invalidate the client remote runspace. @@ -1443,7 +1443,7 @@ internal VMHyperVSocketClientSessionTransportManager( string configurationName) : base(runspaceId, cryptoHelper) { - if (connectionInfo is null) + if (connectionInfo == null) { throw new PSArgumentNullException(nameof(connectionInfo)); } @@ -1452,7 +1452,7 @@ internal VMHyperVSocketClientSessionTransportManager( _vmGuid = vmGuid; _configurationName = configurationName; - if (connectionInfo.Credential is null) + if (connectionInfo.Credential == null) { _networkCredential = CredentialCache.DefaultNetworkCredentials; } @@ -1526,7 +1526,7 @@ internal ContainerHyperVSocketClientSessionTransportManager( Guid targetGuid) : base(runspaceId, cryptoHelper) { - if (connectionInfo is null) + if (connectionInfo == null) { throw new PSArgumentNullException(nameof(connectionInfo)); } @@ -1590,7 +1590,7 @@ internal SSHClientSessionTransportManager( PSRemotingCryptoHelper cryptoHelper) : base(runspaceId, cryptoHelper) { - if (connectionInfo is null) { throw new PSArgumentException("connectionInfo"); } + if (connectionInfo == null) { throw new PSArgumentException("connectionInfo"); } _connectionInfo = connectionInfo; } @@ -1745,7 +1745,7 @@ private static string ReadError(StreamReader reader) // Blocking read from StdError stream string error = reader.ReadLine(); - if (error is null) + if (error == null) { // Stream is closed unexpectedly. throw new PSInvalidOperationException(RemotingErrorIdStrings.SSHAbruptlyTerminated); @@ -1812,7 +1812,7 @@ private void ProcessReaderThread(object state) while (true) { string data = reader.ReadLine(); - if (data is null) + if (data == null) { // End of stream indicates that the SSH transport is broken. // SSH will return the appropriate error in StdErr stream so @@ -1875,7 +1875,7 @@ internal NamedPipeClientSessionTransportManagerBase( string threadName) : base(runspaceId, cryptoHelper) { - if (connectionInfo is null) + if (connectionInfo == null) { throw new PSArgumentNullException(nameof(connectionInfo)); } @@ -1938,7 +1938,7 @@ private void ProcessReaderThread(object state) while (true) { string data = reader.ReadLine(); - if (data is null) + if (data == null) { // End of stream indicates the target process was lost. // Raise transport exception to invalidate the client remote runspace. @@ -2001,7 +2001,7 @@ internal NamedPipeClientSessionTransportManager( PSRemotingCryptoHelper cryptoHelper) : base(connectionInfo, runspaceId, cryptoHelper, _threadName) { - if (connectionInfo is null) + if (connectionInfo == null) { throw new PSArgumentNullException(nameof(connectionInfo)); } @@ -2069,7 +2069,7 @@ internal ContainerNamedPipeClientSessionTransportManager( PSRemotingCryptoHelper cryptoHelper) : base(connectionInfo, runspaceId, cryptoHelper, _threadName) { - if (connectionInfo is null) + if (connectionInfo == null) { throw new PSArgumentNullException(nameof(connectionInfo)); } diff --git a/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs b/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs index a8a99d4e072..1341c9e0a83 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs @@ -51,7 +51,7 @@ public void GetObjectData(SerializationInfo info, StreamingContext context) /// private PSSenderInfo(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) { return; } @@ -68,7 +68,7 @@ private PSSenderInfo(SerializationInfo info, StreamingContext context) return; } - if (serializedData is null) + if (serializedData == null) { return; } diff --git a/src/System.Management.Automation/engine/remoting/fanin/PSSessionConfigurationData.cs b/src/System.Management.Automation/engine/remoting/fanin/PSSessionConfigurationData.cs index 51932ead4c6..17aac7adfdf 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/PSSessionConfigurationData.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/PSSessionConfigurationData.cs @@ -222,8 +222,8 @@ private void Update(string optionName, string optionValue) private void CreateCollectionIfNecessary() { - if (_modulesToImport is null) _modulesToImport = new List(); - if (_modulesToImportInternal is null) _modulesToImportInternal = new List(); + if (_modulesToImport == null) _modulesToImport = new List(); + if (_modulesToImportInternal == null) _modulesToImportInternal = new List(); } private const string SessionConfigToken = "SessionConfigurationData"; diff --git a/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs b/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs index 8612fbf0cdf..8ddd0eb8cb1 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs @@ -223,13 +223,13 @@ internal byte[] ReadOrRegisterCallback(OnDataAvailableCallback callback, result = _dataToBeSent[(int)DataPriorityType.PromptResponse].ReadOrRegisterCallback(_onSendCollectionDataAvailable); priorityType = DataPriorityType.PromptResponse; - if (result is null) + if (result == null) { result = _dataToBeSent[(int)DataPriorityType.Default].ReadOrRegisterCallback(_onSendCollectionDataAvailable); priorityType = DataPriorityType.Default; } // no data to return..so register the callback. - if (result is null) + if (result == null) { // register callback. _onDataAvailableCallback = callback; diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs index 6ed2312e8f4..d5eb990ec57 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs @@ -196,7 +196,7 @@ internal void CreateShell( "CreateShell: Create a new shell in the plugin context", string.Empty); - if (requestDetails is null) + if (requestDetails == null) { // Nothing can be done because requestDetails are required to report operation complete PSEtwLog.LogAnalyticInformational(PSEventId.ReportOperationComplete, @@ -212,8 +212,8 @@ internal void CreateShell( return; } - if ((requestDetails.senderDetails is null) || - (requestDetails.operationInfo is null)) + if ((requestDetails.senderDetails == null) || + (requestDetails.operationInfo == null)) { ReportOperationComplete( requestDetails, @@ -225,7 +225,7 @@ internal void CreateShell( return; } - if (startupInfo is null) + if (startupInfo == null) { ReportOperationComplete( requestDetails, @@ -310,7 +310,7 @@ internal void CreateShell( extraInfo, serverTransportMgr); - if (remoteShellSession is null) + if (remoteShellSession == null) { WSManPluginInstance.ReportWSManOperationComplete( requestDetails, @@ -319,7 +319,7 @@ internal void CreateShell( } context = new WSManPluginOperationShutdownContext(pluginContext, requestDetails.unmanagedHandle, IntPtr.Zero, false); - if (context is null) + if (context == null) { ReportOperationComplete(requestDetails, WSManPluginErrorCodes.OutOfMemory); return; @@ -423,7 +423,7 @@ internal void CreateShell( context, -1, // INFINITE true); // TODO: Do I need to worry not being able to set missing WT_TRANSFER_IMPERSONATION? - if (mgdShellSession.registeredShutDownWaitHandle is null) + if (mgdShellSession.registeredShutDownWaitHandle == null) { isRegisterWaitForSingleObjectSucceeded = false; } @@ -494,7 +494,7 @@ internal void CloseShellOperation( context.isReceiveOperation.ToString()); WSManPluginShellSession mgdShellSession = GetFromActiveShellSessions(context.shellContext); - if (mgdShellSession is null) + if (mgdShellSession == null) { // this should never be the case. this will protect the service. // Dbg.Assert(false, "context.shellContext not matched"); @@ -532,7 +532,7 @@ internal void CloseCommandOperation( context.isReceiveOperation.ToString()); WSManPluginShellSession mgdShellSession = GetFromActiveShellSessions(context.shellContext); - if (mgdShellSession is null) + if (mgdShellSession == null) { // this should never be the case. this will protect the service. // Dbg.Assert(false, "context.shellContext not matched"); @@ -644,7 +644,7 @@ private bool validateIncomingContexts( IntPtr shellContext, string inputFunctionName) { - if (requestDetails is null) + if (requestDetails == null) { // Nothing can be done because requestDetails are required to report operation complete PSEtwLog.LogAnalyticInformational( @@ -716,7 +716,7 @@ internal void CreateCommand( ((IntPtr)shellContext).ToString(), requestDetails.ToString()); WSManPluginShellSession mgdShellSession = GetFromActiveShellSessions(shellContext); - if (mgdShellSession is null) + if (mgdShellSession == null) { ReportOperationComplete( requestDetails, @@ -743,7 +743,7 @@ internal void StopCommand( IntPtr shellContext, IntPtr commandContext) { - if (requestDetails is null) + if (requestDetails == null) { // Nothing can be done because requestDetails are required to report operation complete PSEtwLog.LogAnalyticInformational( @@ -772,7 +772,7 @@ internal void StopCommand( requestDetails.ToString()); WSManPluginShellSession mgdShellSession = GetFromActiveShellSessions(shellContext); - if (mgdShellSession is null) + if (mgdShellSession == null) { ReportOperationComplete( requestDetails, @@ -783,7 +783,7 @@ internal void StopCommand( } WSManPluginCommandSession mgdCommandSession = mgdShellSession.GetCommandSession(commandContext); - if (mgdCommandSession is null) + if (mgdCommandSession == null) { ReportOperationComplete( requestDetails, @@ -860,7 +860,7 @@ internal void ConnectShellOrCommand( requestDetails.ToString()); WSManPluginShellSession mgdShellSession = GetFromActiveShellSessions(shellContext); - if (mgdShellSession is null) + if (mgdShellSession == null) { ReportOperationComplete( requestDetails, @@ -878,7 +878,7 @@ internal void ConnectShellOrCommand( // this connect is on a command WSManPluginCommandSession mgdCmdSession = mgdShellSession.GetCommandSession(commandContext); - if (mgdCmdSession is null) + if (mgdCmdSession == null) { ReportOperationComplete( requestDetails, @@ -952,7 +952,7 @@ internal void SendOneItemToShellOrCommand( requestDetails.ToString()); WSManPluginShellSession mgdShellSession = GetFromActiveShellSessions(shellContext); - if (mgdShellSession is null) + if (mgdShellSession == null) { ReportOperationComplete( requestDetails, @@ -972,7 +972,7 @@ internal void SendOneItemToShellOrCommand( // the data is destined for command. WSManPluginCommandSession mgdCmdSession = mgdShellSession.GetCommandSession(commandContext); - if (mgdCmdSession is null) + if (mgdCmdSession == null) { ReportOperationComplete( requestDetails, @@ -1047,7 +1047,7 @@ internal void EnableShellOrCommandToSendDataToClient( requestDetails.ToString()); WSManPluginShellSession mgdShellSession = GetFromActiveShellSessions(shellContext); - if (mgdShellSession is null) + if (mgdShellSession == null) { ReportOperationComplete( requestDetails, @@ -1059,7 +1059,7 @@ internal void EnableShellOrCommandToSendDataToClient( } WSManPluginOperationShutdownContext ctxtToReport = new WSManPluginOperationShutdownContext(pluginContext, shellContext, IntPtr.Zero, true); - if (ctxtToReport is null) + if (ctxtToReport == null) { ReportOperationComplete(requestDetails, WSManPluginErrorCodes.OutOfMemory); return; @@ -1088,7 +1088,7 @@ internal void EnableShellOrCommandToSendDataToClient( ctxtToReport.commandContext = commandContext; WSManPluginCommandSession mgdCmdSession = mgdShellSession.GetCommandSession(commandContext); - if (mgdCmdSession is null) + if (mgdCmdSession == null) { ReportOperationComplete( requestDetails, @@ -1310,12 +1310,12 @@ internal static void PerformWSManPluginShell( WSManPluginInstance pluginToUse = GetFromActivePlugins(pluginContext); - if (pluginToUse is null) + if (pluginToUse == null) { lock (s_activePlugins) { pluginToUse = GetFromActivePlugins(pluginContext); - if (pluginToUse is null) + if (pluginToUse == null) { // create a new plugin WSManPluginInstance mgdPlugin = new WSManPluginInstance(); @@ -1369,7 +1369,7 @@ internal static void PerformWSManPluginCommand( WSManPluginInstance pluginToUse = GetFromActivePlugins(pluginContext); - if (pluginToUse is null) + if (pluginToUse == null) { ReportOperationComplete( requestDetails, @@ -1422,7 +1422,7 @@ internal static void PerformWSManPluginConnect( WSManPluginInstance pluginToUse = GetFromActivePlugins(pluginContext); - if (pluginToUse is null) + if (pluginToUse == null) { ReportOperationComplete( requestDetails, @@ -1476,7 +1476,7 @@ internal static void PerformWSManPluginSend( WSManPluginInstance pluginToUse = GetFromActivePlugins(pluginContext); - if (pluginToUse is null) + if (pluginToUse == null) { ReportOperationComplete( requestDetails, @@ -1521,7 +1521,7 @@ internal static void PerformWSManPluginReceive( WSManPluginInstance pluginToUse = GetFromActivePlugins(pluginContext); - if (pluginToUse is null) + if (pluginToUse == null) { ReportOperationComplete( requestDetails, @@ -1596,7 +1596,7 @@ internal static void PerformWSManPluginSignal( // we got crtl_c (stop) message from client. so stop powershell WSManPluginInstance pluginToUse = GetFromActivePlugins(pluginContext); - if (pluginToUse is null) + if (pluginToUse == null) { ReportOperationComplete( request, @@ -1634,7 +1634,7 @@ internal static void PerformCloseOperation( WSManPluginInstance pluginToUse = GetFromActivePlugins(context.pluginContext); - if (pluginToUse is null) + if (pluginToUse == null) { return; } @@ -1660,7 +1660,7 @@ internal static void PerformShutdown( { WSManPluginInstance pluginToUse = GetFromActivePlugins(pluginContext); - if (pluginToUse is null) + if (pluginToUse == null) { return; } diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs index 2eb657bf0dc..ed5bf0a4a3e 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs @@ -713,7 +713,7 @@ public static void PSPluginOperationShutdownCallback( object operationContext, bool timedOut) { - if (operationContext is null) + if (operationContext == null) { return; } diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs index 631a0c1571e..f4dabc11558 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs @@ -142,7 +142,7 @@ internal void SendOneItemToSession( return; } - if (inboundData is null) + if (inboundData == null) { // no data is supplied..just ignore. WSManPluginInstance.ReportOperationComplete( @@ -200,7 +200,7 @@ internal bool EnableSessionToSendDataToClient( return false; } - if ((streamSet is null) || + if ((streamSet == null) || (1 != streamSet.streamIDsCount)) { // only "stdout" is the supported output stream. @@ -271,7 +271,7 @@ internal void ReportContext() shutDownContext, -1, // INFINITE true); // TODO: Do I need to worry not being able to set missing WT_TRANSFER_IMPERSONATION? - if (this.registeredShutDownWaitHandle is null) + if (this.registeredShutDownWaitHandle == null) { isRegisterWaitForSingleObjectFailed = true; registeredShutdownNotification = 0; @@ -440,7 +440,7 @@ internal override void ExecuteConnect( int flags, // in WSManNativeApi.WSManData_UnToMan inboundConnectInformation) // in optional { - if (inboundConnectInformation is null) + if (inboundConnectInformation == null) { WSManPluginInstance.ReportOperationComplete( requestDetails, @@ -562,7 +562,7 @@ internal void CloseCommandOperation( WSManPluginOperationShutdownContext context) { WSManPluginCommandSession mgdCmdSession = GetCommandSession(context.commandContext); - if (mgdCmdSession is null) + if (mgdCmdSession == null) { // this should never be the case. this will protect the service. return; diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginTransportManager.cs index 3edfecd5e6e..a02f6623e0a 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginTransportManager.cs @@ -343,7 +343,7 @@ internal bool EnableTransportManagerSendDataToClient( _shutDownContext, -1, // INFINITE true); // TODO: Do I need to worry not being able to set missing WT_TRANSFER_IMPERSONATION? - if (_registeredShutDownWaitHandle is null) + if (_registeredShutDownWaitHandle == null) { isRegisterWaitForSingleObjectSucceeded = false; } diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs index 33c96b5d5d4..1fad7ccb3e8 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs @@ -913,7 +913,7 @@ internal override void ConnectAsync() ReceivedDataCollection.PrepareForStreamConnect(); // additional content with connect shell call. Negotiation and connect related messages // should be included in payload - if (_openContent is null) + if (_openContent == null) { DataPriorityType additionalDataType; byte[] additionalData = dataToBeSent.ReadOrRegisterCallback(null, out additionalDataType); @@ -1068,7 +1068,7 @@ internal override void CreateAsync() // additional content with create shell call. Piggy back first fragment from // the dataToBeSent buffer. - if (_openContent is null) + if (_openContent == null) { DataPriorityType additionalDataType; byte[] additionalData = dataToBeSent.ReadOrRegisterCallback(null, out additionalDataType); @@ -1482,7 +1482,7 @@ private void Initialize(Uri connectionUri, WSManConnectionInfo connectionInfo) { result = WSManNativeApi.WSManCreateSession(WSManAPIData.WSManAPIHandle, connectionStr, 0, authCredentials.GetMarshalledObject(), - (proxyInfo is null) ? IntPtr.Zero : (IntPtr)proxyInfo, + (proxyInfo == null) ? IntPtr.Zero : (IntPtr)proxyInfo, ref _wsManSessionHandle); } finally @@ -2614,7 +2614,7 @@ private void CloseSessionAndClearResources() private void DisposeWSManAPIDataAsync() { WSManAPIDataCommon tempWSManApiData = WSManAPIData; - if (tempWSManApiData is null) { return; } + if (tempWSManApiData == null) { return; } WSManAPIData = null; @@ -3060,7 +3060,7 @@ internal override void CreateAsync() 0, PowershellInstanceId.ToString().ToUpperInvariant(), // WSManRunsShellCommand doesn't accept empty string "". - (_cmdLine is null || _cmdLine.Length == 0) ? " " : (_cmdLine.Length <= 256 ? _cmdLine : _cmdLine.Substring(0, 255)), + (_cmdLine == null || _cmdLine.Length == 0) ? " " : (_cmdLine.Length <= 256 ? _cmdLine : _cmdLine.Substring(0, 255)), argSet, IntPtr.Zero, _createCmdCompleted, @@ -3979,7 +3979,7 @@ private void OnDataAvailableCallback(byte[] data, DataPriorityType priorityType) Dbg.Assert(data != null, "data cannot be null in the data available callback"); tracer.WriteLine("Received data from dataToBeSent store."); - Dbg.Assert(_chunkToSend is null, "data callback received while a chunk is pending to be sent"); + Dbg.Assert(_chunkToSend == null, "data callback received while a chunk is pending to be sent"); _chunkToSend = new SendDataChunk(data, priorityType); SendOneItem(); } diff --git a/src/System.Management.Automation/engine/remoting/server/OutOfProcServerMediator.cs b/src/System.Management.Automation/engine/remoting/server/OutOfProcServerMediator.cs index cbcfa470739..67817c8c6e2 100644 --- a/src/System.Management.Automation/engine/remoting/server/OutOfProcServerMediator.cs +++ b/src/System.Management.Automation/engine/remoting/server/OutOfProcServerMediator.cs @@ -348,7 +348,7 @@ protected void Start(string initialCommand, PSRemotingCryptoHelperServer cryptoH string data = originalStdIn.ReadLine(); lock (_syncObject) { - if (sessionTM is null) + if (sessionTM == null) { sessionTM = CreateSessionTransportManager(configurationName, cryptoHelper, workingDirectory); } @@ -600,7 +600,7 @@ private NamedPipeProcessMediator() : base(false) { } private NamedPipeProcessMediator( RemoteSessionNamedPipeServer namedPipeServer) : base(false) { - if (namedPipeServer is null) + if (namedPipeServer == null) { throw new PSArgumentNullException(nameof(namedPipeServer)); } diff --git a/src/System.Management.Automation/engine/remoting/server/ServerMethodExecutor.cs b/src/System.Management.Automation/engine/remoting/server/ServerMethodExecutor.cs index aa10265ec9a..0c0fb0a0c42 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerMethodExecutor.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerMethodExecutor.cs @@ -136,7 +136,7 @@ internal T ExecuteMethod(RemoteHostMethodId methodId, object[] parameters) RemoteHostResponse remoteHostResponse = _serverDispatchTable.GetResponse(callId, null); // Null means that the response PSObject was not received and there was an error. - if (remoteHostResponse is null) + if (remoteHostResponse == null) { throw RemoteHostExceptions.NewRemoteHostCallFailedException(methodId); } diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs index 5107ab274b0..921f9f456f1 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs @@ -317,7 +317,7 @@ public override bool IsRunspacePushed /// RemoteRunspace. public override void PushRunspace(Runspace runspace) { - if (_debugger is null) + if (_debugger == null) { throw new PSInvalidOperationException(RemotingErrorIdStrings.ServerDriverRemoteHostNoDebuggerToPush); } @@ -328,7 +328,7 @@ public override void PushRunspace(Runspace runspace) } RemoteRunspace remoteRunspace = runspace as RemoteRunspace; - if (remoteRunspace is null) + if (remoteRunspace == null) { throw new PSInvalidOperationException(RemotingErrorIdStrings.ServerDriverRemoteHostNotRemoteRunspace); } @@ -411,7 +411,7 @@ internal bool PropagatePop private void AddPSEditForRunspace(RemoteRunspace remoteRunspace) { - if (remoteRunspace.Events is null) { return; } + if (remoteRunspace.Events == null) { return; } // Add event handler. remoteRunspace.Events.ReceivedEvents.PSEventReceived += HandleRemoteSessionForwardedEvent; @@ -431,7 +431,7 @@ private void AddPSEditForRunspace(RemoteRunspace remoteRunspace) private void RemovePSEditFromRunspace(RemoteRunspace remoteRunspace) { - if (remoteRunspace.Events is null) { return; } + if (remoteRunspace.Events == null) { return; } // It is possible for the popped runspace to be in a bad state after an error. if ((remoteRunspace.RunspaceStateInfo.State != RunspaceState.Opened) || (remoteRunspace.RunspaceAvailability != RunspaceAvailability.Available)) @@ -457,7 +457,7 @@ private void RemovePSEditFromRunspace(RemoteRunspace remoteRunspace) private void HandleRemoteSessionForwardedEvent(object sender, PSEventArgs args) { - if ((Runspace is null) || (Runspace.Events is null)) { return; } + if ((Runspace == null) || (Runspace.Events == null)) { return; } // Forward events from nested pushed session to parent session. try diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs index e7f4e08a500..1a709b11246 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs @@ -343,7 +343,7 @@ public override void SetBufferContents(Coordinates origin, BufferCell[,] content // to keep the other overload in sync: LengthInBufferCells(string, int) public override int LengthInBufferCells(string source) { - if (source is null) + if (source == null) { throw new ArgumentNullException(nameof(source)); } @@ -354,7 +354,7 @@ public override int LengthInBufferCells(string source) // more performant than the default implementation provided by PSHostRawUserInterface public override int LengthInBufferCells(string source, int offset) { - if (source is null) + if (source == null) { throw new ArgumentNullException(nameof(source)); } diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs index 36e11e2d386..72e7db24ae5 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs @@ -108,7 +108,7 @@ internal void ProcessConnect() /// Data received. internal void ProcessReceivedData(RemoteDataObject receivedData) { - if (receivedData is null) + if (receivedData == null) { throw PSTraceSource.NewArgumentNullException(nameof(receivedData)); } @@ -615,7 +615,7 @@ internal void ProcessConnect() /// Data received. internal void ProcessReceivedData(RemoteDataObject receivedData) { - if (receivedData is null) + if (receivedData == null) { throw PSTraceSource.NewArgumentNullException(nameof(receivedData)); } diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs index 44c7f88feef..10814c3ea2b 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs @@ -267,7 +267,7 @@ internal void Start() internal void SendApplicationPrivateDataToClient() { // Include Debug mode information. - if (_applicationPrivateData is null) + if (_applicationPrivateData == null) { _applicationPrivateData = new PSPrimitiveDictionary(); } @@ -382,7 +382,7 @@ internal void Close() /// public void EnterNestedPipeline() { - if (_driverNestedInvoker is null) + if (_driverNestedInvoker == null) { throw new PSNotSupportedException(RemotingErrorIdStrings.NestedPipelineNotSupported); } @@ -396,7 +396,7 @@ public void EnterNestedPipeline() /// public void ExitNestedPipeline() { - if (_driverNestedInvoker is null) + if (_driverNestedInvoker == null) { throw new PSNotSupportedException(RemotingErrorIdStrings.NestedPipelineNotSupported); } @@ -455,7 +455,7 @@ private void HandleRunspaceCreatedForTypeTable(object sender, RunspaceCreatedEve private void SetupRemoteDebugger(Runspace runspace) { CmdletInfo cmdletInfo = runspace.ExecutionContext.SessionState.InvokeCommand.GetCmdlet(ServerRemoteDebugger.SetPSBreakCommandText); - if (cmdletInfo is null) + if (cmdletInfo == null) { if ((runspace.ExecutionContext.LanguageMode != PSLanguageMode.FullLanguage) && (!runspace.ExecutionContext.UseFullLanguageModeInDebugger)) @@ -1134,7 +1134,7 @@ private void HandleResetRunspaceState(object sender, RemoteDataEventArgs 1)) + if ((runspaceToReset == null) || (RunspacePool.GetMaxRunspaces() > 1)) { return false; } @@ -1310,7 +1310,7 @@ private static PreProcessCommandResult PreProcessDebuggerCommand( return PreProcessCommandResult.ValidNotProcessed; } - if ((command.Parameters is null) || (command.Parameters.Count == 0) || + if ((command.Parameters == null) || (command.Parameters.Count == 0) || (!command.Parameters[0].Name.Equals("ResumeAction", StringComparison.OrdinalIgnoreCase))) { throw new PSArgumentException("ResumeAction"); @@ -1338,7 +1338,7 @@ private static PreProcessCommandResult PreProcessDebuggerCommand( // __Set-PSDebugMode private virtual command. // DebugModes enum input parameter. // Returns void. - if ((command.Parameters is null) || (command.Parameters.Count == 0) || + if ((command.Parameters == null) || (command.Parameters.Count == 0) || (!command.Parameters[0].Name.Equals("Mode", StringComparison.OrdinalIgnoreCase))) { throw new PSArgumentException("Mode"); @@ -1366,7 +1366,7 @@ private static PreProcessCommandResult PreProcessDebuggerCommand( // __Set-PSDebuggerStepMode private virtual command. // Boolean Enabled input parameter. // Returns void. - if ((command.Parameters is null) || (command.Parameters.Count == 0) || + if ((command.Parameters == null) || (command.Parameters.Count == 0) || (!command.Parameters[0].Name.Equals("Enabled", StringComparison.OrdinalIgnoreCase))) { throw new PSArgumentException("Enabled"); @@ -1381,7 +1381,7 @@ private static PreProcessCommandResult PreProcessDebuggerCommand( // __Set-PSUnhandledBreakpointMode private virtual command. // UnhandledBreakpointMode input parameter. // Returns void. - if ((command.Parameters is null) || (command.Parameters.Count == 0) || + if ((command.Parameters == null) || (command.Parameters.Count == 0) || (!command.Parameters[0].Name.Equals("UnhandledBreakpointMode", StringComparison.OrdinalIgnoreCase))) { throw new PSArgumentException("UnhandledBreakpointMode"); @@ -1434,7 +1434,7 @@ private static PreProcessCommandResult PreProcessDebuggerCommand( // Returns Breakpoint object(s). TryGetParameter(command, "Breakpoint", out Breakpoint breakpoint); TryGetParameter(command, "BreakpointList", out ArrayList breakpoints); - if (breakpoint is null && breakpoints is null) + if (breakpoint == null && breakpoints == null) { throw new PSArgumentException(DebuggerStrings.BreakpointOrBreakpointListNotSpecified); } @@ -1484,7 +1484,7 @@ private static PreProcessCommandResult PreProcessDebuggerCommand( Breakpoint breakpoint = serverRemoteDebugger.GetBreakpoint(breakpointId, runspaceId); preProcessOutput.Add( - breakpoint is null + breakpoint == null ? false : serverRemoteDebugger.RemoveBreakpoint(breakpoint, runspaceId)); @@ -1834,17 +1834,17 @@ internal ServerRemoteDebugger( Runspace runspace, Debugger debugger) { - if (driverInvoker is null) + if (driverInvoker == null) { throw new PSArgumentNullException(nameof(driverInvoker)); } - if (runspace is null) + if (runspace == null) { throw new PSArgumentNullException(nameof(runspace)); } - if (debugger is null) + if (debugger == null) { throw new PSArgumentNullException(nameof(debugger)); } @@ -2002,7 +2002,7 @@ public override DebuggerCommandResults ProcessCommand(PSCommand command, PSDataC StringUtil.Format(DebuggerStrings.CannotProcessDebuggerCommandNotStopped)); } - if (_processCommandCompleteEvent is null) + if (_processCommandCompleteEvent == null) { _processCommandCompleteEvent = new ManualResetEventSlim(false); } @@ -2525,7 +2525,7 @@ private void EnterDebugMode(bool isNestedStop) { // Blocking call for nested debugger execution (Debug-Runspace) stop events. // The root debugger never makes two EnterDebugMode calls without an ExitDebugMode. - if (_nestedDebugStopCompleteEvent is null) + if (_nestedDebugStopCompleteEvent == null) { _nestedDebugStopCompleteEvent = new ManualResetEventSlim(false); } @@ -2774,7 +2774,7 @@ internal int GetBreakpointCount() internal void PushDebugger(Debugger debugger) { - if (debugger is null) + if (debugger == null) { return; } diff --git a/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineDriver.cs b/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineDriver.cs index 403af84fb83..240395bb567 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineDriver.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineDriver.cs @@ -136,7 +136,7 @@ internal ServerSteppablePipelineDriver(PowerShell powershell, bool noInput, Guid DataStructureHandler.HostResponseReceived += HandleHostResponseReceived; DataStructureHandler.OnSessionConnected += HandleSessionConnected; - if (rsToUse is null) + if (rsToUse == null) { throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.NestedPipelineMissingRunspace); } diff --git a/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineSubscriber.cs b/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineSubscriber.cs index 788cf2fe83e..850993cf162 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineSubscriber.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineSubscriber.cs @@ -121,7 +121,7 @@ private void HandleProcessRecord(object sender, PSEventArgs args) lock (driver.SyncObject) { // Make sure start event handler was called - if (driver.SteppablePipeline is null) + if (driver.SteppablePipeline == null) { return; } diff --git a/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs b/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs index f61187784ba..16978ff04e3 100644 --- a/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs +++ b/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs @@ -295,14 +295,14 @@ internal override RemotingDestination MySelf /// internal void DispatchInputQueueData(object sender, RemoteDataEventArgs dataEventArg) { - if (dataEventArg is null) + if (dataEventArg == null) { throw PSTraceSource.NewArgumentNullException(nameof(dataEventArg)); } RemoteDataObject rcvdData = dataEventArg.ReceivedData; - if (rcvdData is null) + if (rcvdData == null) { throw PSTraceSource.NewArgumentException(nameof(dataEventArg)); } @@ -564,7 +564,7 @@ internal void ExecuteConnect(byte[] connectData, out byte[] connectResponseData) serializedStream.Seek(0, SeekOrigin.Begin); RemoteDataObject capabilityObject = RemoteDataObject.CreateFrom(serializedStream, defragmentor); - if (capabilityObject is null) + if (capabilityObject == null) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnInputValidation); } @@ -606,7 +606,7 @@ internal void ExecuteConnect(byte[] connectData, out byte[] connectResponseData) serializedStream.Seek(0, SeekOrigin.Begin); RemoteDataObject connectRunspacePoolObject = RemoteDataObject.CreateFrom(serializedStream, defragmentor); - if (connectRunspacePoolObject is null) + if (connectRunspacePoolObject == null) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnServerStateValidation); } @@ -663,7 +663,7 @@ internal void ExecuteConnect(byte[] connectData, out byte[] connectResponseData) throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnInputValidation); } - if (_runspacePoolDriver is null) + if (_runspacePoolDriver == null) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnServerStateValidation); } @@ -741,7 +741,7 @@ internal void HandlePostConnect() /// private void HandleCreateRunspacePool(object sender, RemoteDataEventArgs createRunspaceEventArg) { - if (createRunspaceEventArg is null) + if (createRunspaceEventArg == null) { throw PSTraceSource.NewArgumentNullException(nameof(createRunspaceEventArg)); } @@ -809,7 +809,7 @@ private void HandleCreateRunspacePool(object sender, RemoteDataEventArgs createR rsSessionStateToUse = _sessionConfigProvider.GetInitialSessionState(_senderInfo); } - if (rsSessionStateToUse is null) + if (rsSessionStateToUse == null) { throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.InitialSessionStateNull, _configProviderId); } @@ -919,7 +919,7 @@ private void HandleCreateRunspacePool(object sender, RemoteDataEventArgs createR /// private void HandleNegotiationReceived(object sender, RemoteSessionNegotiationEventArgs negotiationEventArg) { - if (negotiationEventArg is null) + if (negotiationEventArg == null) { throw PSTraceSource.NewArgumentNullException(nameof(negotiationEventArg)); } @@ -1144,7 +1144,7 @@ private bool RunServerNegotiationAlgorithm(RemoteSessionCapability clientCapabil /// internal ServerRunspacePoolDriver GetRunspacePoolDriver(Guid clientRunspacePoolId) { - if (_runspacePoolDriver is null) + if (_runspacePoolDriver == null) { return null; } diff --git a/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs b/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs index bdb4dc8e4a9..b943444dd0a 100644 --- a/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs +++ b/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs @@ -70,7 +70,7 @@ private Queue _processPendingEventsQueue /// internal ServerRemoteSessionDSHandlerStateMachine(ServerRemoteSession session) { - if (session is null) + if (session == null) { throw PSTraceSource.NewArgumentNullException(nameof(session)); } @@ -132,7 +132,7 @@ internal ServerRemoteSessionDSHandlerStateMachine(ServerRemoteSession session) { for (int j = 0; j < _stateMachineHandle.GetLength(1); j++) { - if (_stateMachineHandle[i, j] is null) + if (_stateMachineHandle[i, j] == null) { _stateMachineHandle[i, j] += DoClose; } @@ -256,7 +256,7 @@ private void ProcessEvents() /// private void RaiseEventPrivate(RemoteSessionStateMachineEventArgs fsmEventArg) { - if (fsmEventArg is null) + if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg)); } @@ -290,7 +290,7 @@ private void DoCreateSession(object sender, RemoteSessionStateMachineEventArgs f { using (s_trace.TraceEventHandlers()) { - if (fsmEventArg is null) + if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg)); } @@ -319,7 +319,7 @@ private void DoNegotiationPending(object sender, RemoteSessionStateMachineEventA { using (s_trace.TraceEventHandlers()) { - if (fsmEventArg is null) + if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg)); } @@ -351,7 +351,7 @@ private void DoNegotiationReceived(object sender, RemoteSessionStateMachineEvent { using (s_trace.TraceEventHandlers()) { - if (fsmEventArg is null) + if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg)); } @@ -365,7 +365,7 @@ private void DoNegotiationReceived(object sender, RemoteSessionStateMachineEvent throw PSTraceSource.NewArgumentException(nameof(fsmEventArg)); } - if (fsmEventArg.RemoteSessionCapability is null) + if (fsmEventArg.RemoteSessionCapability == null) { throw PSTraceSource.NewArgumentException(nameof(fsmEventArg)); } @@ -389,7 +389,7 @@ private void DoNegotiationReceived(object sender, RemoteSessionStateMachineEvent private void DoNegotiationSending(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { - if (fsmEventArg is null) + if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg)); } @@ -418,7 +418,7 @@ private void DoNegotiationCompleted(object sender, RemoteSessionStateMachineEven { using (s_trace.TraceEventHandlers()) { - if (fsmEventArg is null) + if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg)); } @@ -446,7 +446,7 @@ private void DoEstablished(object sender, RemoteSessionStateMachineEventArgs fsm { using (s_trace.TraceEventHandlers()) { - if (fsmEventArg is null) + if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg)); } @@ -486,12 +486,12 @@ internal void DoMessageReceived(object sender, RemoteSessionStateMachineEventArg { using (s_trace.TraceEventHandlers()) { - if (fsmEventArg is null) + if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg)); } - if (fsmEventArg.RemoteData is null) + if (fsmEventArg.RemoteData == null) { throw PSTraceSource.NewArgumentException(nameof(fsmEventArg)); } @@ -591,7 +591,7 @@ private void DoConnectFailed(object sender, RemoteSessionStateMachineEventArgs f { using (s_trace.TraceEventHandlers()) { - if (fsmEventArg is null) + if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg)); } @@ -628,7 +628,7 @@ private void DoFatalError(object sender, RemoteSessionStateMachineEventArgs fsmE { using (s_trace.TraceEventHandlers()) { - if (fsmEventArg is null) + if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg)); } @@ -673,7 +673,7 @@ private void DoClose(object sender, RemoteSessionStateMachineEventArgs fsmEventA { using (s_trace.TraceEventHandlers()) { - if (fsmEventArg is null) + if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg)); } @@ -727,7 +727,7 @@ private void DoCloseFailed(object sender, RemoteSessionStateMachineEventArgs fsm { using (s_trace.TraceEventHandlers()) { - if (fsmEventArg is null) + if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg)); } @@ -757,7 +757,7 @@ private void DoCloseCompleted(object sender, RemoteSessionStateMachineEventArgs { using (s_trace.TraceEventHandlers()) { - if (fsmEventArg is null) + if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg)); } @@ -787,7 +787,7 @@ private void DoNegotiationFailed(object sender, RemoteSessionStateMachineEventAr { using (s_trace.TraceEventHandlers()) { - if (fsmEventArg is null) + if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg)); } @@ -816,7 +816,7 @@ private void DoNegotiationTimeout(object sender, RemoteSessionStateMachineEventA { using (s_trace.TraceEventHandlers()) { - if (fsmEventArg is null) + if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg)); } @@ -851,7 +851,7 @@ private void DoSendFailed(object sender, RemoteSessionStateMachineEventArgs fsmE { using (s_trace.TraceEventHandlers()) { - if (fsmEventArg is null) + if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg)); } @@ -880,7 +880,7 @@ private void DoReceiveFailed(object sender, RemoteSessionStateMachineEventArgs f { using (s_trace.TraceEventHandlers()) { - if (fsmEventArg is null) + if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg)); } diff --git a/src/System.Management.Automation/engine/remoting/server/serverremotingprotocolimplementation.cs b/src/System.Management.Automation/engine/remoting/server/serverremotingprotocolimplementation.cs index b8c6d0fd15e..1e72be279c7 100644 --- a/src/System.Management.Automation/engine/remoting/server/serverremotingprotocolimplementation.cs +++ b/src/System.Management.Automation/engine/remoting/server/serverremotingprotocolimplementation.cs @@ -170,7 +170,7 @@ internal override ServerRemoteSessionDSHandlerStateMachine StateMachine /// internal override void RaiseDataReceivedEvent(RemoteDataEventArgs dataArg) { - if (dataArg is null) + if (dataArg == null) { throw PSTraceSource.NewArgumentNullException(nameof(dataArg)); } diff --git a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs index ed6ee5e89bb..a7ace47929d 100644 --- a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs +++ b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs @@ -79,7 +79,7 @@ internal static DynamicMetaObject WriteToDebugLog(this DynamicMetaObject obj, Dy internal static BindingRestrictions GetSimpleTypeRestriction(this DynamicMetaObject obj) { - if (obj.Value is null) + if (obj.Value == null) { return BindingRestrictions.GetInstanceRestriction(obj.Expression, obj.Value); } @@ -132,13 +132,13 @@ internal static BindingRestrictions PSGetStaticMemberRestriction(this DynamicMet return obj.Restrictions; } - if (obj.Value is null) + if (obj.Value == null) { return BindingRestrictions.GetInstanceRestriction(obj.Expression, obj.Value); } var baseValue = PSObject.Base(obj.Value); - if (baseValue is null) + if (baseValue == null) { Diagnostics.Assert(obj.Value == AutomationNull.Value, "PSObject.Base should only return null for AutomationNull.Value"); return BindingRestrictions.GetExpressionRestriction(Expression.Equal(obj.Expression, Expression.Constant(AutomationNull.Value))); @@ -187,13 +187,13 @@ internal static BindingRestrictions PSGetTypeRestriction(this DynamicMetaObject return obj.Restrictions; } - if (obj.Value is null) + if (obj.Value == null) { return BindingRestrictions.GetInstanceRestriction(obj.Expression, obj.Value); } var baseValue = PSObject.Base(obj.Value); - if (baseValue is null) + if (baseValue == null) { Diagnostics.Assert(obj.Value == AutomationNull.Value, "PSObject.Base should only return null for AutomationNull.Value"); return BindingRestrictions.GetExpressionRestriction(Expression.Equal(obj.Expression, Expression.Constant(AutomationNull.Value))); @@ -568,7 +568,7 @@ internal static Expression MaybeDebase(DynamicMetaObjectBinder binder, Func()); var restrictions = target.LimitType.IsValueType @@ -1178,7 +1178,7 @@ private class KeyComparer : IEqualityComparer>)site).Update(site, obj); + return obj == null ? null : ((CallSite>)site).Update(site, obj); } internal static bool IsValueTypeMutable(Type type) @@ -2151,7 +2151,7 @@ private PSBinaryOperationBinder(ExpressionType operation, bool ignoreCase, bool private Func GetScalarCompareDelegate() { - if (_compareDelegate is null) + if (_compareDelegate == null) { var lvalExpr = Expression.Parameter(typeof(object), "lval"); var rvalExpr = Expression.Parameter(typeof(object), "rval"); @@ -2401,7 +2401,7 @@ private DynamicMetaObject BinaryNumericOp(string methodName, DynamicMetaObject t arg = FigureSignedUnsignedInt(arg, rightTypeCode, opTypeCode, out opImplType, out argType, out fallbackToDoubleInCaseOfOverflow); } - if (opImplType is null) + if (opImplType == null) { opImplType = typeof(UIntOps); argType = typeof(uint); @@ -2425,7 +2425,7 @@ private DynamicMetaObject BinaryNumericOp(string methodName, DynamicMetaObject t arg = FigureSignedUnsignedInt(arg, rightTypeCode, opTypeCode, out opImplType, out argType, out fallbackToDoubleInCaseOfOverflow); } - if (opImplType is null) + if (opImplType == null) { opImplType = typeof(ULongOps); argType = typeof(ulong); @@ -2530,7 +2530,7 @@ private DynamicMetaObject BinaryNumericStringOp(DynamicMetaObject target, Dynami // We can't determine the operation type at compile time, we'll need another dynamic site // Generate: // tmp = Parser.ScanNumber(arg) - // if (tmp is null) { throw new RuntimeError("BadNumericConstant") } + // if (tmp == null) { throw new RuntimeError("BadNumericConstant") } // dynamic op target tmp // For equality comparison operators, if the conversion fails, we shouldn't raise // an exception, so those must be wrapped in try/catch, like: @@ -2597,7 +2597,7 @@ internal static Expression ConvertStringToNumber(Expression expr, Type toType) private static DynamicMetaObject GetArgAsNumericOrPrimitive(DynamicMetaObject arg, Type targetType) { - if (arg.Value is null) + if (arg.Value == null) { return new DynamicMetaObject(ExpressionCache.Constant(0), arg.PSGetTypeRestriction(), 0); } @@ -2646,7 +2646,7 @@ private static Type GetBitwiseOpType(TypeCode opTypeCode) private DynamicMetaObject BinaryAdd(DynamicMetaObject target, DynamicMetaObject arg, DynamicMetaObject errorSuggestion) { - if (target.Value is null) + if (target.Value == null) { return new DynamicMetaObject(arg.Expression.Cast(typeof(object)), target.CombineRestrictions(arg)); } @@ -2742,7 +2742,7 @@ private DynamicMetaObject BinarySub(DynamicMetaObject target, DynamicMetaObject private DynamicMetaObject BinaryMultiply(DynamicMetaObject target, DynamicMetaObject arg, DynamicMetaObject errorSuggestion) { - if (target.Value is null) + if (target.Value == null) { // Result is null regardless of the arg. return new DynamicMetaObject(ExpressionCache.NullConstant, target.PSGetTypeRestriction()); @@ -2819,7 +2819,7 @@ private DynamicMetaObject BinarySubDivOrRem(DynamicMetaObject target, string implicitOpMethodName, string errorOperatorText) { - if (target.Value is null) + if (target.Value == null) { // if target is null, just use 0 target = new DynamicMetaObject(ExpressionCache.Constant(0), target.PSGetTypeRestriction(), 0); @@ -2850,7 +2850,7 @@ private DynamicMetaObject BinarySubDivOrRem(DynamicMetaObject target, private DynamicMetaObject Shift(DynamicMetaObject target, DynamicMetaObject arg, DynamicMetaObject errorSuggestion, string userOp, Func exprGenerator) { - if (target.Value is null) + if (target.Value == null) { return new DynamicMetaObject(ExpressionCache.Constant(0).Convert(typeof(object)), target.PSGetTypeRestriction()); } @@ -2929,7 +2929,7 @@ private DynamicMetaObject BinaryBitwiseOp(DynamicMetaObject target, string errorOperatorName, string methodName) { - if (target.Value is null && arg.Value is null) + if (target.Value == null && arg.Value == null) { return new DynamicMetaObject(ExpressionCache.Constant(0).Cast(typeof(object)), target.CombineRestrictions(arg)); } @@ -3026,15 +3026,15 @@ private DynamicMetaObject CompareEQ(DynamicMetaObject target, DynamicMetaObject arg, DynamicMetaObject errorSuggestion) { - if (target.Value is null) + if (target.Value == null) { return new DynamicMetaObject( - arg.Value is null ? ExpressionCache.BoxedTrue : ExpressionCache.BoxedFalse, + arg.Value == null ? ExpressionCache.BoxedTrue : ExpressionCache.BoxedFalse, target.CombineRestrictions(arg)); } var enumerable = PSEnumerableBinder.IsEnumerable(target); - if (enumerable is null && arg.Value is null) + if (enumerable == null && arg.Value == null) { return new DynamicMetaObject( ExpressionCache.BoxedFalse, @@ -3049,15 +3049,15 @@ private DynamicMetaObject CompareNE(DynamicMetaObject target, DynamicMetaObject arg, DynamicMetaObject errorSuggestion) { - if (target.Value is null) + if (target.Value == null) { return new DynamicMetaObject( - arg.Value is null ? ExpressionCache.BoxedFalse : ExpressionCache.BoxedTrue, + arg.Value == null ? ExpressionCache.BoxedFalse : ExpressionCache.BoxedTrue, target.CombineRestrictions(arg)); } var enumerable = PSEnumerableBinder.IsEnumerable(target); - if (enumerable is null && arg.Value is null) + if (enumerable == null && arg.Value == null) { return new DynamicMetaObject(ExpressionCache.BoxedTrue, target.CombineRestrictions(arg)); @@ -3167,7 +3167,7 @@ private DynamicMetaObject CompareLT(DynamicMetaObject target, DynamicMetaObject errorSuggestion) { var enumerable = PSEnumerableBinder.IsEnumerable(target); - if (enumerable is null && (target.Value is null || arg.Value is null)) + if (enumerable == null && (target.Value == null || arg.Value == null)) { Expression result = target.LimitType.IsNumeric() ? CompareWithZero(target, Expression.LessThan) @@ -3187,7 +3187,7 @@ private DynamicMetaObject CompareLE(DynamicMetaObject target, DynamicMetaObject errorSuggestion) { var enumerable = PSEnumerableBinder.IsEnumerable(target); - if (enumerable is null && (target.Value is null || arg.Value is null)) + if (enumerable == null && (target.Value == null || arg.Value == null)) { Expression result = target.LimitType.IsNumeric() ? CompareWithZero(target, Expression.LessThan) @@ -3209,7 +3209,7 @@ private DynamicMetaObject CompareGT(DynamicMetaObject target, // Handle a null operand as a special case here unless the target is enumerable or if one of the operands is numeric, // in which case null is converted to 0 and regular numeric comparison is done. var enumerable = PSEnumerableBinder.IsEnumerable(target); - if (enumerable is null && (target.Value is null || arg.Value is null)) + if (enumerable == null && (target.Value == null || arg.Value == null)) { Expression result = target.LimitType.IsNumeric() ? CompareWithZero(target, Expression.GreaterThanOrEqual) @@ -3231,7 +3231,7 @@ private DynamicMetaObject CompareGE(DynamicMetaObject target, // Handle a null operand as a special case here unless the target is enumerable or if one of the operands is numeric, // in which case null is converted to 0 and regular numeric comparison is done. var enumerable = PSEnumerableBinder.IsEnumerable(target); - if (enumerable is null && (target.Value is null || arg.Value is null)) + if (enumerable == null && (target.Value == null || arg.Value == null)) { Expression result = target.LimitType.IsNumeric() ? CompareWithZero(target, Expression.GreaterThanOrEqual) @@ -3417,27 +3417,27 @@ internal static PSUnaryOperationBinder Get(ExpressionType operation) switch (operation) { case ExpressionType.Not: - if (s_notBinder is null) + if (s_notBinder == null) Interlocked.CompareExchange(ref s_notBinder, new PSUnaryOperationBinder(operation), null); return s_notBinder; case ExpressionType.OnesComplement: - if (s_bnotBinder is null) + if (s_bnotBinder == null) Interlocked.CompareExchange(ref s_bnotBinder, new PSUnaryOperationBinder(operation), null); return s_bnotBinder; case ExpressionType.UnaryPlus: - if (s_unaryPlusBinder is null) + if (s_unaryPlusBinder == null) Interlocked.CompareExchange(ref s_unaryPlusBinder, new PSUnaryOperationBinder(operation), null); return s_unaryPlusBinder; case ExpressionType.Negate: - if (s_unaryMinus is null) + if (s_unaryMinus == null) Interlocked.CompareExchange(ref s_unaryMinus, new PSUnaryOperationBinder(operation), null); return s_unaryMinus; case ExpressionType.Increment: - if (s_incrementBinder is null) + if (s_incrementBinder == null) Interlocked.CompareExchange(ref s_incrementBinder, new PSUnaryOperationBinder(operation), null); return s_incrementBinder; case ExpressionType.Decrement: - if (s_decrementBinder is null) + if (s_decrementBinder == null) Interlocked.CompareExchange(ref s_decrementBinder, new PSUnaryOperationBinder(operation), null); return s_decrementBinder; } @@ -3516,7 +3516,7 @@ internal DynamicMetaObject BNot(DynamicMetaObject target, DynamicMetaObject erro return this.DeferForPSObject(target); } - if (target.Value is null) + if (target.Value == null) { return new DynamicMetaObject(ExpressionCache.Constant(-1).Cast(typeof(object)), target.PSGetTypeRestriction()); } @@ -3692,7 +3692,7 @@ private DynamicMetaObject IncrDecr(DynamicMetaObject target, int valueToAdd, Dyn return this.DeferForPSObject(target); } - if (target.Value is null) + if (target.Value == null) { return new DynamicMetaObject(ExpressionCache.Constant(valueToAdd).Cast(typeof(object)), target.PSGetTypeRestriction()); } @@ -3900,7 +3900,7 @@ internal static Expression InvokeConverter(LanguagePrimitives.IConversionData co return conv; } - if (resultType.IsValueType && Nullable.GetUnderlyingType(resultType) is null) + if (resultType.IsValueType && Nullable.GetUnderlyingType(resultType) == null) { return Expression.Unbox(conv, resultType); } @@ -3957,7 +3957,7 @@ public override string ToString() "PSGetIndexBinder indexCount={0}{1}{2} ver:{3}", this.CallInfo.ArgumentCount, _allowSlicing ? string.Empty : " slicing disallowed", - _constraints is null ? string.Empty : " constraints: " + _constraints, + _constraints == null ? string.Empty : " constraints: " + _constraints, _version); } @@ -3993,7 +3993,7 @@ public override DynamicMetaObject FallbackGetIndex(DynamicMetaObject target, Dyn return comResult.UpdateComRestrictionsForPsObject(indexes).WriteToDebugLog(this); } - if (target.Value is null) + if (target.Value == null) { return (errorSuggestion ?? target.ThrowRuntimeError(indexes, BindingRestrictions.Empty, "NullArray", ParserStrings.NullArray)).WriteToDebugLog(this); @@ -4005,7 +4005,7 @@ public override DynamicMetaObject FallbackGetIndex(DynamicMetaObject target, Dyn // $a[$null] # error // $a[$null,$null] # no error, result is an empty array // The rationale: V1/V2 did it, and when people are slicing, it's better to return some of the results than none. - if (indexes.Length == 1 && indexes[0].Value is null && _allowSlicing) + if (indexes.Length == 1 && indexes[0].Value == null && _allowSlicing) { return (errorSuggestion ?? target.ThrowRuntimeError(indexes, BindingRestrictions.Empty, "NullArrayIndex", ParserStrings.NullArrayIndex)).WriteToDebugLog(this); @@ -4032,7 +4032,7 @@ public override DynamicMetaObject FallbackGetIndex(DynamicMetaObject target, Dyn // If the type explicitly implements an indexer specified by an interface // then the DefaultMemberAttribute will not carry over to the implementation. // This check will catch those cases. - if (defaultMember is null) + if (defaultMember == null) { defaultMember = i.GetCustomAttributes(inherit: false).FirstOrDefault(); if (defaultMember != null) @@ -4249,7 +4249,7 @@ private DynamicMetaObject GetIndexArray(DynamicMetaObject target, DynamicMetaObj } var indexAsInt = ConvertIndex(indexes[0], typeof(int)); - if (indexAsInt is null) + if (indexAsInt == null) { // Calling the indexer will fail because we can't convert an index to the correct type. return errorSuggestion ?? PSConvertBinder.ThrowNoConversion(target, typeof(int), this, _version, indexes); @@ -4289,7 +4289,7 @@ private DynamicMetaObject GetIndexMultiDimensionArray(DynamicMetaObject target, if (indexes.Length == 1) { var enumerable = PSEnumerableBinder.IsEnumerable(indexes[0]); - if (enumerable is null) + if (enumerable == null) { return target.ThrowRuntimeError(indexes, BindingRestrictions.Empty, "NeedMultidimensionalIndex", ParserStrings.NeedMultidimensionalIndex, @@ -4332,7 +4332,7 @@ private DynamicMetaObject InvokeIndexer(DynamicMetaObject target, { MethodInfo getter = PSInvokeMemberBinder.FindBestMethod(target, indexes, "get_" + methodName, false, _constraints); - if (getter is null) + if (getter == null) { return CheckForSlicing(target, indexes) ?? errorSuggestion ?? CannotIndexTarget(target, indexes); } @@ -4384,7 +4384,7 @@ private DynamicMetaObject InvokeIndexer(DynamicMetaObject target, ? PSConvertBinder.ConvertToByRefLikeTypeViaCasting(indexes[i], parameterType) : ConvertIndex(indexes[i], parameterType); - if (indexExprs[i] is null) + if (indexExprs[i] == null) { // Calling the indexer will fail because we can't convert an index to the correct type. return errorSuggestion ?? PSConvertBinder.ThrowNoConversion(target, parameterType, this, _version, indexes); @@ -4393,7 +4393,7 @@ private DynamicMetaObject InvokeIndexer(DynamicMetaObject target, if (CanIndexFromEndWithNegativeIndex(target, getter, getterParams)) { - if (lengthProperty is null) + if (lengthProperty == null) { // Count is declared by most supported types, Length will catch some edge cases like strings. lengthProperty = target.LimitType.GetProperty("Count") ?? @@ -4543,7 +4543,7 @@ private PSSetIndexBinder(Tuple tuple) public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "PSSetIndexBinder indexCnt={0}{1} ver:{2}", - CallInfo.ArgumentCount, _constraints is null ? string.Empty : " constraints: " + _constraints, _version); + CallInfo.ArgumentCount, _constraints == null ? string.Empty : " constraints: " + _constraints, _version); } internal static void InvalidateCache() @@ -4582,13 +4582,13 @@ public override DynamicMetaObject FallbackSetIndex( return result.UpdateComRestrictionsForPsObject(indexes).WriteToDebugLog(this); } - if (target.Value is null) + if (target.Value == null) { return (errorSuggestion ?? target.ThrowRuntimeError(indexes, BindingRestrictions.Empty, "NullArray", ParserStrings.NullArray)).WriteToDebugLog(this); } - if (indexes.Length == 1 && indexes[0].Value is null) + if (indexes.Length == 1 && indexes[0].Value == null) { return (errorSuggestion ?? target.ThrowRuntimeError(indexes, BindingRestrictions.Empty, "NullArrayIndex", ParserStrings.NullArrayIndex).WriteToDebugLog(this)); @@ -4628,7 +4628,7 @@ private DynamicMetaObject InvokeIndexer( { MethodInfo setter = PSInvokeMemberBinder.FindBestMethod(target, indexes.Append(value), "set_" + methodName, false, _constraints); - if (setter is null) + if (setter == null) { return errorSuggestion ?? CannotIndexTarget(target, indexes, value); } @@ -4666,7 +4666,7 @@ private DynamicMetaObject InvokeIndexer( ? PSConvertBinder.ConvertToByRefLikeTypeViaCasting(argument, parameterType) : PSGetIndexBinder.ConvertIndex(argument, parameterType); - if (indexExprs[i] is null) + if (indexExprs[i] == null) { // Calling the indexer will fail because we can't convert an index to the correct type. return errorSuggestion ?? PSConvertBinder.ThrowNoConversion(target, parameterType, this, _version, indexes.Append(value).ToArray()); @@ -4788,7 +4788,7 @@ private DynamicMetaObject SetIndexArray(DynamicMetaObject target, } var intIndex = PSGetIndexBinder.ConvertIndex(indexes[0], typeof(int)); - if (intIndex is null) + if (intIndex == null) { return errorSuggestion ?? PSConvertBinder.ThrowNoConversion(indexes[0], typeof(int), this, _version, target, value); @@ -4796,7 +4796,7 @@ private DynamicMetaObject SetIndexArray(DynamicMetaObject target, var elementType = target.LimitType.GetElementType(); var valueExpr = PSGetIndexBinder.ConvertIndex(value, elementType); - if (valueExpr is null) + if (valueExpr == null) { return errorSuggestion ?? PSConvertBinder.ThrowNoConversion(value, elementType, this, _version, indexes.Prepend(target).ToArray()); @@ -4816,7 +4816,7 @@ private DynamicMetaObject SetIndexMultiDimensionArray(DynamicMetaObject target, { var elementType = target.LimitType.GetElementType(); var valueExpr = PSGetIndexBinder.ConvertIndex(value, elementType); - if (valueExpr is null) + if (valueExpr == null) { return errorSuggestion ?? PSConvertBinder.ThrowNoConversion(value, elementType, this, _version, indexes.Prepend(target).ToArray()); @@ -4825,7 +4825,7 @@ private DynamicMetaObject SetIndexMultiDimensionArray(DynamicMetaObject target, if (indexes.Length == 1) { var indexExpr = PSGetIndexBinder.ConvertIndex(indexes[0], typeof(int[])); - if (indexExpr is null) + if (indexExpr == null) { return errorSuggestion ?? PSConvertBinder.ThrowNoConversion(indexes[0], typeof(int[]), this, _version, new DynamicMetaObject[] { target, value }); @@ -4856,7 +4856,7 @@ private DynamicMetaObject SetIndexMultiDimensionArray(DynamicMetaObject target, for (int i = 0; i < indexes.Length; i++) { indexExprs[i] = PSGetIndexBinder.ConvertIndex(indexes[i], typeof(int)); - if (indexExprs[i] is null) + if (indexExprs[i] == null) { return PSConvertBinder.ThrowNoConversion(indexes[i], typeof(int), this, _version, indexes.Except(new DynamicMetaObject[] { indexes[i] }).Append(target).Append(value).ToArray()); @@ -4895,7 +4895,7 @@ public int GetHashCode(PSGetMemberBinderKeyType obj) { var stringComparer = obj.Item3 ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; return Utils.CombineHashCodes(stringComparer.GetHashCode(obj.Item1), - obj.Item2 is null ? 0 : obj.Item2.GetHashCode(), + obj.Item2 == null ? 0 : obj.Item2.GetHashCode(), obj.Item3.GetHashCode(), obj.Item4.GetHashCode()); } @@ -5171,7 +5171,7 @@ public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, Dy object targetValue = PSObject.Base(target.Value); - if (targetValue is null) + if (targetValue == null) { // PSGetTypeRestriction will actually create an instance restriction because the targetValue is null. return PropertyDoesntExist(target, target.PSGetTypeRestriction()).WriteToDebugLog(this); @@ -5219,7 +5219,7 @@ public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, Dy if (!canOptimize) { - Diagnostics.Assert(memberInfo is null, "We don't bother returning members if we can't optimize."); + Diagnostics.Assert(memberInfo == null, "We don't bother returning members if we can't optimize."); return new DynamicMetaObject( WrapGetMemberInTry(Expression.Call(CachedReflectionInfo.PSGetMemberBinder_GetAdaptedValue, GetTargetExpr(target, typeof(object)), @@ -5229,7 +5229,7 @@ public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, Dy if (memberInfo != null) { - Diagnostics.Assert(memberInfo.instance is null, "We shouldn't be here if a member is already bound."); + Diagnostics.Assert(memberInfo.instance == null, "We shouldn't be here if a member is already bound."); // The most common case - we're getting some property. We can optimize many different kinds // of property accessors, so we special case each possibility. @@ -5262,7 +5262,7 @@ public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, Dy if (propertyAccessor != null) { if (propertyAccessor.GetMethod.IsFamily && - (_classScope is null || !_classScope.IsSubclassOf(propertyAccessor.DeclaringType))) + (_classScope == null || !_classScope.IsSubclassOf(propertyAccessor.DeclaringType))) { return GenerateGetPropertyException(restrictions).WriteToDebugLog(this); } @@ -5325,7 +5325,7 @@ public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, Dy if (!isGeneric || genericTypeArg != null) { var temp = Expression.Variable(typeof(object)); - if (expr is null) + if (expr == null) { // If expr is not null, it's the fallback when no member exists. If it is null, // the fallback is the result from PropertyDoesntExist. @@ -5462,7 +5462,7 @@ private DynamicMetaObject PropertyDoesntExist(DynamicMetaObject target, BindingR if (Name.Equals("Length", StringComparison.OrdinalIgnoreCase) || Name.Equals("Count", StringComparison.OrdinalIgnoreCase)) { // $null.Count should be 0, anything else should be 1 - var resultCount = PSObject.Base(target.Value) is null ? 0 : 1; + var resultCount = PSObject.Base(target.Value) == null ? 0 : 1; return new DynamicMetaObject( Expression.Condition( Compiler.IsStrictMode(2), @@ -5509,7 +5509,7 @@ internal static bool IsAllowedInConstrainedLanguage(object targetValue, string n // Otherwise, check if it's a core type Type targetType = targetValue as Type; - if ((!isStatic) || (targetType is null)) + if ((!isStatic) || (targetType == null)) { targetType = targetValue.GetType(); } @@ -5555,7 +5555,7 @@ private PSMemberInfo ResolveAlias(PSAliasProperty alias, DynamicMetaObject targe List aliasRestrictions) { Diagnostics.Assert(aliasRestrictions != null, "aliasRestrictions cannot be null"); - if (aliases is null) + if (aliases == null) { aliases = new HashSet { alias.Name }; } @@ -5657,7 +5657,7 @@ internal PSMemberInfo GetPSMemberInfo(DynamicMetaObject target, object value = isTargetDeserializedObject ? target.Value : PSObject.Base(target.Value); var adapterSet = PSObject.GetMappedAdapter(value, typeTable); - if (memberInfo is null) + if (memberInfo == null) { canOptimize = adapterSet.OriginalAdapter.CanSiteBinderOptimize(memberTypeToOperateOn); // Don't bother looking for the member if we're not going to use it. @@ -5667,7 +5667,7 @@ internal PSMemberInfo GetPSMemberInfo(DynamicMetaObject target, } } - if (memberInfo is null && canOptimize && adapterSet.DotNetAdapter != null) + if (memberInfo == null && canOptimize && adapterSet.DotNetAdapter != null) { memberInfo = adapterSet.DotNetAdapter.BaseGetMember(value, Name); } @@ -5686,13 +5686,13 @@ internal PSMemberInfo GetPSMemberInfo(DynamicMetaObject target, if (alias != null) { aliasConversionType = alias.ConversionType; - if (aliasRestrictions is null) + if (aliasRestrictions == null) { aliasRestrictions = new List(); } memberInfo = ResolveAlias(alias, target, aliases, aliasRestrictions); - if (memberInfo is null) + if (memberInfo == null) { // this can happen in the cases where referenced name of the alias property // maps to an adapter that cannot optimize (like ManagementObjectAdapter) @@ -5719,8 +5719,8 @@ internal PSMemberInfo GetPSMemberInfo(DynamicMetaObject target, var getMethod = propertyInfo.GetGetMethod(nonPublic: true); var setMethod = propertyInfo.GetSetMethod(nonPublic: true); - if ((getMethod is null || getMethod.IsFamily || getMethod.IsPublic) && - (setMethod is null || setMethod.IsFamily || setMethod.IsPublic)) + if ((getMethod == null || getMethod.IsFamily || getMethod.IsPublic) && + (setMethod == null || setMethod.IsFamily || setMethod.IsPublic)) { memberInfo = new PSProperty(this.Name, PSObject.DotNetInstanceAdapter, target.Value, new DotNetAdapter.PropertyCacheEntry(propertyInfo)); } @@ -5740,7 +5740,7 @@ internal PSMemberInfo GetPSMemberInfo(DynamicMetaObject target, var methodInfo = member as MethodInfo; if (methodInfo != null && (methodInfo.IsPublic || methodInfo.IsFamily)) { - if (candidateMethods is null) + if (candidateMethods == null) { candidateMethods = new List(); } @@ -5836,12 +5836,12 @@ internal static object GetAdaptedValue(object obj, string member) } var adapterSet = PSObject.GetMappedAdapter(obj, context != null ? context.TypeTable : null); - if (memberInfo is null) + if (memberInfo == null) { memberInfo = adapterSet.OriginalAdapter.BaseGetMember(obj, member); } - if (memberInfo is null && adapterSet.DotNetAdapter != null) + if (memberInfo == null && adapterSet.DotNetAdapter != null) { memberInfo = adapterSet.DotNetAdapter.BaseGetMember(obj, member); } @@ -5943,7 +5943,7 @@ public int GetHashCode(PSSetMemberBinderKeyType obj) { var stringComparer = obj.Item3 ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; return Utils.CombineHashCodes(stringComparer.GetHashCode(obj.Item1), - obj.Item2 is null ? 0 : obj.Item2.GetHashCode(), + obj.Item2 == null ? 0 : obj.Item2.GetHashCode(), obj.Item3.GetHashCode()); } } @@ -5993,7 +5993,7 @@ public override string ToString() private Expression GetTransformedExpression(IEnumerable transformationAttributes, Expression originalExpression) { - if (transformationAttributes is null) + if (transformationAttributes == null) { return originalExpression; } @@ -6053,7 +6053,7 @@ public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, Dy } var targetValue = PSObject.Base(target.Value); - if (targetValue is null) + if (targetValue == null) { return (target.ThrowRuntimeError(new[] { value }, BindingRestrictions.Empty, "PropertyNotFound", ParserStrings.PropertyNotFound, @@ -6168,7 +6168,7 @@ public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, Dy if (!canOptimize) { - Diagnostics.Assert(memberInfo is null, "We don't bother returning members if we can't optimize."); + Diagnostics.Assert(memberInfo == null, "We don't bother returning members if we can't optimize."); return new DynamicMetaObject( Expression.Call(CachedReflectionInfo.PSSetMemberBinder_SetAdaptedValue, PSGetMemberBinder.GetTargetExpr(target, typeof(object)), @@ -6177,7 +6177,7 @@ public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, Dy restrictions).WriteToDebugLog(this); } - if (memberInfo is null) + if (memberInfo == null) { return (errorSuggestion ?? new DynamicMetaObject( Compiler.ThrowRuntimeError("PropertyAssignmentException", ParserStrings.PropertyNotFound, this.ReturnType, Expression.Constant(Name)), @@ -6256,7 +6256,7 @@ public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, Dy if (propertyInfo != null) { if (propertyInfo.SetMethod.IsFamily && - (_classScope is null || !_classScope.IsSubclassOf(propertyInfo.DeclaringType))) + (_classScope == null || !_classScope.IsSubclassOf(propertyInfo.DeclaringType))) { return GeneratePropertyAssignmentException(restrictions).WriteToDebugLog(this); } @@ -6276,7 +6276,7 @@ public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, Dy var nullableUnderlyingType = Nullable.GetUnderlyingType(lhsType); if (nullableUnderlyingType != null) { - if (value.Value is null) + if (value.Value == null) { expr = Expression.Block( Expression.Assign(lhs, this.GetTransformedExpression(argumentTransformationAttributes, Expression.Constant(null, lhsType))), @@ -6440,12 +6440,12 @@ internal static object SetAdaptedValue(object obj, string member, object value) } var adapterSet = PSObject.GetMappedAdapter(obj, context != null ? context.TypeTable : null); - if (memberInfo is null) + if (memberInfo == null) { memberInfo = adapterSet.OriginalAdapter.BaseGetMember(obj, member); } - if (memberInfo is null && adapterSet.DotNetAdapter != null) + if (memberInfo == null && adapterSet.DotNetAdapter != null) { memberInfo = adapterSet.DotNetAdapter.BaseGetMember(obj, member); } @@ -6517,7 +6517,7 @@ public bool Equals(PSInvokeMemberBinderKeyType x, PSInvokeMemberBinderKeyType y) && x.Item2.Equals(y.Item2) && x.Item3 == y.Item3 && x.Item4 == y.Item4 - && ((x.Item5 is null) ? (y.Item5 is null) : x.Item5.Equals(y.Item5)) + && ((x.Item5 == null) ? (y.Item5 == null) : x.Item5.Equals(y.Item5)) && x.Item6 == y.Item6 && x.Item7 == y.Item7; } @@ -6529,9 +6529,9 @@ public int GetHashCode(PSInvokeMemberBinderKeyType obj) obj.Item2.GetHashCode(), obj.Item3.GetHashCode(), obj.Item4.GetHashCode(), - obj.Item5 is null ? 0 : obj.Item5.GetHashCode(), + obj.Item5 == null ? 0 : obj.Item5.GetHashCode(), obj.Item6.GetHashCode(), - obj.Item7 is null ? 0 : obj.Item7.GetHashCode()); + obj.Item7 == null ? 0 : obj.Item7.GetHashCode()); } } @@ -6630,7 +6630,7 @@ public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, } var targetValue = PSObject.Base(target.Value); - if (targetValue is null) + if (targetValue == null) { if (!_static && !_nonEnumerating) { @@ -6718,7 +6718,7 @@ public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, if (!canOptimize) { - Diagnostics.Assert(methodInfo is null, "We don't bother returning members if we can't optimize."); + Diagnostics.Assert(methodInfo == null, "We don't bother returning members if we can't optimize."); Expression call; if (_propertySetter) @@ -7119,7 +7119,7 @@ internal static Expression InvokeMethod(MethodBase mi, DynamicMetaObject target, Diagnostics.Assert(parameters[i].IsOptional, "if there are too few arguments, FindBestMethod should only succeed if parameters are optional"); var argValue = parameters[i].DefaultValue; - if (argValue is null) + if (argValue == null) { argExprs[i] = Expression.Default(parameterType); } @@ -7238,7 +7238,7 @@ private DynamicMetaObject InvokeMemberOnCollection(DynamicMetaObject targetEnume private static DynamicMetaObject GetTargetAsEnumerable(DynamicMetaObject target) { var enumerableTarget = PSEnumerableBinder.IsEnumerable(target); - if (enumerableTarget is null) + if (enumerableTarget == null) { // Wrap the target in an array. enumerableTarget = PSEnumerableBinder.IsEnumerable( @@ -7367,7 +7367,7 @@ internal static bool IsHeterogeneousArray(object[] args) } var firstElement = PSObject.Base(args[0]); - if (firstElement is null) + if (firstElement == null) { return true; } @@ -7387,7 +7387,7 @@ internal static bool IsHeterogeneousArray(object[] args) return args.Skip(1).Any(element => { var obj = PSObject.Base(element); - return obj is null || !firstType.Equals(obj.GetType()); + return obj == null || !firstType.Equals(obj.GetType()); }); } @@ -7396,7 +7396,7 @@ internal static object InvokeAdaptedMember(object obj, string methodName, object var context = LocalPipeline.GetExecutionContextFromTLS(); var adapterSet = PSObject.GetMappedAdapter(obj, context != null ? context.TypeTable : null); var methodInfo = adapterSet.OriginalAdapter.BaseGetMember(obj, methodName) as PSMethodInfo; - if (methodInfo is null && adapterSet.DotNetAdapter != null) + if (methodInfo == null && adapterSet.DotNetAdapter != null) { methodInfo = adapterSet.DotNetAdapter.BaseGetMember(obj, methodName) as PSMethodInfo; } @@ -7441,7 +7441,7 @@ internal static object InvokeAdaptedSetMember(object obj, string methodName, obj var context = LocalPipeline.GetExecutionContextFromTLS(); var adapterSet = PSObject.GetMappedAdapter(obj, context != null ? context.TypeTable : null); var methodInfo = adapterSet.OriginalAdapter.BaseGetMember(obj, methodName); - if (methodInfo is null && adapterSet.DotNetAdapter != null) + if (methodInfo == null && adapterSet.DotNetAdapter != null) { methodInfo = adapterSet.DotNetAdapter.BaseGetMember(obj, methodName); } @@ -7461,13 +7461,13 @@ internal static bool TryGetInstanceMethod(object value, string memberName, out P PSMemberInfoInternalCollection instanceMembers; var memberInfo = PSObject.HasInstanceMembers(value, out instanceMembers) ? instanceMembers[memberName] : null; methodInfo = memberInfo as PSMethodInfo; - if (memberInfo is null) + if (memberInfo == null) { // No member, just return false return false; } - if (methodInfo is null) + if (methodInfo == null) { // Found a member, but it wasn't a method, throw an exception because we can't call it. throw InterpreterError.NewInterpreterException(memberName, typeof(RuntimeException), null, @@ -7505,7 +7505,7 @@ public bool Equals(Tuple x, Tuple y) { return x.Item1.Equals(y.Item1) - && ((x.Item2 is null) ? (y.Item2 is null) : x.Item2.Equals(y.Item2)) + && ((x.Item2 == null) ? (y.Item2 == null) : x.Item2.Equals(y.Item2)) && x.Item3 == y.Item3; } @@ -7571,7 +7571,7 @@ public override DynamicMetaObject FallbackCreateInstance(DynamicMetaObject targe } var targetValue = PSObject.Base(target.Value); - if (targetValue is null) + if (targetValue == null) { return target.ThrowRuntimeError(args, BindingRestrictions.Empty, "InvokeMethodOnNull", ParserStrings.InvokeMethodOnNull).WriteToDebugLog(this); } @@ -7641,7 +7641,7 @@ public override DynamicMetaObject FallbackCreateInstance(DynamicMetaObject targe internal static bool IsTargetTypeByRefLike(object target) { var targetValue = PSObject.Base(target); - if (targetValue is null) { return false; } + if (targetValue == null) { return false; } var instanceType = targetValue as Type ?? targetValue.GetType(); return instanceType.IsByRefLike; @@ -7653,7 +7653,7 @@ internal static bool IsTargetTypeByRefLike(object target) internal static bool IsTargetTypeNonPublic(object target) { var targetValue = PSObject.Base(target); - if (targetValue is null) { return false; } + if (targetValue == null) { return false; } var instanceType = targetValue as Type ?? targetValue.GetType(); return !TypeResolver.IsPublic(instanceType); @@ -7683,7 +7683,7 @@ public bool Equals(Tuple x, Tuple y) { return x.Item1.Equals(y.Item1) - && ((x.Item2 is null) ? (y.Item2 is null) : x.Item2.Equals(y.Item2)); + && ((x.Item2 == null) ? (y.Item2 == null) : x.Item2.Equals(y.Item2)); } public int GetHashCode(Tuple obj) diff --git a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs index f4232035963..819588225ba 100644 --- a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs +++ b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs @@ -56,14 +56,14 @@ internal CompiledScriptBlockData(string scriptText, bool isProductCode) internal bool Compile(bool optimized) { - if (_attributes is null) + if (_attributes == null) { InitializeMetadata(); } // We need the name to index map to check if any allscope variables are assigned. If they // are, we can't run the optimized version, so we'll compile once more unoptimized and run that. - if (optimized && NameToIndexMap is null) + if (optimized && NameToIndexMap == null) { CompileOptimized(); } @@ -120,7 +120,7 @@ private void InitializeMetadata() _usesCmdletBinding = cmdletBindingAttribute != null; } - bool automaticPosition = cmdletBindingAttribute is null || cmdletBindingAttribute.PositionalBinding; + bool automaticPosition = cmdletBindingAttribute == null || cmdletBindingAttribute.PositionalBinding; var runtimeDefinedParameterDictionary = Ast.GetParameterMetadata(automaticPosition, ref _usesCmdletBinding); @@ -194,7 +194,7 @@ private void ReallyCompile(bool optimize) private void PerformSecurityChecks() { var scriptBlockAst = Ast as ScriptBlockAst; - if (scriptBlockAst is null) + if (scriptBlockAst == null) { // Checks are only needed at the top level. return; @@ -264,13 +264,13 @@ bool IsScriptBlockInFactASafeHashtable() } PipelineAst pipelineAst = endBlock.Statements[0] as PipelineAst; - if (pipelineAst is null) + if (pipelineAst == null) { return false; } HashtableAst hashtableAst = pipelineAst.GetPureExpression() as HashtableAst; - if (hashtableAst is null) + if (hashtableAst == null) { return false; } @@ -346,7 +346,7 @@ internal bool IsProductCode { get { - if (_isProductCode is null) + if (_isProductCode == null) { _isProductCode = SecuritySupport.IsProductBinary(((Ast)_ast).Extent.File); } @@ -381,7 +381,7 @@ internal bool HasSuspiciousContent internal List GetAttributes() { - if (_attributes is null) + if (_attributes == null) { InitializeMetadata(); } @@ -409,7 +409,7 @@ internal RuntimeDefinedParameterDictionary RuntimeDefinedParameters { get { - if (_runtimeDefinedParameterDictionary is null) + if (_runtimeDefinedParameterDictionary == null) { InitializeMetadata(); } @@ -422,7 +422,7 @@ internal CmdletBindingAttribute CmdletBindingAttribute { get { - if (_runtimeDefinedParameterDictionary is null) + if (_runtimeDefinedParameterDictionary == null) { InitializeMetadata(); } @@ -437,7 +437,7 @@ internal ObsoleteAttribute ObsoleteAttribute { get { - if (_runtimeDefinedParameterDictionary is null) + if (_runtimeDefinedParameterDictionary == null) { InitializeMetadata(); } @@ -469,11 +469,11 @@ internal ExperimentalAttribute ExperimentalAttribute public MergedCommandParameterMetadata GetParameterMetadata(ScriptBlock scriptBlock) { - if (_parameterMetadata is null) + if (_parameterMetadata == null) { lock (this) { - if (_parameterMetadata is null) + if (_parameterMetadata == null) { CommandMetadata metadata = new CommandMetadata( scriptBlock, @@ -506,7 +506,7 @@ public override string ToString() } var funcDefn = (FunctionDefinitionAst)_ast; - if (funcDefn.Parameters is null) + if (funcDefn.Parameters == null) { return funcDefn.Body.ToStringForSerialization(); } @@ -571,7 +571,7 @@ internal static ScriptBlock TryGetCachedScriptBlock(string fileName, string file if (s_cachedScripts.TryGetValue(key, out scriptBlock)) { Diagnostics.Assert( - scriptBlock.SessionStateInternal is null, + scriptBlock.SessionStateInternal == null, "A cached scriptblock should not have it's session state bound, that causes a memory leak."); return scriptBlock.Clone(); } @@ -664,7 +664,7 @@ internal string ToStringWithDollarUsingHandling( { FunctionDefinitionAst funcDefn = null; var sbAst = Ast as ScriptBlockAst; - if (sbAst is null) + if (sbAst == null) { funcDefn = (FunctionDefinitionAst)Ast; sbAst = funcDefn.Body; @@ -678,7 +678,7 @@ internal string ToStringWithDollarUsingHandling( string paramText; string additionalNewParams = usingVariablesTuple.Item2; - if (funcDefn is null || funcDefn.Parameters is null) + if (funcDefn == null || funcDefn.Parameters == null) { paramText = "param(" + additionalNewParams + ")" + Environment.NewLine; } @@ -696,7 +696,7 @@ internal string ToStringWithDollarUsingHandling( /// public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) { throw PSTraceSource.NewArgumentNullException(nameof(info)); } @@ -764,7 +764,7 @@ private PipelineAst GetSimplePipeline(Func errorHandler) } var pipeAst = statements[0] as PipelineAst; - if (pipeAst is null) + if (pipeAst == null) { return errorHandler(AutomationExceptions.CanOnlyConvertOnePipeline); } @@ -919,7 +919,7 @@ internal string GetWithInputHandlingForInvokeCommandWithUsingExpression( AstInternal.GetWithInputHandlingForInvokeCommandWithUsingExpression(usingVariablesTuple); // result.Item1 is ParamText; result.Item2 is ScriptBlockText - return result.Item1 is null ? result.Item2 : result.Item1 + result.Item2; + return result.Item1 == null ? result.Item2 : result.Item1 + result.Item2; } internal bool IsUsingDollarInput() => AstSearcher.IsUsingDollarInput(this.Ast); @@ -972,7 +972,7 @@ internal void InvokeWithPipeImpl( ExecutionContext context = GetContextFromTLS(); Diagnostics.Assert( - SessionStateInternal is null || SessionStateInternal.ExecutionContext == context, + SessionStateInternal == null || SessionStateInternal.ExecutionContext == context, "The scriptblock is being invoked in a runspace different than the one where it was created"); if (context.CurrentPipelineStopping) @@ -982,25 +982,25 @@ internal void InvokeWithPipeImpl( // Validate at the arguments are consistent. The only public API that gets you here never sets createLocalScope to false... Diagnostics.Assert( - createLocalScope || functionsToDefine is null, + createLocalScope || functionsToDefine == null, "When calling ScriptBlock.InvokeWithContext(), if 'functionsToDefine' != null then 'createLocalScope' must be true"); Diagnostics.Assert( - createLocalScope || variablesToDefine is null, + createLocalScope || variablesToDefine == null, "When calling ScriptBlock.InvokeWithContext(), if 'variablesToDefine' != null then 'createLocalScope' must be true"); - if (args is null) + if (args == null) { args = Array.Empty(); } bool runOptimized = context._debuggingMode > 0 ? false : createLocalScope; var codeToInvoke = GetCodeToInvoke(ref runOptimized, clauseToInvoke); - if (codeToInvoke is null) + if (codeToInvoke == null) { return; } - if (outputPipe is null) + if (outputPipe == null) { // If we don't have a pipe to write to, we need to discard all results. outputPipe = new Pipe { NullPipe = true }; @@ -1052,7 +1052,7 @@ internal void InvokeWithPipeImpl( try { var myInvocationInfo = invocationInfo; - if (myInvocationInfo is null) + if (myInvocationInfo == null) { var callerFrame = context.Debugger.GetCallStack().LastOrDefault(); var extent = (callerFrame != null) @@ -1102,7 +1102,7 @@ internal void InvokeWithPipeImpl( throw e; } - if (def.Value is null) + if (def.Value == null) { PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException( ParserStrings.NullFunctionBodyInFunctionDefinitionDictionary, def.Key); @@ -1121,7 +1121,7 @@ internal void InvokeWithPipeImpl( foreach (var psvar in variablesToDefine) { // Check for null entries. - if (psvar is null) + if (psvar == null) { PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException( ParserStrings.NullEntryInVariablesDefinitionList, index); @@ -1141,7 +1141,7 @@ internal void InvokeWithPipeImpl( } else { - if (context.EngineSessionState.CurrentScope.LocalsTuple is null) + if (context.EngineSessionState.CurrentScope.LocalsTuple == null) { // If the locals tuple is null, that means either: // * we're invoking a script block for a module @@ -1623,7 +1623,7 @@ private static bool GetAndValidateEncryptionRecipients( // If the engine hasn't started up yet, then we're just compiling script // blocks. We'll have to log them when they are used and we have an engine // to work with. - if (sessionState is null) + if (sessionState == null) { return false; } @@ -2150,13 +2150,13 @@ internal class ScriptBlockSerializationHelper : ISerializable, IObjectReference private ScriptBlockSerializationHelper(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) { throw new ArgumentNullException(nameof(info)); } _scriptText = info.GetValue("ScriptText", typeof(string)) as string; - if (_scriptText is null) + if (_scriptText == null) { throw PSTraceSource.NewArgumentNullException(nameof(info)); } @@ -2382,7 +2382,7 @@ public object GetDynamicParameters() if (_scriptBlock.HasDynamicParameters) { var resultList = new List(); - Diagnostics.Assert(_functionContext._outputPipe is null, "Output pipe should not be set yet."); + Diagnostics.Assert(_functionContext._outputPipe == null, "Output pipe should not be set yet."); _functionContext._outputPipe = new Pipe(resultList); RunClause( clause: _runOptimized ? _scriptBlock.DynamicParamBlock : _scriptBlock.UnoptimizedDynamicParamBlock, @@ -2406,7 +2406,7 @@ public object GetDynamicParameters() /// internal void SetLocalsTupleForNewScope(SessionStateScope scope) { - Diagnostics.Assert(scope.LocalsTuple is null, "a newly created scope shouldn't have it's tuple set."); + Diagnostics.Assert(scope.LocalsTuple == null, "a newly created scope shouldn't have it's tuple set."); scope.LocalsTuple = _localsTuple; } diff --git a/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs b/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs index c532bd66532..d340f8c2667 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs @@ -170,7 +170,7 @@ internal static object GetMDArrayValueOrSlice(Array array, object indexes) indexArray = null; } - if (indexArray is null || indexArray.Length != array.Rank) + if (indexArray == null || indexArray.Length != array.Rank) { if (whyFailed != null) { @@ -216,7 +216,7 @@ private static void ReportIndexingError(Array array, object index, Exception rea // Convert this index into something printable (we hope)... string msgString = IndexStringMessage(index); - if (reason is null) + if (reason == null) { throw InterpreterError.NewInterpreterException(index, typeof(RuntimeException), null, "NeedMultidimensionalIndex", ParserStrings.NeedMultidimensionalIndex, array.Rank, msgString); @@ -278,7 +278,7 @@ internal static object GetNonIndexable(object target, object[] indices) } var context = LocalPipeline.GetExecutionContextFromTLS(); - if (context is null || !context.IsStrictVersion(2)) + if (context == null || !context.IsStrictVersion(2)) { return AutomationNull.Value; } diff --git a/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs b/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs index 8e7cc34df52..7b06697afa1 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs @@ -209,7 +209,7 @@ private void PrepareScriptBlockToInvoke(object instance, object sessionStateInte // If the current thread doesn't have a default Runspace, then an InvalidOperationException will be thrown when invoking the // script block, which is expected. sessionStateToUse = (SessionStateInternal)_sessionStateKeeper.GetSessionState(); - if (sessionStateToUse is null) + if (sessionStateToUse == null) { lock (_defaultSessionStateToUse) { @@ -284,7 +284,7 @@ public static void ValidateSetProperty(Type type, string propertyName, object va { var validateAttributes = type.GetProperty(propertyName).GetCustomAttributes(); var executionContext = LocalPipeline.GetExecutionContextFromTLS(); - var engineIntrinsics = executionContext is null ? null : executionContext.EngineIntrinsics; + var engineIntrinsics = executionContext == null ? null : executionContext.EngineIntrinsics; foreach (var validateAttribute in validateAttributes) { validateAttribute.InternalValidate(value, engineIntrinsics); diff --git a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs index c729061ba63..5a452935c6d 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs @@ -43,12 +43,12 @@ private static CommandProcessorBase AddCommand(PipelineProcessor pipe, var mi = PSObject.Base(commandElements[0].ArgumentValue) as PSModuleInfo; if (mi != null) { - if (mi.ModuleType == ModuleType.Binary && mi.SessionState is null) + if (mi.ModuleType == ModuleType.Binary && mi.SessionState == null) { throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, "CantInvokeInBinaryModule", ParserStrings.CantInvokeInBinaryModule, mi.Name); } - else if (mi.SessionState is null) + else if (mi.SessionState == null) { throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, "CantInvokeInNonImportedModule", ParserStrings.CantInvokeInNonImportedModule, mi.Name); @@ -144,7 +144,7 @@ private static CommandProcessorBase AddCommand(PipelineProcessor pipe, { // CreateCommand doesn't have the context to set InvocationInfo properly // so we'll do it here instead... - if (rte.ErrorRecord.InvocationInfo is null) + if (rte.ErrorRecord.InvocationInfo == null) { InvocationInfo invocationInfo = new InvocationInfo(null, commandExtent, context) { InvocationName = invocationName }; @@ -540,7 +540,7 @@ internal static void InvokePipelineInBackground( var variableName = ((VariableExpressionAst)v).VariablePath.UserPath; // Skip variables that don't exist - if (funcContext._executionContext.EngineSessionState.GetVariable(variableName) is null) + if (funcContext._executionContext.EngineSessionState.GetVariable(variableName) == null) { continue; } @@ -634,7 +634,7 @@ internal static SteppablePipeline GetSteppablePipeline(PipelineAst pipelineAst, var commandTuples = new List, List>>(); ExecutionContext context = LocalPipeline.GetExecutionContextFromTLS(); - if (context is null) + if (context == null) { // If ExecutionContext from TLS is null then we are not in powershell engine thread. string scriptText = scriptBlock.ToString(); @@ -756,7 +756,7 @@ private static CommandParameterInternal GetCommandParameter(CommandParameterAst var argumentAst = commandParameterAst.Argument; var errorPos = commandParameterAst.ErrorPosition; - if (argumentAst is null) + if (argumentAst == null) { return CommandParameterInternal.CreateParameter(commandParameterAst.ParameterName, errorPos.Text, commandParameterAst); } @@ -859,7 +859,7 @@ protected CommandRedirection(RedirectionStream from) internal void UnbindForExpression(FunctionContext funcContext, Pipe[] pipes) { - if (pipes is null) + if (pipes == null) { // The pipes can be null if there was an exception (ideally we'd just call unbind // from a fault, but that isn't supported in a clr dynamic method. @@ -1267,7 +1267,7 @@ internal static void DefineFunction(ExecutionContext context, context, functionDefinitionAst.IsFilter); var expAttribute = scriptBlock.ExperimentalAttribute; - if (expAttribute is null || expAttribute.ToShow) + if (expAttribute == null || expAttribute.ToShow) { context.EngineSessionState.SetFunctionRaw(functionDefinitionAst.Name, scriptBlock, context.EngineSessionState.CurrentScope.ScopeOrigin); @@ -1276,7 +1276,7 @@ internal static void DefineFunction(ExecutionContext context, catch (Exception exception) { var rte = exception as RuntimeException; - if (rte is null) + if (rte == null) { throw ExceptionHandlingOps.ConvertToRuntimeException(exception, functionDefinitionAst.Extent); } @@ -1301,7 +1301,7 @@ internal ScriptBlock GetScriptBlock(ExecutionContext context, bool isFilter) { // We always clone the result, even when creating a new script block, so that the cached // value doesn't hold on to any session state. - Diagnostics.Assert(_scriptBlock is null || _scriptBlock.SessionStateInternal is null, + Diagnostics.Assert(_scriptBlock == null || _scriptBlock.SessionStateInternal == null, "Cached script block should not hold on to session state"); var result = (_scriptBlock ?? (_scriptBlock = new ScriptBlock(_ast, isFilter))).Clone(); @@ -1315,7 +1315,7 @@ internal static class HashtableOps internal static void AddKeyValuePair(IDictionary hashtable, object key, object value, IScriptExtent errorExtent) { key = PSObject.Base(key); - if (key is null) + if (key == null) { throw InterpreterError.NewInterpreterException(hashtable, typeof(RuntimeException), errorExtent, "InvalidNullKey", ParserStrings.InvalidNullKey); @@ -1603,7 +1603,7 @@ internal static void CheckActionPreference(FunctionContext funcContext, Exceptio } var rte = exception as RuntimeException; - if (rte is null) + if (rte == null) { rte = ConvertToRuntimeException(exception, funcContext.CurrentPosition); } @@ -1627,7 +1627,7 @@ internal static void CheckActionPreference(FunctionContext funcContext, Exceptio // handling an exception, then the exception is new, and we // can break on it if requested. if (!rte.WasRethrown && - context.CurrentExceptionBeingHandled is null && + context.CurrentExceptionBeingHandled == null && preference == ActionPreference.Break) { context.Debugger?.Break(rte); @@ -1931,7 +1931,7 @@ internal static void SetErrorVariables(IScriptExtent extent, RuntimeException rt internal static bool ExceptionCannotBeStoppedContinuedOrIgnored(RuntimeException rte, ExecutionContext context) { return context.PropagateExceptionsToEnclosingStatementBlock - || context.ShellFunctionErrorOutputPipe is null + || context.ShellFunctionErrorOutputPipe == null || context.CurrentPipelineStopping || rte.SuppressPromptInInterpreter || rte is PipelineStoppedException; @@ -1946,12 +1946,12 @@ internal static bool ExceptionCannotBeStoppedContinuedOrIgnored(RuntimeException /// True if it was able to report the error. internal static bool ReportErrorRecord(IScriptExtent extent, RuntimeException rte, ExecutionContext context) { - if (context.ShellFunctionErrorOutputPipe is null) + if (context.ShellFunctionErrorOutputPipe == null) return false; Diagnostics.Assert(rte.ErrorRecord != null, "The runtime exception's error record was null"); - if (rte.ErrorRecord.InvocationInfo is null && extent != null && extent != PositionUtilities.EmptyExtent) + if (rte.ErrorRecord.InvocationInfo == null && extent != null && extent != PositionUtilities.EmptyExtent) rte.ErrorRecord.SetInvocationInfo(new InvocationInfo(null, extent, context)); PSObject errorWrap = PSObject.AsPSObject(new ErrorRecord(rte.ErrorRecord, rte)); @@ -2019,7 +2019,7 @@ internal static RuntimeException ConvertToException(object result, IScriptExtent internal static RuntimeException ConvertToRuntimeException(Exception exception, IScriptExtent extent) { RuntimeException runtimeException = exception as RuntimeException; - if (runtimeException is null) + if (runtimeException == null) { var icer = exception as IContainsErrorRecord; var er = icer != null @@ -2050,7 +2050,7 @@ internal static void ConvertToMethodInvocationException(Exception exception, Typ if ((exception is FlowControlException || exception is ScriptCallDepthException || exception is PipelineStoppedException) && - ((memberInfo is null) || ((memberInfo.DeclaringType != typeof(PowerShell)) && (memberInfo.DeclaringType != typeof(Pipeline))))) + ((memberInfo == null) || ((memberInfo.DeclaringType != typeof(PowerShell)) && (memberInfo.DeclaringType != typeof(Pipeline))))) { return; } @@ -2104,7 +2104,7 @@ internal static Type ResolveTypeName(ITypeName typeName, IScriptExtent errorPos) Exception exception; var result = TypeResolver.ResolveITypeName(typeName, out exception); - if (result is null) + if (result == null) { if (exception != null) { @@ -2167,11 +2167,11 @@ internal static bool IsInstance(object left, object right) Type rType = rval as Type; - if (rType is null) + if (rType == null) { rType = ParserOps.ConvertTo(rval, null); - if (rType is null) + if (rType == null) { // "the right operand of '-is' must be a type" throw InterpreterError.NewInterpreterException(rval, typeof(RuntimeException), @@ -2195,7 +2195,7 @@ internal static bool IsInstance(object left, object right) internal static object AsOperator(object left, Type type) { - if (type is null) + if (type == null) { throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, "AsOperatorRequiresType", ParserStrings.AsOperatorRequiresType); @@ -2459,7 +2459,7 @@ internal static string ResolveFilePath(IScriptExtent errorExtent, object obj, Ex } // Make sure at least one file was found... - if (filePaths is null || filePaths.Count < 1) + if (filePaths == null || filePaths.Count < 1) { // "No files matching '{0}' were found.." throw InterpreterError.NewInterpreterException(filePath, typeof(RuntimeException), errorExtent, @@ -2478,7 +2478,7 @@ internal static string ResolveFilePath(IScriptExtent errorExtent, object obj, Ex catch (RuntimeException rte) { // Add the invocation info to this command... - if (rte.ErrorRecord != null && rte.ErrorRecord.InvocationInfo is null) + if (rte.ErrorRecord != null && rte.ErrorRecord.InvocationInfo == null) rte.ErrorRecord.SetInvocationInfo(new InvocationInfo(null, errorExtent, context)); throw; } @@ -2546,7 +2546,7 @@ internal static object Where(IEnumerator enumerator, ScriptBlock expressionSB, W // Optimization to speed up the case where there is no condition expression // Useful when using selection mode and number to return to do fast list // slicing. - if (expressionSB is null) + if (expressionSB == null) { if (selectionMode == WhereOperatorSelectionMode.Default) { @@ -2653,7 +2653,7 @@ internal static object Where(IEnumerator enumerator, ScriptBlock expressionSB, W if (returnTheRest) { - matches.Add(ie is null ? null : PSObject.AsPSObject(ie)); + matches.Add(ie == null ? null : PSObject.AsPSObject(ie)); if (numberToReturn > 0 && matches.Count >= numberToReturn) { break; @@ -2683,30 +2683,30 @@ internal static object Where(IEnumerator enumerator, ScriptBlock expressionSB, W if (matches.Count < numberToReturn) { - matches.Add(ie is null ? null : PSObject.AsPSObject(ie)); + matches.Add(ie == null ? null : PSObject.AsPSObject(ie)); } else { if (numberToReturn == 1) { - matches[0] = ie is null ? null : PSObject.AsPSObject(ie); + matches[0] = ie == null ? null : PSObject.AsPSObject(ie); } else { // Maintains a sliding window matches.RemoveAt(0); - matches.Add(ie is null ? null : PSObject.AsPSObject(ie)); + matches.Add(ie == null ? null : PSObject.AsPSObject(ie)); } } } else if (selectionMode == WhereOperatorSelectionMode.SkipUntil) { - matches.Add(ie is null ? null : PSObject.AsPSObject(ie)); + matches.Add(ie == null ? null : PSObject.AsPSObject(ie)); returnTheRest = true; } else { - matches.Add(ie is null ? null : PSObject.AsPSObject(ie)); + matches.Add(ie == null ? null : PSObject.AsPSObject(ie)); } if (selectionMode != WhereOperatorSelectionMode.Last) @@ -2726,7 +2726,7 @@ internal static object Where(IEnumerator enumerator, ScriptBlock expressionSB, W else if (selectionMode == WhereOperatorSelectionMode.Until) { // no match so in the until case, we add the value until the count is reached - matches.Add(ie is null ? null : PSObject.AsPSObject(ie)); + matches.Add(ie == null ? null : PSObject.AsPSObject(ie)); if (numberToReturn > 0 && matches.Count >= numberToReturn) { break; @@ -2735,7 +2735,7 @@ internal static object Where(IEnumerator enumerator, ScriptBlock expressionSB, W else if (selectionMode == WhereOperatorSelectionMode.Split) { // If in split mode, record both matched and noteMatched elements. - notMatched.Add(ie is null ? null : PSObject.AsPSObject(ie)); + notMatched.Add(ie == null ? null : PSObject.AsPSObject(ie)); } } @@ -2748,7 +2748,7 @@ internal static object Where(IEnumerator enumerator, ScriptBlock expressionSB, W while (MoveNext(context, enumerator)) { var ie = Current(enumerator); - notMatched.Add(ie is null ? null : PSObject.AsPSObject(ie)); + notMatched.Add(ie == null ? null : PSObject.AsPSObject(ie)); } return new object[] { matches, notMatched }; @@ -2769,7 +2769,7 @@ internal static object ForEach(IEnumerator enumerator, object expression, object { Diagnostics.Assert(enumerator != null, "The ForEach() operator should never receive a null enumerator value from the runtime."); Diagnostics.Assert(arguments != null, "The ForEach() operator should never receive a null value for the 'arguments' parameter from the runtime."); - if (expression is null) + if (expression == null) { throw new ArgumentNullException(nameof(expression)); } @@ -2836,7 +2836,7 @@ internal static object ForEach(IEnumerator enumerator, object expression, object } } - if (resultCollection is null) + if (resultCollection == null) { throw InterpreterError.NewInterpreterException(expression, typeof(RuntimeException), null, "ForEachTypeConversionFailed", ParserStrings.ForEachTypeConversionFailed, ParserOps.ConvertTo(targetType, null)); @@ -2913,7 +2913,7 @@ internal static object ForEach(IEnumerator enumerator, object expression, object // handle the null case with PowerShell semantics: // - retrieving a property on null adds a null to the result set // - setting a property on null or trying to invoke a method is an error - if (current is null) + if (current == null) { if (arguments.Length == 0) { @@ -2938,7 +2938,7 @@ internal static object ForEach(IEnumerator enumerator, object expression, object PSMemberInfo member = ie.Members[name]; // If the property was not found, check strict mode... - if (member is null) + if (member == null) { if (context.IsStrictVersion(2)) { diff --git a/src/System.Management.Automation/engine/runtime/Operations/VariableOps.cs b/src/System.Management.Automation/engine/runtime/Operations/VariableOps.cs index a2c6cc93a97..d337c56ab2b 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/VariableOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/VariableOps.cs @@ -39,9 +39,9 @@ internal static object SetVariableValue(VariablePath variablePath, object value, SessionStateScope scope; PSVariable var = sessionState.GetVariableItem(variablePath, out scope, origin); - if (var is null) + if (var == null) { - var attributes = attributeAsts is null + var attributes = attributeAsts == null ? new Collection() : GetAttributeCollection(attributeAsts); var = new PSVariable(variablePath.UnqualifiedPath, value, ScopedItemOptions.None, attributes); @@ -117,7 +117,7 @@ private static bool ThrowStrictModeUndefinedVariable(ExecutionContext executionC { // In some limited cases, the compiler knows we don't want an error, like when we're backing up // $foreach and $switch, which might not be set. In that case, the ast passed is null. - if (varAst is null) + if (varAst == null) { return false; } @@ -216,7 +216,7 @@ internal static PSReference GetVariableAsRef(VariablePath variablePath, Executio SessionStateScope scope; PSVariable var = sessionState.GetVariableItem(variablePath, out scope, origin); - if (var is null) + if (var == null) { throw InterpreterError.NewInterpreterException(variablePath, typeof(RuntimeException), null, "NonExistingVariableReference", @@ -224,7 +224,7 @@ internal static PSReference GetVariableAsRef(VariablePath variablePath, Executio } object value = var.Value; - if (staticType is null && value != null) + if (staticType == null && value != null) { value = PSObject.Base(value); if (value != null) @@ -233,7 +233,7 @@ internal static PSReference GetVariableAsRef(VariablePath variablePath, Executio } } - if (staticType is null) + if (staticType == null) { var declaredType = var.Attributes.OfType().FirstOrDefault(); staticType = declaredType != null ? declaredType.TargetType : typeof(LanguagePrimitives.Null); diff --git a/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs b/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs index 4db40c9de8d..e2409eba626 100644 --- a/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs +++ b/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs @@ -48,7 +48,7 @@ public override AstVisitAction VisitPipeline(PipelineAst pipelineAst) // know that we have at least: // * a NamedBlockAst (the end block) // * a ScriptBlockAst (the ast we're comparing to) - if (pipelineAst.GetPureExpression() is null || pipelineAst.Parent.Parent == ScriptBeingConverted) + if (pipelineAst.GetPureExpression() == null || pipelineAst.Parent.Parent == ScriptBeingConverted) { ThrowError( new ScriptBlockToPowerShellNotSupportedException( @@ -226,7 +226,7 @@ internal static PowerShell Convert(ScriptBlockAst body, { ExecutionContext.CheckStackDepth(); - if (args is null) + if (args == null) { args = Array.Empty(); } @@ -257,7 +257,7 @@ internal static PowerShell Convert(ScriptBlockAst body, // When the context is null (or they haven't supplied any variables), throw, but only if we really need the // context (basically, if we have some variable reference to resolve). - if (context is null && (checker.HasUsingExpr || checker.UsesParameter) && (variables is null)) + if (context == null && (checker.HasUsingExpr || checker.UsesParameter) && (variables == null)) { throw new PSInvalidOperationException(AutomationExceptions.CantConvertScriptBlockWithNoContext); } @@ -387,7 +387,7 @@ private static Tuple, object[]> GetUsingValues(Ast bo if (variables != null) { var variableAst = usingAst.SubExpression as VariableExpressionAst; - if (variableAst is null) + if (variableAst == null) { throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), usingAst.Extent, "CantGetUsingExpressionValueWithSpecifiedVariableDictionary", AutomationExceptions.CantGetUsingExpressionValueWithSpecifiedVariableDictionary, usingAst.Extent.Text); @@ -479,7 +479,7 @@ private static bool HasUsingExpressionsInDifferentScopes(UsingExpressionAst usin // We find the closest parent ScriptBlockAst of the current UsingExpression, which represents the scope // that the current UsingExpression is in. - if (sbClosestToPreviousUsingExpr is null) + if (sbClosestToPreviousUsingExpr == null) { // The current UsingExpression is the first one to be analyzed. sbClosestToPreviousUsingExpr = sbAst; @@ -503,7 +503,7 @@ private static bool HasUsingExpressionsInDifferentScopes(UsingExpressionAst usin // must be in 'Parameters' property of this FunctionDefinitionAst. // In this case, the 'Body' of this FunctionDefinitionAst represents the scope that the UsingExpression is in. - if (sbClosestToPreviousUsingExpr is null) + if (sbClosestToPreviousUsingExpr == null) { // The current UsingExpression is the first one to be analyzed. sbClosestToPreviousUsingExpr = funcAst.Body; @@ -697,7 +697,7 @@ private string GetCommandName(CommandElementAst commandNameAst, bool isTrustedIn if (exprAst != null) { var value = GetExpressionValue(exprAst, isTrustedInput); - if (value is null) + if (value == null) { ScriptBlockToPowerShellChecker.ThrowError( new ScriptBlockToPowerShellNotSupportedException( @@ -735,7 +735,7 @@ private string GetCommandName(CommandElementAst commandNameAst, bool isTrustedIn private void GetSplattedVariable(VariableExpressionAst variableAst) { - if (_context is null) + if (_context == null) { throw new PSInvalidOperationException(AutomationExceptions.CantConvertScriptBlockWithNoContext); } @@ -755,7 +755,7 @@ private void GetSplattedVariable(VariableExpressionAst variableAst) private object GetExpressionValue(ExpressionAst exprAst, bool isTrustedInput) { // be sure that there's a context at hand - if (_context is null) + if (_context == null) { var rs = RunspaceFactory.CreateRunspace(InitialSessionState.Create()); rs.Open(); diff --git a/src/System.Management.Automation/engine/scriptparameterbindercontroller.cs b/src/System.Management.Automation/engine/scriptparameterbindercontroller.cs index b3f0f6757d1..9a63b1969a8 100644 --- a/src/System.Management.Automation/engine/scriptparameterbindercontroller.cs +++ b/src/System.Management.Automation/engine/scriptparameterbindercontroller.cs @@ -275,7 +275,7 @@ private void HandleRemainingArguments(Collection argum // This is important when splatting, we reconstruct the parameter if the // value is splatted. var parameterText = new PSObject(new string(parameter.ParameterText)); - if (parameterText.Properties[NotePropertyNameForSplattingParametersInArgs] is null) + if (parameterText.Properties[NotePropertyNameForSplattingParametersInArgs] == null) { var noteProperty = new PSNoteProperty(NotePropertyNameForSplattingParametersInArgs, parameter.ParameterName) diff --git a/src/System.Management.Automation/engine/serialization.cs b/src/System.Management.Automation/engine/serialization.cs index 6094310cbb7..b70c7037c26 100644 --- a/src/System.Management.Automation/engine/serialization.cs +++ b/src/System.Management.Automation/engine/serialization.cs @@ -216,12 +216,12 @@ internal Serializer(XmlWriter writer, int depth, bool useDepthFromTypes) /// Serialization context. internal Serializer(XmlWriter writer, SerializationContext context) { - if (writer is null) + if (writer == null) { throw PSTraceSource.NewArgumentException(nameof(writer)); } - if (context is null) + if (context == null) { throw PSTraceSource.NewArgumentException(nameof(context)); } @@ -482,7 +482,7 @@ internal Deserializer(XmlReader reader) /// internal Deserializer(XmlReader reader, DeserializationContext context) { - if (reader is null) + if (reader == null) { throw PSTraceSource.NewArgumentNullException(nameof(reader)); } @@ -664,12 +664,12 @@ internal static void AddDeserializationPrefix(ref string type) /// true if is either a live or deserialized instance of class or one of its subclasses; false otherwise. internal static bool IsInstanceOfType(object o, Type type) { - if (type is null) + if (type == null) { throw PSTraceSource.NewArgumentNullException(nameof(type)); } - if (o is null) + if (o == null) { return false; } @@ -685,12 +685,12 @@ internal static bool IsInstanceOfType(object o, Type type) /// true if is a deserialized instance of class or one of its subclasses; false otherwise. internal static bool IsDeserializedInstanceOfType(object o, Type type) { - if (type is null) + if (type == null) { throw PSTraceSource.NewArgumentNullException(nameof(type)); } - if (o is null) + if (o == null) { return false; } @@ -719,7 +719,7 @@ internal static bool IsDeserializedInstanceOfType(object o, Type type) internal static string MaskDeserializationPrefix(string typeName) { - if (typeName is null) + if (typeName == null) { return null; } @@ -941,7 +941,7 @@ int depth Dbg.Assert(depth >= 0, "depth should always be greater or equal to zero"); this.CheckIfStopping(); - if (source is null) + if (source == null) { WriteNull(streamName, property); return; @@ -1495,7 +1495,7 @@ int depth } bool writeToString = true; - if (mshSource.ToStringFromDeserialization is null) // continue to write ToString from deserialized objects, but... + if (mshSource.ToStringFromDeserialization == null) // continue to write ToString from deserialized objects, but... { if (mshSource.ImmediateBaseObjectIsEmpty) // ... don't write ToString for property bags { @@ -1683,7 +1683,7 @@ string toStringValue if (typeNames.Count > 0) { string typeNameHierarchyReferenceId = _typeRefIdHandler.GetRefId(typeNames); - if (typeNameHierarchyReferenceId is null) + if (typeNameHierarchyReferenceId == null) { WriteStartElement(SerializationStrings.TypeNamesTag); @@ -1920,7 +1920,7 @@ IEnumerable specificPropertiesToSerialize Dbg.Assert(source != null, "caller should validate the information"); IEnumerable extendedMembersEnumerable = null; - if (specificPropertiesToSerialize is null) + if (specificPropertiesToSerialize == null) { // Get only extended members including hidden members from the psobect source. PSMemberInfoIntegratingCollection membersToSearch = @@ -1983,7 +1983,7 @@ int depth foreach (PSMemberInfo info in propertyCollection) { PSProperty prop = info as PSProperty; - if (prop is null) + if (prop == null) { continue; } @@ -2163,7 +2163,7 @@ int depth } Dbg.Assert(key != null, "Dictionary keys should never be null"); - if (key is null) break; + if (key == null) break; WriteStartElement(SerializationStrings.DictionaryEntryTag); WriteOneObject(key, null, SerializationStrings.DictionaryKey, depth); @@ -2286,7 +2286,7 @@ private int GetDepthOfSerialization(object source, int depth) Dbg.Assert(source != null, "Caller should verify source != null"); PSObject pso = PSObject.AsPSObject(source); - if (pso is null) + if (pso == null) { return depth; } @@ -2427,7 +2427,7 @@ TypeSerializationInfo entry Dbg.Assert(source != null, "caller should have validated the information"); Dbg.Assert(entry != null, "caller should have validated the information"); - if (entry.Serializer is null) + if (entry.Serializer == null) { // we are not using GetToString, because we assume that // ToString() for primitive types never throws @@ -3132,13 +3132,13 @@ private object ReadOneDeserializedObject(out string streamName, out bool isKnown { string refId = _reader.GetAttribute(SerializationStrings.ReferenceIdAttribute); - if (refId is null) + if (refId == null) { throw NewXmlException(Serialization.AttributeExpected, null, SerializationStrings.ReferenceIdAttribute); } object duplicate = _objectRefIdHandler.GetReferencedObject(refId); - if (duplicate is null) + if (duplicate == null) { throw NewXmlException(Serialization.InvalidReferenceId, null, refId); } @@ -3217,7 +3217,7 @@ private bool RehydrateCimInstanceProperty( } CimProperty cimProperty = cimInstance.CimInstanceProperties[deserializedProperty.Name]; - if (cimProperty is null) + if (cimProperty == null) { return false; } @@ -3229,13 +3229,13 @@ private bool RehydrateCimInstanceProperty( PSObject psoPropertyValue = PSObject.AsPSObject(propertyValue); if (psoPropertyValue.BaseObject is ArrayList) { - if ((psoPropertyValue.InternalTypeNames is null) || (psoPropertyValue.InternalTypeNames.Count == 0)) + if ((psoPropertyValue.InternalTypeNames == null) || (psoPropertyValue.InternalTypeNames.Count == 0)) { return false; } string originalArrayTypeName = Deserializer.MaskDeserializationPrefix(psoPropertyValue.InternalTypeNames[0]); - if (originalArrayTypeName is null) + if (originalArrayTypeName == null) { return false; } @@ -3302,13 +3302,13 @@ private bool RehydrateCimInstanceProperty( private CimClass RehydrateCimClass(PSPropertyInfo classMetadataProperty) { - if ((classMetadataProperty is null) || (classMetadataProperty.Value is null)) + if ((classMetadataProperty == null) || (classMetadataProperty.Value == null)) { return null; } IEnumerable deserializedClasses = LanguagePrimitives.GetEnumerable(classMetadataProperty.Value); - if (deserializedClasses is null) + if (deserializedClasses == null) { return null; } @@ -3324,7 +3324,7 @@ private CimClass RehydrateCimClass(PSPropertyInfo classMetadataProperty) { parentClass = currentClass; - if (deserializedClass is null) + if (deserializedClass == null) { return null; } @@ -3332,7 +3332,7 @@ private CimClass RehydrateCimClass(PSPropertyInfo classMetadataProperty) PSObject psoDeserializedClass = PSObject.AsPSObject(deserializedClass); PSPropertyInfo namespaceProperty = psoDeserializedClass.InstanceMembers[InternalDeserializer.CimNamespaceProperty] as PSPropertyInfo; - if (namespaceProperty is null) + if (namespaceProperty == null) { return null; } @@ -3340,7 +3340,7 @@ private CimClass RehydrateCimClass(PSPropertyInfo classMetadataProperty) string cimNamespace = namespaceProperty.Value as string; PSPropertyInfo classNameProperty = psoDeserializedClass.InstanceMembers[InternalDeserializer.CimClassNameProperty] as PSPropertyInfo; - if (classNameProperty is null) + if (classNameProperty == null) { return null; } @@ -3348,7 +3348,7 @@ private CimClass RehydrateCimClass(PSPropertyInfo classMetadataProperty) string cimClassName = classNameProperty.Value as string; PSPropertyInfo computerNameProperty = psoDeserializedClass.InstanceMembers[InternalDeserializer.CimServerNameProperty] as PSPropertyInfo; - if (computerNameProperty is null) + if (computerNameProperty == null) { return null; } @@ -3356,13 +3356,13 @@ private CimClass RehydrateCimClass(PSPropertyInfo classMetadataProperty) string computerName = computerNameProperty.Value as string; PSPropertyInfo hashCodeProperty = psoDeserializedClass.InstanceMembers[InternalDeserializer.CimHashCodeProperty] as PSPropertyInfo; - if (hashCodeProperty is null) + if (hashCodeProperty == null) { return null; } var hashCodeObject = hashCodeProperty.Value; - if (hashCodeObject is null) + if (hashCodeObject == null) { return null; } @@ -3387,7 +3387,7 @@ private CimClass RehydrateCimClass(PSPropertyInfo classMetadataProperty) } PSPropertyInfo miXmlProperty = psoDeserializedClass.InstanceMembers[InternalDeserializer.CimMiXmlProperty] as PSPropertyInfo; - if ((miXmlProperty is null) || (miXmlProperty.Value is null)) + if ((miXmlProperty == null) || (miXmlProperty.Value == null)) { return null; } @@ -3433,7 +3433,7 @@ private PSObject RehydrateCimInstance(PSObject deserializedObject) PSPropertyInfo classMetadataProperty = deserializedObject.InstanceMembers[CimClassMetadataProperty] as PSPropertyInfo; CimClass cimClass = RehydrateCimClass(classMetadataProperty); - if (cimClass is null) + if (cimClass == null) { return deserializedObject; } @@ -3474,7 +3474,7 @@ private PSObject RehydrateCimInstance(PSObject deserializedObject) foreach (PSMemberInfo deserializedMemberInfo in deserializedObject.AdaptedMembers) { PSPropertyInfo deserializedProperty = deserializedMemberInfo as PSPropertyInfo; - if (deserializedProperty is null) + if (deserializedProperty == null) { continue; } @@ -3495,7 +3495,7 @@ private PSObject RehydrateCimInstance(PSObject deserializedObject) foreach (PSMemberInfo deserializedMemberInfo in deserializedObject.InstanceMembers) { PSPropertyInfo deserializedProperty = deserializedMemberInfo as PSPropertyInfo; - if (deserializedProperty is null) + if (deserializedProperty == null) { continue; } @@ -3548,7 +3548,7 @@ internal object ReadOneObject(out string streamName) bool isKnownPrimitiveType; object result = ReadOneDeserializedObject(out streamName, out isKnownPrimitiveType); - if (result is null) + if (result == null) { return null; } @@ -3595,7 +3595,7 @@ internal object ReadOneObject(out string streamName) mshSource.InternalTypeNames.Key, targetType.FullName, rehydrationException.ToString(), - rehydrationException.InnerException is null + rehydrationException.InnerException == null ? string.Empty : rehydrationException.InnerException.ToString()); } @@ -3787,13 +3787,13 @@ private void ReadTypeNames(PSObject dso) { string refId = _reader.GetAttribute(SerializationStrings.ReferenceIdAttribute); s_trace.WriteLine("Processing TypeNamesReferenceTag with refId {0}", refId); - if (refId is null) + if (refId == null) { throw NewXmlException(Serialization.AttributeExpected, null, SerializationStrings.ReferenceIdAttribute); } ConsolidatedString typeNames = _typeRefIdHandler.GetReferencedObject(refId); - if (typeNames is null) + if (typeNames == null) { throw NewXmlException(Serialization.InvalidTypeHierarchyReferenceId, null, refId); } @@ -4026,7 +4026,7 @@ private object ReadDictionary(ContainerType ct) object key = ReadOneObject(); - if (key is null) + if (key == null) { throw NewXmlException(Serialization.NullAsDictionaryKey, null); } @@ -4659,7 +4659,7 @@ internal static object DeserializeProgressRecord(InternalDeserializer deserializ activityId = int.Parse(deserializer.ReadDecodedElementString(SerializationStrings.ProgressRecordActivityId), CultureInfo.InvariantCulture); object tmp = deserializer.ReadOneObject(); - currentOperation = (tmp is null) ? null : tmp.ToString(); + currentOperation = (tmp == null) ? null : tmp.ToString(); parentActivityId = int.Parse(deserializer.ReadDecodedElementString(SerializationStrings.ProgressRecordParentActivityId), CultureInfo.InvariantCulture); percentComplete = int.Parse(deserializer.ReadDecodedElementString(SerializationStrings.ProgressRecordPercentComplete), CultureInfo.InvariantCulture); @@ -4905,7 +4905,7 @@ params object[] args private string ReadNameAttribute() { string encodedName = _reader.GetAttribute(SerializationStrings.NameAttribute); - if (encodedName is null) + if (encodedName == null) { throw NewXmlException(Serialization.AttributeExpected, null, SerializationStrings.NameAttribute); } @@ -5317,7 +5317,7 @@ internal static object GetPropertyValue(PSObject psObject, string propertyName) { PSNoteProperty property = (PSNoteProperty)psObject.Properties[propertyName]; - if (property is null) + if (property == null) { return null; } @@ -5332,7 +5332,7 @@ internal static object GetPsObjectPropertyBaseObject(PSObject psObject, string p { PSObject propertyPsObject = (PSObject)GetPropertyValue(psObject, propertyName); - if (propertyPsObject is null) + if (propertyPsObject == null) { return null; } @@ -5510,7 +5510,7 @@ internal static string GetToString(object source) internal static string GetToStringForPrimitiveObject(PSObject pso) { // if object is not wrapped in a PSObject, then nothing modifies the ToString value of the primitive object - if (pso is null) + if (pso == null) { return null; } @@ -5526,7 +5526,7 @@ internal static string GetToStringForPrimitiveObject(PSObject pso) if (token != null) { string originalToString = GetToString(pso.BaseObject); - if (originalToString is null || !string.Equals(token, originalToString, StringComparison.Ordinal)) + if (originalToString == null || !string.Equals(token, originalToString, StringComparison.Ordinal)) { return token; } @@ -5538,7 +5538,7 @@ internal static string GetToStringForPrimitiveObject(PSObject pso) internal static PSMemberInfoInternalCollection GetSpecificPropertiesToSerialize(PSObject source, Collection> allPropertiesCollection, TypeTable typeTable) { - if (source is null) + if (source == null) { return null; } @@ -5562,7 +5562,7 @@ internal static PSMemberInfoInternalCollection GetSpecificProper foreach (string propertyName in namesOfPropertiesToSerialize) { PSPropertyInfo property = allProperties[propertyName]; - if (property is null) + if (property == null) { PSEtwLog.LogAnalyticWarning( PSEventId.Serializer_SpecificPropertyMissing, PSOpcode.Exception, PSTask.Serialization, @@ -5599,14 +5599,14 @@ internal static object GetPropertyValueInThreadSafeManner(PSPropertyInfo propert } PSScriptProperty script = property as PSScriptProperty; - Dbg.Assert(script is null || script.GetterScript != null, "scriptProperty.IsGettable => (scriptProperty.GetterScript != null)"); + Dbg.Assert(script == null || script.GetterScript != null, "scriptProperty.IsGettable => (scriptProperty.GetterScript != null)"); if ((script != null) && (!canUseDefaultRunspaceInThreadSafeManner)) { PSEtwLog.LogAnalyticWarning( PSEventId.Serializer_ScriptPropertyWithoutRunspace, PSOpcode.Exception, PSTask.Serialization, PSKeyword.Serializer | PSKeyword.UseAlwaysAnalytic, property.Name, - property.instance is null ? string.Empty : PSObject.GetTypeNames(property.instance).Key, + property.instance == null ? string.Empty : PSObject.GetTypeNames(property.instance).Key, script.GetterScript.ToString()); success = false; @@ -5625,9 +5625,9 @@ internal static object GetPropertyValueInThreadSafeManner(PSPropertyInfo propert PSEventId.Serializer_PropertyGetterFailed, PSOpcode.Exception, PSTask.Serialization, PSKeyword.Serializer | PSKeyword.UseAlwaysAnalytic, property.Name, - property.instance is null ? string.Empty : PSObject.GetTypeNames(property.instance).Key, + property.instance == null ? string.Empty : PSObject.GetTypeNames(property.instance).Key, e.ToString(), - e.InnerException is null ? string.Empty : e.InnerException.ToString()); + e.InnerException == null ? string.Empty : e.InnerException.ToString()); success = false; return null; @@ -5649,13 +5649,13 @@ private class WeakReferenceEqualityComparer : IEqualityComparer public bool Equals(WeakReference x, WeakReference y) { object tx = x.Target; - if (tx is null) + if (tx == null) { return false; // collected object is not equal to anything (object.ReferenceEquals(null, null) == true) } object ty = y.Target; - if (ty is null) + if (ty == null) { return false; // collected object is not equal to anything (object.ReferenceEquals(null, null) == true) } @@ -5666,7 +5666,7 @@ public bool Equals(WeakReference x, WeakReference y) public int GetHashCode(WeakReference obj) { object t = obj.Target; - if (t is null) + if (t == null) { // collected object doesn't have a hash code // return an arbitrary hashcode here and fall back on Equal method for comparison @@ -5905,7 +5905,7 @@ public PSPrimitiveDictionary() public PSPrimitiveDictionary(Hashtable other) : base(StringComparer.OrdinalIgnoreCase) { - if (other is null) + if (other == null) { throw new ArgumentNullException(nameof(other)); } @@ -5941,7 +5941,7 @@ private string VerifyKey(object key) { key = PSObject.Base(key); string keyAsString = key as string; - if (keyAsString is null) + if (keyAsString == null) { string message = StringUtil.Format(Serialization.PrimitiveHashtableInvalidKey, key.GetType().FullName); @@ -5983,7 +5983,7 @@ private string VerifyKey(object key) private void VerifyValue(object value) { // null is a primitive type - if (value is null) + if (value == null) { return; } @@ -6546,7 +6546,7 @@ internal static bool TryPathGet(IDictionary data, out T result, params string Dbg.Assert(keys.Length >= 1, "Caller should verify that keys.Length >= 1"); Dbg.Assert(keys[0] != null, "Caller should verify that keys[i] != null"); - if (data is null || !data.Contains(keys[0])) + if (data == null || !data.Contains(keys[0])) { result = default(T); return false; @@ -6691,12 +6691,12 @@ public override bool CanConvertFrom(PSObject sourceValue, Type destinationType) /// If no conversion was possible. public override object ConvertFrom(PSObject sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) { - if (destinationType is null) + if (destinationType == null) { throw PSTraceSource.NewArgumentNullException(nameof(destinationType)); } - if (sourceValue is null) + if (sourceValue == null) { throw new PSInvalidCastException( "InvalidCastWhenRehydratingFromNull", @@ -6740,7 +6740,7 @@ private static object ConvertFrom(PSObject o, Func converter) { if (member.MemberType == (member.MemberType & (PSMemberTypes.Properties | PSMemberTypes.MemberSet | PSMemberTypes.PropertySet))) { - if (rehydratedPSObject.Members[member.Name] is null) + if (rehydratedPSObject.Members[member.Name] == null) { rehydratedPSObject.InstanceMembers.Add(member); returnPSObject = true; @@ -6857,14 +6857,14 @@ internal static T GetPropertyValue(PSObject pso, string propertyName, Rehydra Dbg.Assert(!string.IsNullOrEmpty(propertyName), "Caller should verify propertyName != null"); PSPropertyInfo property = pso.Properties[propertyName]; - if ((property is null) && (RehydrationFlags.MissingPropertyOk == (flags & RehydrationFlags.MissingPropertyOk))) + if ((property == null) && (RehydrationFlags.MissingPropertyOk == (flags & RehydrationFlags.MissingPropertyOk))) { return default(T); } else { object propertyValue = property.Value; - if ((propertyValue is null) && (RehydrationFlags.NullValueOk == (flags & RehydrationFlags.NullValueOk))) + if ((propertyValue == null) && (RehydrationFlags.NullValueOk == (flags & RehydrationFlags.NullValueOk))) { return default(T); } @@ -6880,7 +6880,7 @@ private static ListType RehydrateList(PSObject pso, string p where ListType : IList, new() { ArrayList deserializedList = GetPropertyValue(pso, propertyName, flags); - if (deserializedList is null) + if (deserializedList == null) { if (RehydrationFlags.NullValueMeansEmptyList == (flags & RehydrationFlags.NullValueMeansEmptyList)) { @@ -7206,7 +7206,7 @@ internal static PSSenderInfo RehydratePSSenderInfo(PSObject pso) PSObject userIdentity = GetPropertyValue(userInfo, "Identity"); PSObject certDetails = GetPropertyValue(userIdentity, "CertificateDetails"); - PSCertificateDetails psCertDetails = certDetails is null ? null : new PSCertificateDetails( + PSCertificateDetails psCertDetails = certDetails == null ? null : new PSCertificateDetails( GetPropertyValue(certDetails, "Subject"), GetPropertyValue(certDetails, "IssuerName"), GetPropertyValue(certDetails, "IssuerThumbprint")); @@ -7274,13 +7274,13 @@ private static T RehydrateObjectSecurity(PSObject pso) /// public static UInt32 GetParameterSetMetadataFlags(PSObject instance) { - if (instance is null) + if (instance == null) { throw PSTraceSource.NewArgumentNullException(nameof(instance)); } ParameterSetMetadata parameterSetMetadata = instance.BaseObject as ParameterSetMetadata; - if (parameterSetMetadata is null) + if (parameterSetMetadata == null) { throw PSTraceSource.NewArgumentNullException(nameof(instance)); } @@ -7296,18 +7296,18 @@ public static UInt32 GetParameterSetMetadataFlags(PSObject instance) /// PSObject containing serialized InvocationInfo. public static PSObject GetInvocationInfo(PSObject instance) { - if (instance is null) + if (instance == null) { throw PSTraceSource.NewArgumentNullException(nameof(instance)); } DebuggerStopEventArgs dbgStopEventArgs = instance.BaseObject as DebuggerStopEventArgs; - if (dbgStopEventArgs is null) + if (dbgStopEventArgs == null) { throw PSTraceSource.NewArgumentNullException(nameof(instance)); } - if (dbgStopEventArgs.InvocationInfo is null) + if (dbgStopEventArgs.InvocationInfo == null) { return null; } @@ -7348,7 +7348,7 @@ private static EntrySelectedBy RehydrateEntrySelectedBy(PSObject deserializedEsb private static WideControlEntryItem RehydrateWideControlEntryItem(PSObject deserializedEntryItem) { var entrySelectedBy = GetPropertyValue(deserializedEntryItem, "EntrySelectedBy", RehydrationFlags.MissingPropertyOk); - if (entrySelectedBy is null) + if (entrySelectedBy == null) { var selectedBy = RehydrateList, string>(deserializedEntryItem, "SelectedBy", RehydrationFlags.MissingPropertyOk); entrySelectedBy = EntrySelectedBy.Get(selectedBy, null); @@ -7378,7 +7378,7 @@ private static ListControlEntryItem RehydrateListControlEntryItem(PSObject deser private static ListControlEntry RehydrateListControlEntry(PSObject deserializedEntry) { var entrySelectedBy = GetPropertyValue(deserializedEntry, "EntrySelectedBy", RehydrationFlags.MissingPropertyOk); - if (entrySelectedBy is null) + if (entrySelectedBy == null) { var selectedBy = RehydrateList, string>(deserializedEntry, "SelectedBy", RehydrationFlags.MissingPropertyOk); entrySelectedBy = EntrySelectedBy.Get(selectedBy, null); @@ -7556,13 +7556,13 @@ private static PSControlGroupBy RehydrateGroupBy(PSObject deserializedGroupBy) /// public static Guid GetFormatViewDefinitionInstanceId(PSObject instance) { - if (instance is null) + if (instance == null) { throw PSTraceSource.NewArgumentNullException(nameof(instance)); } FormatViewDefinition formatViewDefinition = instance.BaseObject as FormatViewDefinition; - if (formatViewDefinition is null) + if (formatViewDefinition == null) { throw PSTraceSource.NewArgumentNullException(nameof(instance)); } @@ -7585,7 +7585,7 @@ private static ExtendedTypeDefinition RehydrateExtendedTypeDefinition(PSObject d // But if a new PowerShell connects to an old endpoint, TypeNames will be missing, so fall back to TypeName in that case. string typeName; var typeNames = RehydrateList, string>(deserializedTypeDefinition, "TypeNames", RehydrationFlags.MissingPropertyOk); - if (typeNames is null || typeNames.Count == 0) + if (typeNames == null || typeNames.Count == 0) { typeName = GetPropertyValue(deserializedTypeDefinition, "TypeName"); } diff --git a/src/System.Management.Automation/help/AliasHelpInfo.cs b/src/System.Management.Automation/help/AliasHelpInfo.cs index 0d40b380844..b51d1b192dc 100644 --- a/src/System.Management.Automation/help/AliasHelpInfo.cs +++ b/src/System.Management.Automation/help/AliasHelpInfo.cs @@ -22,7 +22,7 @@ private AliasHelpInfo(AliasInfo aliasInfo) { _fullHelpObject = new PSObject(); - string name = (aliasInfo.ResolvedCommand is null) ? aliasInfo.UnresolvedCommandName : aliasInfo.ResolvedCommand.Name; + string name = (aliasInfo.ResolvedCommand == null) ? aliasInfo.UnresolvedCommandName : aliasInfo.ResolvedCommand.Name; this.ForwardTarget = name; // A Cmdlet/Function/Script etc can have alias. @@ -92,10 +92,10 @@ internal override PSObject FullHelp /// AliasHelpInfo object. internal static AliasHelpInfo GetHelpInfo(AliasInfo aliasInfo) { - if (aliasInfo is null) + if (aliasInfo == null) return null; - if (aliasInfo.ResolvedCommand is null && aliasInfo.UnresolvedCommandName is null) + if (aliasInfo.ResolvedCommand == null && aliasInfo.UnresolvedCommandName == null) return null; AliasHelpInfo aliasHelpInfo = new AliasHelpInfo(aliasInfo); diff --git a/src/System.Management.Automation/help/AliasHelpProvider.cs b/src/System.Management.Automation/help/AliasHelpProvider.cs index 28cd655e6eb..670c0202bc7 100644 --- a/src/System.Management.Automation/help/AliasHelpProvider.cs +++ b/src/System.Management.Automation/help/AliasHelpProvider.cs @@ -258,7 +258,7 @@ internal override IEnumerable SearchHelp(HelpRequest helpRequest, bool private static bool Match(HelpInfo helpInfo, HelpRequest helpRequest) { - if (helpRequest is null) + if (helpRequest == null) return true; if (0 == (helpRequest.HelpCategory & helpInfo.HelpCategory)) @@ -288,7 +288,7 @@ private static bool Match(string target, string[] patterns) { // patterns should never be null as shell never accepts // empty inputs. Keeping this check as a safe measure. - if (patterns is null || patterns.Length == 0) + if (patterns == null || patterns.Length == 0) return true; foreach (string pattern in patterns) diff --git a/src/System.Management.Automation/help/BaseCommandHelpInfo.cs b/src/System.Management.Automation/help/BaseCommandHelpInfo.cs index 12554ee2f14..0c70b815928 100644 --- a/src/System.Management.Automation/help/BaseCommandHelpInfo.cs +++ b/src/System.Management.Automation/help/BaseCommandHelpInfo.cs @@ -29,11 +29,11 @@ internal PSObject Details { get { - if (this.FullHelp is null) + if (this.FullHelp == null) return null; - if (this.FullHelp.Properties["Details"] is null || - this.FullHelp.Properties["Details"].Value is null) + if (this.FullHelp.Properties["Details"] == null || + this.FullHelp.Properties["Details"].Value == null) { return null; } @@ -51,19 +51,19 @@ internal override string Name get { PSObject commandDetails = this.Details; - if (commandDetails is null) + if (commandDetails == null) { return string.Empty; } - if (commandDetails.Properties["Name"] is null || - commandDetails.Properties["Name"].Value is null) + if (commandDetails.Properties["Name"] == null || + commandDetails.Properties["Name"].Value == null) { return string.Empty; } string name = commandDetails.Properties["Name"].Value.ToString(); - if (name is null) + if (name == null) return string.Empty; return name.Trim(); @@ -79,13 +79,13 @@ internal override string Synopsis get { PSObject commandDetails = this.Details; - if (commandDetails is null) + if (commandDetails == null) { return string.Empty; } - if (commandDetails.Properties["Description"] is null || - commandDetails.Properties["Description"].Value is null) + if (commandDetails.Properties["Description"] == null || + commandDetails.Properties["Description"].Value == null) { return string.Empty; } @@ -94,21 +94,21 @@ internal override string Synopsis commandDetails.Properties["Description"].Value, typeof(object[]), CultureInfo.InvariantCulture); - if (synopsisItems is null || synopsisItems.Length == 0) + if (synopsisItems == null || synopsisItems.Length == 0) { return string.Empty; } - PSObject firstSynopsisItem = synopsisItems[0] is null ? null : PSObject.AsPSObject(synopsisItems[0]); - if (firstSynopsisItem is null || - firstSynopsisItem.Properties["Text"] is null || - firstSynopsisItem.Properties["Text"].Value is null) + PSObject firstSynopsisItem = synopsisItems[0] == null ? null : PSObject.AsPSObject(synopsisItems[0]); + if (firstSynopsisItem == null || + firstSynopsisItem.Properties["Text"] == null || + firstSynopsisItem.Properties["Text"].Value == null) { return string.Empty; } string synopsis = firstSynopsisItem.Properties["Text"].Value.ToString(); - if (synopsis is null) + if (synopsis == null) { return string.Empty; } @@ -219,7 +219,7 @@ internal Uri LookupUriFromCommandInfo() } ExecutionContext context = LocalPipeline.GetExecutionContextFromTLS(); - if (context is null) + if (context == null) { return null; } @@ -237,7 +237,7 @@ internal Uri LookupUriFromCommandInfo() cmdInfo = context.SessionState.InvokeCommand.GetCommands(commandToSearch, cmdTypesToLookFor, false).FirstOrDefault(); } - if ((cmdInfo is null) || (cmdInfo.CommandMetadata is null)) + if ((cmdInfo == null) || (cmdInfo.CommandMetadata == null)) { return null; } @@ -279,16 +279,16 @@ internal static Uri GetUriFromCommandPSObject(PSObject commandFullHelp) { // this object knows Maml format... // So retrieve Uri information as per the format.. - if ((commandFullHelp is null) || - (commandFullHelp.Properties["relatedLinks"] is null) || - (commandFullHelp.Properties["relatedLinks"].Value is null)) + if ((commandFullHelp == null) || + (commandFullHelp.Properties["relatedLinks"] == null) || + (commandFullHelp.Properties["relatedLinks"].Value == null)) { // return the default.. return null; } PSObject relatedLinks = PSObject.AsPSObject(commandFullHelp.Properties["relatedLinks"].Value); - if (relatedLinks.Properties["navigationLink"] is null) + if (relatedLinks.Properties["navigationLink"] == null) { return null; } @@ -299,7 +299,7 @@ internal static Uri GetUriFromCommandPSObject(PSObject commandFullHelp) CultureInfo.InvariantCulture); foreach (object navigationLinkAsObject in navigationLinks) { - if (navigationLinkAsObject is null) + if (navigationLinkAsObject == null) { continue; } @@ -356,12 +356,12 @@ internal override bool MatchPatternInContent(WildcardPattern pattern) string synopsis = Synopsis; string detailedDescription = DetailedDescription; - if (synopsis is null) + if (synopsis == null) { synopsis = string.Empty; } - if (detailedDescription is null) + if (detailedDescription == null) { detailedDescription = string.Empty; } @@ -378,9 +378,9 @@ internal override PSObject[] GetParameter(string pattern) { // this object knows Maml format... // So retrieve parameter information as per the format.. - if ((this.FullHelp is null) || - (this.FullHelp.Properties["parameters"] is null) || - (this.FullHelp.Properties["parameters"].Value is null)) + if ((this.FullHelp == null) || + (this.FullHelp.Properties["parameters"] == null) || + (this.FullHelp.Properties["parameters"].Value == null)) { // return the default.. return base.GetParameter(pattern); @@ -388,7 +388,7 @@ internal override PSObject[] GetParameter(string pattern) PSObject prmts = PSObject.AsPSObject(this.FullHelp.Properties["parameters"].Value); - if (prmts.Properties["parameter"] is null) + if (prmts.Properties["parameter"] == null) { return base.GetParameter(pattern); } @@ -418,7 +418,7 @@ internal override PSObject[] GetParameter(string pattern) WildcardPattern matcher = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase); foreach (PSObject prmtr in prmtArray) { - if ((prmtr.Properties["name"] is null) || (prmtr.Properties["name"].Value is null)) + if ((prmtr.Properties["name"] == null) || (prmtr.Properties["name"].Value == null)) { continue; } @@ -444,11 +444,11 @@ internal string DetailedDescription { get { - if (this.FullHelp is null) + if (this.FullHelp == null) return string.Empty; - if (this.FullHelp.Properties["Description"] is null || - this.FullHelp.Properties["Description"].Value is null) + if (this.FullHelp.Properties["Description"] == null || + this.FullHelp.Properties["Description"].Value == null) { return string.Empty; } @@ -457,7 +457,7 @@ internal string DetailedDescription this.FullHelp.Properties["Description"].Value, typeof(object[]), CultureInfo.InvariantCulture); - if (descriptionItems is null || descriptionItems.Length == 0) + if (descriptionItems == null || descriptionItems.Length == 0) { return string.Empty; } @@ -469,15 +469,15 @@ internal string DetailedDescription StringBuilder result = new StringBuilder(400); foreach (object descriptionItem in descriptionItems) { - if (descriptionItem is null) + if (descriptionItem == null) { continue; } PSObject descriptionObject = PSObject.AsPSObject(descriptionItem); - if ((descriptionObject is null) || - (descriptionObject.Properties["Text"] is null) || - (descriptionObject.Properties["Text"].Value is null)) + if ((descriptionObject == null) || + (descriptionObject.Properties["Text"] == null) || + (descriptionObject.Properties["Text"].Value == null)) { continue; } diff --git a/src/System.Management.Automation/help/CabinetNativeApi.cs b/src/System.Management.Automation/help/CabinetNativeApi.cs index 7c2333fc380..4b19861e473 100644 --- a/src/System.Management.Automation/help/CabinetNativeApi.cs +++ b/src/System.Management.Automation/help/CabinetNativeApi.cs @@ -243,7 +243,7 @@ internal static IntPtr FdiOpen(string filename, int oflag, int pmode) { FileStream stream = new FileStream(filename, mode, access, share); - if (stream is null) + if (stream == null) { return new IntPtr(-1); } @@ -321,7 +321,7 @@ internal static int FdiClose(IntPtr fp) GCHandle handle = GCHandle.FromIntPtr(fp); FileStream stream = (FileStream)handle.Target; - if (stream is null) + if (stream == null) { return -1; } diff --git a/src/System.Management.Automation/help/CommandHelpProvider.cs b/src/System.Management.Automation/help/CommandHelpProvider.cs index b97d36ac793..8771c4eced7 100644 --- a/src/System.Management.Automation/help/CommandHelpProvider.cs +++ b/src/System.Management.Automation/help/CommandHelpProvider.cs @@ -221,7 +221,7 @@ private HelpInfo GetHelpInfo(CommandInfo commandInfo, bool reportErrors, bool se { result = GetFromCommandCache(cmdletInfo.ModuleName, cmdletInfo.Name, cmdletInfo.HelpCategory); - if (result is null) + if (result == null) { // Try load the help file specified by CmdletInfo.HelpFile property helpFile = FindHelpFile(cmdletInfo); @@ -249,7 +249,7 @@ private HelpInfo GetHelpInfo(CommandInfo commandInfo, bool reportErrors, bool se } // For scripts, try to retrieve the help from the file specified by .ExternalHelp directive - if (result is null && isScriptCommand) + if (result == null && isScriptCommand) { ScriptBlock sb = null; try @@ -311,7 +311,7 @@ private HelpInfo GetHelpInfo(CommandInfo commandInfo, bool reportErrors, bool se // in the appropriate UI culture subfolder of ModuleBase, and retrieve help // If still not able to get help, try search for a file called -Help.xml // under the ModuleBase and the NestedModule's directory, and retrieve help - if (result is null && !InternalTestHooks.BypassOnlineHelpRetrieval) + if (result == null && !InternalTestHooks.BypassOnlineHelpRetrieval) { // Get the name and ModuleBase directory of the command's module // and the nested module that implements the command @@ -338,7 +338,7 @@ private HelpInfo GetHelpInfo(CommandInfo commandInfo, bool reportErrors, bool se result = GetHelpInfoFromHelpFile(commandInfo, helpFileToFind, searchPaths, reportErrors, out helpFile); } - if (result is null && !string.IsNullOrEmpty(nestedModulePath)) + if (result == null && !string.IsNullOrEmpty(nestedModulePath)) { // Search for -Help.xml under both ModuleBase and NestedModule's directory searchPaths.Add(Path.GetDirectoryName(nestedModulePath)); @@ -361,7 +361,7 @@ private HelpInfo GetHelpInfo(CommandInfo commandInfo, bool reportErrors, bool se } // If the above fails to get help, construct an HelpInfo object using the syntax and definition of the command - if (result is null) + if (result == null) { if (commandInfo.CommandType == CommandTypes.ExternalScript || commandInfo.CommandType == CommandTypes.Script) @@ -383,7 +383,7 @@ private HelpInfo GetHelpInfo(CommandInfo commandInfo, bool reportErrors, bool se if (result != null) { - if (isScriptCommand && result.GetUriForOnlineHelp() is null) + if (isScriptCommand && result.GetUriForOnlineHelp() == null) { if (!string.IsNullOrEmpty(commandInfo.CommandMetadata.HelpUri)) { @@ -395,12 +395,12 @@ private HelpInfo GetHelpInfo(CommandInfo commandInfo, bool reportErrors, bool se } } - if (isCmdlet && result.FullHelp.Properties["PSSnapIn"] is null) + if (isCmdlet && result.FullHelp.Properties["PSSnapIn"] == null) { result.FullHelp.Properties.Add(new PSNoteProperty("PSSnapIn", cmdletInfo.PSSnapIn)); } - if (result.FullHelp.Properties["ModuleName"] is null) + if (result.FullHelp.Properties["ModuleName"] == null) { result.FullHelp.Properties.Add(new PSNoteProperty("ModuleName", commandInfo.ModuleName)); } @@ -473,10 +473,10 @@ internal override IEnumerable ExactMatchHelp(HelpRequest helpRequest) private static string GetCmdletAssemblyPath(CmdletInfo cmdletInfo) { - if (cmdletInfo is null) + if (cmdletInfo == null) return null; - if (cmdletInfo.ImplementingType is null) + if (cmdletInfo.ImplementingType == null) return null; return Path.GetDirectoryName(cmdletInfo.ImplementingType.Assembly.Location); @@ -564,7 +564,7 @@ private string FindHelpFile(CmdletInfo cmdletInfo) return null; } - if (cmdletInfo is null) + if (cmdletInfo == null) { throw PSTraceSource.NewArgumentNullException(nameof(cmdletInfo)); } @@ -704,7 +704,7 @@ private void LoadHelpFile(string helpFile, string helpFileIdentifier) } } - if (helpItemsNode is null) + if (helpItemsNode == null) { s_tracer.WriteLine("Unable to find 'helpItems' element in file {0}", helpFile); return; @@ -754,7 +754,7 @@ private void LoadHelpFile(string helpFile, string helpFileIdentifier) /// private void ProcessUserDefinedHelpData(string mshSnapInId, UserDefinedHelpData userDefinedHelpData) { - if (userDefinedHelpData is null) + if (userDefinedHelpData == null) return; if (string.IsNullOrEmpty(userDefinedHelpData.Name)) @@ -762,12 +762,12 @@ private void ProcessUserDefinedHelpData(string mshSnapInId, UserDefinedHelpData HelpInfo helpInfo = GetFromCommandCache(mshSnapInId, userDefinedHelpData.Name, HelpCategory.Cmdlet); - if (helpInfo is null) + if (helpInfo == null) return; MamlCommandHelpInfo commandHelpInfo = helpInfo as MamlCommandHelpInfo; - if (commandHelpInfo is null) + if (commandHelpInfo == null) return; commandHelpInfo.AddUserDefinedData(userDefinedHelpData); @@ -814,7 +814,7 @@ private HelpInfo GetFromCommandCache(string helpFileIdentifier, CommandInfo comm { Debug.Assert(commandInfo != null, "commandInfo cannot be null"); HelpInfo result = GetFromCommandCache(helpFileIdentifier, commandInfo.Name, commandInfo.HelpCategory); - if (result is null) + if (result == null) { // check if the command is prefixed and try retrieving help by removing the prefix if ((commandInfo.Module != null) && (!string.IsNullOrEmpty(commandInfo.Prefix))) @@ -844,7 +844,7 @@ private HelpInfo GetFromCommandCacheOrCmdletInfo(CmdletInfo cmdletInfo) { Debug.Assert(cmdletInfo != null, "cmdletInfo cannot be null"); HelpInfo result = GetFromCommandCache(cmdletInfo.ModuleName, cmdletInfo.Name, cmdletInfo.HelpCategory); - if (result is null) + if (result == null) { // check if the command is prefixed and try retrieving help by removing the prefix if ((cmdletInfo.Module != null) && (!string.IsNullOrEmpty(cmdletInfo.Prefix))) @@ -984,7 +984,7 @@ internal static bool IsMamlHelp(string helpFile, XmlNode helpItemsNode) if (helpFile.EndsWith(".maml", StringComparison.OrdinalIgnoreCase)) return true; - if (helpItemsNode.Attributes is null) + if (helpItemsNode.Attributes == null) return false; foreach (XmlNode attribute in helpItemsNode.Attributes) @@ -1170,7 +1170,7 @@ internal override IEnumerable SearchHelp(HelpRequest helpRequest, bool /// private static bool Match(HelpInfo helpInfo, HelpRequest helpRequest, CommandInfo commandInfo) { - if (helpRequest is null) + if (helpRequest == null) return true; if (0 == (helpRequest.HelpCategory & commandInfo.HelpCategory)) @@ -1227,7 +1227,7 @@ private static bool Match(string target, ICollection patterns) { // patterns should never be null as shell never accepts // empty inputs. Keeping this check as a safe measure. - if (patterns is null || patterns.Count == 0) + if (patterns == null || patterns.Count == 0) return true; foreach (string pattern in patterns) @@ -1381,7 +1381,7 @@ internal string Name internal static UserDefinedHelpData Load(XmlNode dataNode) { - if (dataNode is null) + if (dataNode == null) return null; UserDefinedHelpData userDefinedHelpData = new UserDefinedHelpData(); diff --git a/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs b/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs index cde4b093d1c..b8be27e99a0 100644 --- a/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs +++ b/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs @@ -902,7 +902,7 @@ private static bool HasHelpInfoUri(PSModuleInfo module, string moduleName) return true; } - if (module is null) + if (module == null) { return false; } diff --git a/src/System.Management.Automation/help/DscResourceHelpProvider.cs b/src/System.Management.Automation/help/DscResourceHelpProvider.cs index c2fd800b1e7..c29ed02b456 100644 --- a/src/System.Management.Automation/help/DscResourceHelpProvider.cs +++ b/src/System.Management.Automation/help/DscResourceHelpProvider.cs @@ -184,7 +184,7 @@ internal static bool IsMamlHelp(string helpFile, XmlNode helpItemsNode) if (helpFile.EndsWith(".maml", StringComparison.OrdinalIgnoreCase)) return true; - if (helpItemsNode.Attributes is null) + if (helpItemsNode.Attributes == null) return false; foreach (XmlNode attribute in helpItemsNode.Attributes) @@ -325,7 +325,7 @@ private void LoadHelpFile(string helpFile, string helpFileIdentifier) } } - if (helpItemsNode is null) + if (helpItemsNode == null) { s_tracer.WriteLine("Unable to find 'helpItems' element in file {0}", helpFile); return; diff --git a/src/System.Management.Automation/help/HelpCategoryInvalidException.cs b/src/System.Management.Automation/help/HelpCategoryInvalidException.cs index 51df200583d..4d2a8100d0c 100644 --- a/src/System.Management.Automation/help/HelpCategoryInvalidException.cs +++ b/src/System.Management.Automation/help/HelpCategoryInvalidException.cs @@ -126,7 +126,7 @@ protected HelpCategoryInvalidException(SerializationInfo info, [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) { throw PSTraceSource.NewArgumentNullException(nameof(info)); } diff --git a/src/System.Management.Automation/help/HelpCommands.cs b/src/System.Management.Automation/help/HelpCommands.cs index 746f2afc163..852db86c267 100644 --- a/src/System.Management.Automation/help/HelpCommands.cs +++ b/src/System.Management.Automation/help/HelpCommands.cs @@ -364,7 +364,7 @@ protected override void ProcessRecord() private HelpCategory ToHelpCategory(string[] category, ref bool failed) { - if (category is null || category.Length == 0) + if (category == null || category.Length == 0) return HelpCategory.None; HelpCategory helpCategory = HelpCategory.None; @@ -486,7 +486,7 @@ private void GetAndWriteParameterInfo(HelpInfo helpInfo) PSObject[] pInfos = GetParameterInfo(helpInfo); - if ((pInfos is null) || (pInfos.Length == 0)) + if ((pInfos == null) || (pInfos.Length == 0)) { Exception innerException = PSTraceSource.NewArgumentException("Parameter", HelpErrors.NoParmsFound, Parameter); @@ -606,7 +606,7 @@ private void WriteObjectsOrShowOnlineHelp(HelpInfo helpInfo, bool showFullHelp) { PSObject[] pInfos = GetParameterInfo(helpInfo); - if ((pInfos is null) || (pInfos.Length == 0)) + if ((pInfos == null) || (pInfos.Length == 0)) { return; } @@ -778,7 +778,7 @@ private static bool DoesCurrentRunspaceIncludeCoreHelpCmdlet() [SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings")] public static string GetHelpUri(PSObject commandInfoPSObject) { - if (commandInfoPSObject is null) + if (commandInfoPSObject == null) { return string.Empty; } @@ -786,7 +786,7 @@ public static string GetHelpUri(PSObject commandInfoPSObject) CommandInfo cmdInfo = PSObject.Base(commandInfoPSObject) as CommandInfo; // GetHelpUri helper method is expected to be used only by System.Management.Automation.CommandInfo // objects from types.ps1xml - if ((cmdInfo is null) || (string.IsNullOrEmpty(cmdInfo.Name))) + if ((cmdInfo == null) || (string.IsNullOrEmpty(cmdInfo.Name))) { return string.Empty; } diff --git a/src/System.Management.Automation/help/HelpCommentsParser.cs b/src/System.Management.Automation/help/HelpCommentsParser.cs index 0f43aedc44b..77347527ab4 100644 --- a/src/System.Management.Automation/help/HelpCommentsParser.cs +++ b/src/System.Management.Automation/help/HelpCommentsParser.cs @@ -154,7 +154,7 @@ private XmlElement BuildXmlForParameter( command_parameter.AppendChild(maml_description).AppendChild(maml_para).AppendChild(maml_para_text); } - if (type is null) + if (type == null) type = typeof(object); var elementType = type.IsArray ? type.GetElementType() : type; @@ -274,7 +274,7 @@ internal XmlDocument BuildXmlFromComments() CompiledCommandParameter parameter = mergedParameter.Parameter; parameter.ParameterSetData.TryGetValue(ParameterAttribute.AllParameterSets, out parameterSetData); - while (parameterSetData is null && i < 32) + while (parameterSetData == null && i < 32) { parameterSetData = parameter.GetParameterSetData(1u << i++); } @@ -304,7 +304,7 @@ internal XmlDocument BuildXmlFromComments() if (string.IsNullOrEmpty(defaultValueStr)) { - if (defaultValue is null) + if (defaultValue == null) { RuntimeDefinedParameter rdp; if (_scriptBlock.RuntimeDefinedParameters.TryGetValue(parameterName, out rdp)) @@ -637,7 +637,7 @@ private static string GetSection(List commentLines, ref int i) internal string GetHelpFile(CommandInfo commandInfo) { - if (_sections.MamlHelpFile is null) + if (_sections.MamlHelpFile == null) { return null; } @@ -671,7 +671,7 @@ internal RemoteHelpInfo GetRemoteHelpInfo(ExecutionContext context, CommandInfo SessionState sessionState = scriptCommandInfo.ScriptBlock.SessionState; object runspaceInfoAsObject = sessionState.PSVariable.GetValue(_sections.RemoteHelpRunspace); PSSession runspaceInfo; - if (runspaceInfoAsObject is null || + if (runspaceInfoAsObject == null || !LanguagePrimitives.TryConvertTo(runspaceInfoAsObject, out runspaceInfo)) { string errorMessage = HelpErrors.RemoteRunspaceNotAvailable; @@ -695,7 +695,7 @@ internal RemoteHelpInfo GetRemoteHelpInfo(ExecutionContext context, CommandInfo /// True if any special comments are found, false otherwise. internal bool AnalyzeCommentBlock(List comments) { - if (comments is null || comments.Count == 0) + if (comments == null || comments.Count == 0) { return false; } @@ -852,7 +852,7 @@ internal static HelpInfo CreateFromComments(ExecutionContext context, // If only .ExternalHelp is defined and the help file is not found, then we // use the metadata driven help - if (comments.Count == 1 && helpCommentsParser.isExternalHelpSet && helpFile is null) + if (comments.Count == 1 && helpCommentsParser.isExternalHelpSet && helpFile == null) { return null; } @@ -869,7 +869,7 @@ internal static HelpInfo CreateFromComments(ExecutionContext context, CommandInf if (remoteHelpInfo != null) { // Add HelpUri if necessary - if (remoteHelpInfo.GetUriForOnlineHelp() is null) + if (remoteHelpInfo.GetUriForOnlineHelp() == null) { DefaultCommandHelpObjectBuilder.AddRelatedLinksProperties(remoteHelpInfo.FullHelp, commandInfo.CommandMetadata.HelpUri); @@ -921,7 +921,7 @@ internal static HelpInfo CreateFromComments(ExecutionContext context, CommandInf } // Add HelpUri if necessary - if (localHelpInfo.GetUriForOnlineHelp() is null) + if (localHelpInfo.GetUriForOnlineHelp() == null) { DefaultCommandHelpObjectBuilder.AddRelatedLinksProperties(localHelpInfo.FullHelp, commandInfo.CommandMetadata.HelpUri); } @@ -937,7 +937,7 @@ internal static HelpInfo CreateFromComments(ExecutionContext context, CommandInf /// True if the block is our special comment block for help, false otherwise. internal static bool IsCommentHelpText(List commentBlock) { - if ((commentBlock is null) || (commentBlock.Count == 0)) + if ((commentBlock == null) || (commentBlock.Count == 0)) return false; HelpCommentsParser generator = new HelpCommentsParser(); @@ -1045,7 +1045,7 @@ private static List GetParameterComments(Language.Token[] tokens, IParam { var result = new List(); var parameters = ipmp.Parameters; - if (parameters is null || parameters.Count == 0) + if (parameters == null || parameters.Count == 0) { return result; } @@ -1111,7 +1111,7 @@ private static List GetParameterComments(Language.Token[] tokens, IParam Language.Token[] tokens = null; scriptBlockTokenCache.TryGetValue(rootAst, out tokens); - if (tokens is null) + if (tokens == null) { ParseError[] errors; // storing all comment tokens @@ -1129,7 +1129,7 @@ private static List GetParameterComments(Language.Token[] tokens, IParam { // The first comment block preceding the function or configuration keyword is a candidate help comment block. var funcOrConfigTokenIndex = - savedStartIndex = FirstTokenInExtent(tokens, configAst is null ? ast.Extent : configAst.Extent); + savedStartIndex = FirstTokenInExtent(tokens, configAst == null ? ast.Extent : configAst.Extent); commentBlock = GetPrecedingCommentBlock(tokens, funcOrConfigTokenIndex, CommentBlockProximity); @@ -1190,7 +1190,7 @@ private static List GetParameterComments(Language.Token[] tokens, IParam { // One more check - make sure the comment doesn't belong to the first function in the script. var endBlock = ((ScriptBlockAst)ast).EndBlock; - if (endBlock is null || !endBlock.Unnamed) + if (endBlock == null || !endBlock.Unnamed) { return Tuple.Create(commentBlock, GetParameterComments(tokens, ipmp, savedStartIndex)); } diff --git a/src/System.Management.Automation/help/HelpErrorTracer.cs b/src/System.Management.Automation/help/HelpErrorTracer.cs index bd360dca38e..9c9fd0165b5 100644 --- a/src/System.Management.Automation/help/HelpErrorTracer.cs +++ b/src/System.Management.Automation/help/HelpErrorTracer.cs @@ -122,7 +122,7 @@ public void Dispose() internal HelpErrorTracer(HelpSystem helpSystem) { - if (helpSystem is null) + if (helpSystem == null) { throw PSTraceSource.NewArgumentNullException("HelpSystem"); } diff --git a/src/System.Management.Automation/help/HelpFileHelpInfo.cs b/src/System.Management.Automation/help/HelpFileHelpInfo.cs index 09a65b0890a..1df1b70411b 100644 --- a/src/System.Management.Automation/help/HelpFileHelpInfo.cs +++ b/src/System.Management.Automation/help/HelpFileHelpInfo.cs @@ -120,7 +120,7 @@ private static string GetLine(string text, int line) { result = reader.ReadLine(); - if (result is null) + if (result == null) return null; } diff --git a/src/System.Management.Automation/help/HelpFileHelpProvider.cs b/src/System.Management.Automation/help/HelpFileHelpProvider.cs index 142664e002c..2c527d2f95a 100644 --- a/src/System.Management.Automation/help/HelpFileHelpProvider.cs +++ b/src/System.Management.Automation/help/HelpFileHelpProvider.cs @@ -222,7 +222,7 @@ internal override IEnumerable SearchHelp(HelpRequest helpRequest, bool var matchedFilesToRemove = FilterToLatestModuleVersion(files); - if (files is null) + if (files == null) yield break; foreach (string file in files) diff --git a/src/System.Management.Automation/help/HelpInfo.cs b/src/System.Management.Automation/help/HelpInfo.cs index d11de9e37b7..207d8b54d51 100644 --- a/src/System.Management.Automation/help/HelpInfo.cs +++ b/src/System.Management.Automation/help/HelpInfo.cs @@ -124,7 +124,7 @@ internal PSObject ShortHelp { get { - if (this.FullHelp is null) + if (this.FullHelp == null) return null; PSObject shortHelpObject = new PSObject(this.FullHelp); @@ -198,35 +198,35 @@ internal virtual bool MatchPatternInContent(WildcardPattern pattern) /// protected void AddCommonHelpProperties() { - if (this.FullHelp is null) + if (this.FullHelp == null) return; - if (this.FullHelp.Properties["Name"] is null) + if (this.FullHelp.Properties["Name"] == null) { this.FullHelp.Properties.Add(new PSNoteProperty("Name", this.Name)); } - if (this.FullHelp.Properties["Category"] is null) + if (this.FullHelp.Properties["Category"] == null) { this.FullHelp.Properties.Add(new PSNoteProperty("Category", this.HelpCategory.ToString())); } - if (this.FullHelp.Properties["Synopsis"] is null) + if (this.FullHelp.Properties["Synopsis"] == null) { this.FullHelp.Properties.Add(new PSNoteProperty("Synopsis", this.Synopsis)); } - if (this.FullHelp.Properties["Component"] is null) + if (this.FullHelp.Properties["Component"] == null) { this.FullHelp.Properties.Add(new PSNoteProperty("Component", this.Component)); } - if (this.FullHelp.Properties["Role"] is null) + if (this.FullHelp.Properties["Role"] == null) { this.FullHelp.Properties.Add(new PSNoteProperty("Role", this.Role)); } - if (this.FullHelp.Properties["Functionality"] is null) + if (this.FullHelp.Properties["Functionality"] == null) { this.FullHelp.Properties.Add(new PSNoteProperty("Functionality", this.Functionality)); } @@ -242,7 +242,7 @@ protected void AddCommonHelpProperties() /// protected void UpdateUserDefinedDataProperties() { - if (this.FullHelp is null) + if (this.FullHelp == null) return; this.FullHelp.Properties.Remove("Component"); diff --git a/src/System.Management.Automation/help/HelpNotFoundException.cs b/src/System.Management.Automation/help/HelpNotFoundException.cs index f9ba44c386d..355be44fd7c 100644 --- a/src/System.Management.Automation/help/HelpNotFoundException.cs +++ b/src/System.Management.Automation/help/HelpNotFoundException.cs @@ -132,7 +132,7 @@ protected HelpNotFoundException(SerializationInfo info, [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) { throw PSTraceSource.NewArgumentNullException(nameof(info)); } diff --git a/src/System.Management.Automation/help/HelpRequest.cs b/src/System.Management.Automation/help/HelpRequest.cs index 4102197e87a..7e4de9f1569 100644 --- a/src/System.Management.Automation/help/HelpRequest.cs +++ b/src/System.Management.Automation/help/HelpRequest.cs @@ -126,9 +126,9 @@ internal void Validate() if (string.IsNullOrEmpty(Target) && HelpCategory == HelpCategory.None && string.IsNullOrEmpty(Provider) - && Component is null - && Role is null - && Functionality is null + && Component == null + && Role == null + && Functionality == null ) { Target = "default"; @@ -152,7 +152,7 @@ internal void Validate() // if either of component/role/functionality is specified then look in the // following help categories - if ((!(Component is null && Role is null && Functionality is null)) && + if ((!(Component == null && Role == null && Functionality == null)) && (HelpCategory == HelpCategory.None)) { HelpCategory = HelpCategory.Alias | HelpCategory.Cmdlet | HelpCategory.Function | HelpCategory.Filter | HelpCategory.ExternalScript | HelpCategory.ScriptCommand; diff --git a/src/System.Management.Automation/help/HelpSystem.cs b/src/System.Management.Automation/help/HelpSystem.cs index c7dc9eb68f4..fb92ed1c19c 100644 --- a/src/System.Management.Automation/help/HelpSystem.cs +++ b/src/System.Management.Automation/help/HelpSystem.cs @@ -93,7 +93,7 @@ internal class HelpSystem /// Execution context for this help system. internal HelpSystem(ExecutionContext context) { - if (context is null) + if (context == null) { throw PSTraceSource.NewArgumentNullException("ExecutionContext"); } @@ -159,7 +159,7 @@ internal void Initialize() /// An array of HelpInfo object. internal IEnumerable GetHelp(HelpRequest helpRequest) { - if (helpRequest is null) + if (helpRequest == null) return null; helpRequest.Validate(); @@ -695,7 +695,7 @@ internal HelpErrorTracer HelpErrorTracer /// internal IDisposable Trace(string helpFile) { - if (_helpErrorTracer is null) + if (_helpErrorTracer == null) return null; return _helpErrorTracer.Trace(helpFile); @@ -707,7 +707,7 @@ internal IDisposable Trace(string helpFile) /// internal void TraceError(ErrorRecord errorRecord) { - if (_helpErrorTracer is null) + if (_helpErrorTracer == null) return; _helpErrorTracer.TraceError(errorRecord); @@ -720,7 +720,7 @@ internal void TraceError(ErrorRecord errorRecord) /// internal void TraceErrors(Collection errorRecords) { - if (_helpErrorTracer is null || errorRecords is null) + if (_helpErrorTracer == null || errorRecords == null) return; _helpErrorTracer.TraceErrors(errorRecords); @@ -741,7 +741,7 @@ private void ValidateHelpCulture() { CultureInfo culture = CultureInfo.CurrentUICulture; - if (_culture is null) + if (_culture == null) { _culture = culture; return; @@ -764,7 +764,7 @@ private void ValidateHelpCulture() /// internal void ResetHelpProviders() { - if (_helpProviders is null) + if (_helpProviders == null) return; for (int i = 0; i < _helpProviders.Count; i++) diff --git a/src/System.Management.Automation/help/HelpUtils.cs b/src/System.Management.Automation/help/HelpUtils.cs index 08507186939..0c0770173be 100644 --- a/src/System.Management.Automation/help/HelpUtils.cs +++ b/src/System.Management.Automation/help/HelpUtils.cs @@ -18,7 +18,7 @@ internal class HelpUtils /// internal static string GetUserHomeHelpSearchPath() { - if (userHomeHelpPath is null) + if (userHomeHelpPath == null) { #if UNIX var userModuleFolder = Platform.SelectProductNameForDirectory(Platform.XDG_Type.USER_MODULES); diff --git a/src/System.Management.Automation/help/MUIFileSearcher.cs b/src/System.Management.Automation/help/MUIFileSearcher.cs index 3a867e20c5d..2101e268dc1 100644 --- a/src/System.Management.Automation/help/MUIFileSearcher.cs +++ b/src/System.Management.Automation/help/MUIFileSearcher.cs @@ -66,7 +66,7 @@ internal Collection Result { get { - if (_result is null) + if (_result == null) { _result = new Collection(); @@ -155,7 +155,7 @@ private void AddFiles(string muiDirectory, string directory, string pattern) { string[] files = GetFiles(muiDirectory, pattern); - if (files is null) + if (files == null) return; foreach (string file in files) @@ -348,7 +348,7 @@ internal static string LocateFile(string file, Collection searchPaths) { MUIFileSearcher searcher = new MUIFileSearcher(file, searchPaths, SearchMode.First); - if (searcher.Result is null || searcher.Result.Count == 0) + if (searcher.Result == null || searcher.Result.Count == 0) return null; return searcher.Result[0]; diff --git a/src/System.Management.Automation/help/MamlCommandHelpInfo.cs b/src/System.Management.Automation/help/MamlCommandHelpInfo.cs index 12e1469e7c9..998e647cd05 100644 --- a/src/System.Management.Automation/help/MamlCommandHelpInfo.cs +++ b/src/System.Management.Automation/help/MamlCommandHelpInfo.cs @@ -220,7 +220,7 @@ internal void SetAdditionalDataFromHelpComment(string component, string function /// User defined data object. internal void AddUserDefinedData(UserDefinedHelpData userDefinedData) { - if (userDefinedData is null) + if (userDefinedData == null) return; string propertyValue; @@ -284,7 +284,7 @@ internal static MamlCommandHelpInfo Load(XmlNode xmlNode, HelpCategory helpCateg /// Merged command help info object. internal MamlCommandHelpInfo MergeProviderSpecificHelp(PSObject cmdletHelp, PSObject[] dynamicParameterHelp) { - if (this._fullHelpObject is null) + if (this._fullHelpObject == null) return null; MamlCommandHelpInfo result = (MamlCommandHelpInfo)this.MemberwiseClone(); @@ -317,11 +317,11 @@ internal MamlCommandHelpInfo MergeProviderSpecificHelp(PSObject cmdletHelp, PSOb /// private string ExtractTextForHelpProperty(PSObject psObject, string propertyName) { - if (psObject is null) + if (psObject == null) return string.Empty; - if (psObject.Properties[propertyName] is null || - psObject.Properties[propertyName].Value is null) + if (psObject.Properties[propertyName] == null || + psObject.Properties[propertyName].Value == null) { return string.Empty; } @@ -338,7 +338,7 @@ private string ExtractTextForHelpProperty(PSObject psObject, string propertyName /// private string ExtractText(PSObject psObject) { - if (psObject is null) + if (psObject == null) { return string.Empty; } diff --git a/src/System.Management.Automation/help/MamlNode.cs b/src/System.Management.Automation/help/MamlNode.cs index 872543d2e4c..51fda0bc244 100644 --- a/src/System.Management.Automation/help/MamlNode.cs +++ b/src/System.Management.Automation/help/MamlNode.cs @@ -98,7 +98,7 @@ internal PSObject PSObject { get { - if (_mshObject is null) + if (_mshObject == null) { // There is no XSLT to convert docs to supported maml format // We dont want comments etc to spoil our format. @@ -192,7 +192,7 @@ internal PSObject PSObject /// private PSObject GetPSObject(XmlNode xmlNode) { - if (xmlNode is null) + if (xmlNode == null) return new PSObject(); PSObject mshObject = null; @@ -300,7 +300,7 @@ private Hashtable GetInsideProperties(XmlNode xmlNode) { Hashtable properties = new Hashtable(StringComparer.OrdinalIgnoreCase); - if (xmlNode is null) + if (xmlNode == null) return properties; if (xmlNode.ChildNodes != null) @@ -378,14 +378,14 @@ private static void AddProperty(Hashtable properties, string name, PSObject mshO { ArrayList propertyValues = (ArrayList)properties[name]; - if (propertyValues is null) + if (propertyValues == null) { propertyValues = new ArrayList(); properties[name] = propertyValues; } - if (mshObject is null) + if (mshObject == null) return; if (mshObject.BaseObject is PSCustomObject || !mshObject.BaseObject.GetType().Equals(typeof(PSObject[]))) @@ -417,7 +417,7 @@ private static void AddProperty(Hashtable properties, string name, PSObject mshO /// private static Hashtable SimplifyProperties(Hashtable properties) { - if (properties is null) + if (properties == null) return null; Hashtable result = new Hashtable(StringComparer.OrdinalIgnoreCase); @@ -427,7 +427,7 @@ private static Hashtable SimplifyProperties(Hashtable properties) { ArrayList propertyValues = (ArrayList)enumerator.Value; - if (propertyValues is null || propertyValues.Count == 0) + if (propertyValues == null || propertyValues.Count == 0) continue; if (propertyValues.Count == 1) @@ -458,10 +458,10 @@ private static Hashtable SimplifyProperties(Hashtable properties) /// private static bool IsAtomic(XmlNode xmlNode) { - if (xmlNode is null) + if (xmlNode == null) return false; - if (xmlNode.ChildNodes is null) + if (xmlNode.ChildNodes == null) return true; if (xmlNode.ChildNodes.Count > 1) @@ -488,10 +488,10 @@ private static bool IsAtomic(XmlNode xmlNode) /// private static bool IncludeMamlFormatting(XmlNode xmlNode) { - if (xmlNode is null) + if (xmlNode == null) return false; - if (xmlNode.ChildNodes is null || xmlNode.ChildNodes.Count == 0) + if (xmlNode.ChildNodes == null || xmlNode.ChildNodes.Count == 0) return false; foreach (XmlNode childNode in xmlNode.ChildNodes) @@ -536,7 +536,7 @@ private static bool IsMamlFormattingPSObject(PSObject mshObject) { Collection typeNames = mshObject.TypeNames; - if (typeNames is null || typeNames.Count == 0) + if (typeNames == null || typeNames.Count == 0) return false; return typeNames[typeNames.Count - 1].Equals("MamlTextItem", StringComparison.OrdinalIgnoreCase); @@ -693,10 +693,10 @@ private void WriteMamlInvalidChildNodeCountError(XmlNode node, string childNodeN private static string GetNodePath(XmlNode xmlNode) { - if (xmlNode is null) + if (xmlNode == null) return string.Empty; - if (xmlNode.ParentNode is null) + if (xmlNode.ParentNode == null) return "\\" + xmlNode.LocalName; return GetNodePath(xmlNode.ParentNode) + "\\" + xmlNode.LocalName + GetNodeIndex(xmlNode); @@ -704,7 +704,7 @@ private static string GetNodePath(XmlNode xmlNode) private static string GetNodeIndex(XmlNode xmlNode) { - if (xmlNode is null || xmlNode.ParentNode is null) + if (xmlNode == null || xmlNode.ParentNode == null) return string.Empty; int index = 0; @@ -748,7 +748,7 @@ private static string GetNodeIndex(XmlNode xmlNode) /// private static PSObject GetParaPSObject(XmlNode xmlNode, bool newLine, bool trim = true) { - if (xmlNode is null) + if (xmlNode == null) return null; if (!xmlNode.LocalName.Equals("para", StringComparison.OrdinalIgnoreCase)) @@ -810,13 +810,13 @@ private ArrayList GetListPSObjects(XmlNode xmlNode) { ArrayList mshObjects = new ArrayList(); - if (xmlNode is null) + if (xmlNode == null) return mshObjects; if (!xmlNode.LocalName.Equals("list", StringComparison.OrdinalIgnoreCase)) return mshObjects; - if (xmlNode.ChildNodes is null || xmlNode.ChildNodes.Count == 0) + if (xmlNode.ChildNodes == null || xmlNode.ChildNodes.Count == 0) return mshObjects; bool ordered = IsOrderedList(xmlNode); @@ -848,10 +848,10 @@ private ArrayList GetListPSObjects(XmlNode xmlNode) /// private static bool IsOrderedList(XmlNode xmlNode) { - if (xmlNode is null) + if (xmlNode == null) return false; - if (xmlNode.Attributes is null || xmlNode.Attributes.Count == 0) + if (xmlNode.Attributes == null || xmlNode.Attributes.Count == 0) return false; foreach (XmlNode attribute in xmlNode.Attributes) @@ -875,7 +875,7 @@ private static bool IsOrderedList(XmlNode xmlNode) /// private PSObject GetListItemPSObject(XmlNode xmlNode, bool ordered, ref int index) { - if (xmlNode is null) + if (xmlNode == null) return null; if (!xmlNode.LocalName.Equals("listItem", StringComparison.OrdinalIgnoreCase)) @@ -941,13 +941,13 @@ private ArrayList GetDefinitionListPSObjects(XmlNode xmlNode) { ArrayList mshObjects = new ArrayList(); - if (xmlNode is null) + if (xmlNode == null) return mshObjects; if (!xmlNode.LocalName.Equals("definitionList", StringComparison.OrdinalIgnoreCase)) return mshObjects; - if (xmlNode.ChildNodes is null || xmlNode.ChildNodes.Count == 0) + if (xmlNode.ChildNodes == null || xmlNode.ChildNodes.Count == 0) return mshObjects; foreach (XmlNode childNode in xmlNode.ChildNodes) @@ -992,7 +992,7 @@ private ArrayList GetDefinitionListPSObjects(XmlNode xmlNode) /// private PSObject GetDefinitionListItemPSObject(XmlNode xmlNode) { - if (xmlNode is null) + if (xmlNode == null) return null; if (!xmlNode.LocalName.Equals("definitionListItem", StringComparison.OrdinalIgnoreCase)) @@ -1041,13 +1041,13 @@ private PSObject GetDefinitionListItemPSObject(XmlNode xmlNode) /// private string GetDefinitionText(XmlNode xmlNode) { - if (xmlNode is null) + if (xmlNode == null) return null; if (!xmlNode.LocalName.Equals("definition", StringComparison.OrdinalIgnoreCase)) return null; - if (xmlNode.ChildNodes is null || xmlNode.ChildNodes.Count == 0) + if (xmlNode.ChildNodes == null || xmlNode.ChildNodes.Count == 0) return string.Empty; if (xmlNode.ChildNodes.Count > 1) @@ -1112,7 +1112,7 @@ private static string GetPreformattedText(string text) string[] lines = noTabText.Split(Utils.Separators.Newline); string[] trimedLines = TrimLines(lines); - if (trimedLines is null || trimedLines.Length == 0) + if (trimedLines == null || trimedLines.Length == 0) return string.Empty; int minIndentation = GetMinIndentation(trimedLines); @@ -1146,7 +1146,7 @@ private static string GetPreformattedText(string text) /// An string array with empty lines trimed on either end. private static string[] TrimLines(string[] lines) { - if (lines is null || lines.Length == 0) + if (lines == null || lines.Length == 0) return null; int i = 0; diff --git a/src/System.Management.Automation/help/MamlUtil.cs b/src/System.Management.Automation/help/MamlUtil.cs index 36c8199bcab..7ace664b728 100644 --- a/src/System.Management.Automation/help/MamlUtil.cs +++ b/src/System.Management.Automation/help/MamlUtil.cs @@ -53,7 +53,7 @@ internal static void OverridePSTypeNames(PSObject maml1, PSObject maml2) /// internal static void AddCommonProperties(PSObject maml1, PSObject maml2) { - if (maml1.Properties["PSSnapIn"] is null) + if (maml1.Properties["PSSnapIn"] == null) { PSPropertyInfo snapInProperty = maml2.Properties["PSSnapIn"]; if (snapInProperty != null) @@ -62,7 +62,7 @@ internal static void AddCommonProperties(PSObject maml1, PSObject maml2) } } - if (maml1.Properties["ModuleName"] is null) + if (maml1.Properties["ModuleName"] == null) { PSPropertyInfo moduleNameProperty = maml2.Properties["ModuleName"]; if (moduleNameProperty != null) @@ -206,7 +206,7 @@ internal static PSPropertyInfo GetPropertyInfo(PSObject psObject, string[] path) return propertyInfo; } - if (propertyInfo is null || !(propertyInfo.Value is PSObject)) + if (propertyInfo == null || !(propertyInfo.Value is PSObject)) { return null; } @@ -302,7 +302,7 @@ internal static void EnsurePropertyInfoPathExists(PSObject psObject, string[] pa PSPropertyInfo propertyInfo = psObject.Properties[propertyName]; // Add a property info here if none was found. - if (propertyInfo is null) + if (propertyInfo == null) { // Add null on the last one, since we don't need to extend path further. object propertyValue = (i < path.Length - 1) ? new PSObject() : null; @@ -317,7 +317,7 @@ internal static void EnsurePropertyInfoPathExists(PSObject psObject, string[] pa } // If we are not on the last path element, let's make sure we can extend the path. - if (propertyInfo.Value is null || !(propertyInfo.Value is PSObject)) + if (propertyInfo.Value == null || !(propertyInfo.Value is PSObject)) { propertyInfo.Value = new PSObject(); } diff --git a/src/System.Management.Automation/help/PSClassHelpProvider.cs b/src/System.Management.Automation/help/PSClassHelpProvider.cs index 1863644e21e..ee65529a026 100644 --- a/src/System.Management.Automation/help/PSClassHelpProvider.cs +++ b/src/System.Management.Automation/help/PSClassHelpProvider.cs @@ -189,7 +189,7 @@ internal static bool IsMamlHelp(string helpFile, XmlNode helpItemsNode) if (helpFile.EndsWith(".maml", StringComparison.OrdinalIgnoreCase)) return true; - if (helpItemsNode.Attributes is null) + if (helpItemsNode.Attributes == null) return false; foreach (XmlNode attribute in helpItemsNode.Attributes) @@ -330,7 +330,7 @@ private void LoadHelpFile(string helpFile, string helpFileIdentifier) } } - if (helpItemsNode is null) + if (helpItemsNode == null) { s_tracer.WriteLine("Unable to find 'helpItems' element in file {0}", helpFile); return; diff --git a/src/System.Management.Automation/help/ProviderCommandHelpInfo.cs b/src/System.Management.Automation/help/ProviderCommandHelpInfo.cs index b95ade5141c..6d9bedf4fac 100644 --- a/src/System.Management.Automation/help/ProviderCommandHelpInfo.cs +++ b/src/System.Management.Automation/help/ProviderCommandHelpInfo.cs @@ -29,7 +29,7 @@ internal ProviderCommandHelpInfo(HelpInfo genericHelpInfo, ProviderContext provi // Now pick which help we should show. MamlCommandHelpInfo providerSpecificHelpInfo = providerContext.GetProviderSpecificHelpInfo(genericHelpInfo.Name); - if (providerSpecificHelpInfo is null) + if (providerSpecificHelpInfo == null) { _helpInfo = genericHelpInfo; } diff --git a/src/System.Management.Automation/help/ProviderContext.cs b/src/System.Management.Automation/help/ProviderContext.cs index 86fc8a6c895..184ad5526fa 100644 --- a/src/System.Management.Automation/help/ProviderContext.cs +++ b/src/System.Management.Automation/help/ProviderContext.cs @@ -101,7 +101,7 @@ internal MamlCommandHelpInfo GetProviderSpecificHelpInfo(string helpItemName) { } - if (providerInfo is null) + if (providerInfo == null) { return null; } @@ -111,7 +111,7 @@ internal MamlCommandHelpInfo GetProviderSpecificHelpInfo(string helpItemName) ICmdletProviderSupportsHelp provider = cmdletProvider as ICmdletProviderSupportsHelp; // Under JEA sessions the resolvedProviderPath will be null, we should allow get-help to continue. - if (provider is null) + if (provider == null) { return null; } @@ -131,7 +131,7 @@ Runspaces.SessionStateProviderEntry sessionStateProvider in } } - if (resolvedProviderPath is null) + if (resolvedProviderPath == null) { if (isJEASession) { diff --git a/src/System.Management.Automation/help/ProviderHelpInfo.cs b/src/System.Management.Automation/help/ProviderHelpInfo.cs index 48d05a35ea3..39eebe0c23a 100644 --- a/src/System.Management.Automation/help/ProviderHelpInfo.cs +++ b/src/System.Management.Automation/help/ProviderHelpInfo.cs @@ -36,17 +36,17 @@ internal override string Name { get { - if (_fullHelpObject is null) + if (_fullHelpObject == null) return string.Empty; - if (_fullHelpObject.Properties["Name"] is null) + if (_fullHelpObject.Properties["Name"] == null) return string.Empty; - if (_fullHelpObject.Properties["Name"].Value is null) + if (_fullHelpObject.Properties["Name"].Value == null) return string.Empty; string name = _fullHelpObject.Properties["Name"].Value.ToString(); - if (name is null) + if (name == null) return string.Empty; return name.Trim(); @@ -61,17 +61,17 @@ internal override string Synopsis { get { - if (_fullHelpObject is null) + if (_fullHelpObject == null) return string.Empty; - if (_fullHelpObject.Properties["Synopsis"] is null) + if (_fullHelpObject.Properties["Synopsis"] == null) return string.Empty; - if (_fullHelpObject.Properties["Synopsis"].Value is null) + if (_fullHelpObject.Properties["Synopsis"].Value == null) return string.Empty; string synopsis = _fullHelpObject.Properties["Synopsis"].Value.ToString(); - if (synopsis is null) + if (synopsis == null) return string.Empty; return synopsis.Trim(); @@ -86,17 +86,17 @@ internal string DetailedDescription { get { - if (this.FullHelp is null) + if (this.FullHelp == null) return string.Empty; - if (this.FullHelp.Properties["DetailedDescription"] is null || - this.FullHelp.Properties["DetailedDescription"].Value is null) + if (this.FullHelp.Properties["DetailedDescription"] == null || + this.FullHelp.Properties["DetailedDescription"].Value == null) { return string.Empty; } IList descriptionItems = FullHelp.Properties["DetailedDescription"].Value as IList; - if (descriptionItems is null || descriptionItems.Count == 0) + if (descriptionItems == null || descriptionItems.Count == 0) { return string.Empty; } @@ -108,9 +108,9 @@ internal string DetailedDescription foreach (object descriptionItem in descriptionItems) { PSObject descriptionObject = PSObject.AsPSObject(descriptionItem); - if ((descriptionObject is null) || - (descriptionObject.Properties["Text"] is null) || - (descriptionObject.Properties["Text"].Value is null)) + if ((descriptionObject == null) || + (descriptionObject.Properties["Text"] == null) || + (descriptionObject.Properties["Text"].Value == null)) { continue; } @@ -167,12 +167,12 @@ internal override bool MatchPatternInContent(WildcardPattern pattern) string synopsis = Synopsis; string detailedDescription = DetailedDescription; - if (synopsis is null) + if (synopsis == null) { synopsis = string.Empty; } - if (detailedDescription is null) + if (detailedDescription == null) { detailedDescription = string.Empty; } @@ -199,7 +199,7 @@ internal PSObject GetCmdletHelp(string cmdletName) LoadCmdletHelps(); - if (_cmdletHelps is null) + if (_cmdletHelps == null) return null; return (PSObject)_cmdletHelps[cmdletName]; @@ -214,21 +214,21 @@ private void LoadCmdletHelps() if (_cmdletHelps != null) return; - if (_fullHelpObject is null) + if (_fullHelpObject == null) return; _cmdletHelps = new Hashtable(); - if (_fullHelpObject.Properties["Cmdlets"] is null) + if (_fullHelpObject.Properties["Cmdlets"] == null) return; PSObject cmdlets = (PSObject)_fullHelpObject.Properties["Cmdlets"].Value; - if (cmdlets is null) + if (cmdlets == null) return; - if (cmdlets.Properties["Cmdlet"] is null || - cmdlets.Properties["Cmdlet"].Value is null) + if (cmdlets.Properties["Cmdlet"] == null || + cmdlets.Properties["Cmdlet"].Value == null) return; if (cmdlets.Properties["Cmdlet"].Value.GetType().Equals(typeof(PSObject[]))) @@ -237,8 +237,8 @@ private void LoadCmdletHelps() for (int i = 0; i < cmdletHelpItems.Length; i++) { - if (cmdletHelpItems[i].Properties["Name"] is null - || cmdletHelpItems[i].Properties["Name"].Value is null) + if (cmdletHelpItems[i].Properties["Name"] == null + || cmdletHelpItems[i].Properties["Name"].Value == null) return; string name = ((PSObject)cmdletHelpItems[i].Properties["Name"].Value).ToString(); @@ -265,12 +265,12 @@ private void LoadCmdletHelps() /// An array of mshObject that contains the parameter help. internal PSObject[] GetDynamicParameterHelp(string[] parameters) { - if (parameters is null || parameters.Length == 0) + if (parameters == null || parameters.Length == 0) return null; LoadDynamicParameterHelps(); - if (_dynamicParameterHelps is null) + if (_dynamicParameterHelps == null) return null; ArrayList result = new ArrayList(); @@ -295,21 +295,21 @@ private void LoadDynamicParameterHelps() if (_dynamicParameterHelps != null) return; - if (_fullHelpObject is null) + if (_fullHelpObject == null) return; _dynamicParameterHelps = new Hashtable(); - if (_fullHelpObject.Properties["DynamicParameters"] is null) + if (_fullHelpObject.Properties["DynamicParameters"] == null) return; PSObject dynamicParameters = (PSObject)_fullHelpObject.Properties["DynamicParameters"].Value; - if (dynamicParameters is null) + if (dynamicParameters == null) return; - if (dynamicParameters.Properties["DynamicParameter"] is null - || dynamicParameters.Properties["DynamicParameter"].Value is null) + if (dynamicParameters.Properties["DynamicParameter"] == null + || dynamicParameters.Properties["DynamicParameter"].Value == null) return; if (dynamicParameters.Properties["DynamicParameter"].Value.GetType().Equals(typeof(PSObject[]))) @@ -318,8 +318,8 @@ private void LoadDynamicParameterHelps() for (int i = 0; i < dynamicParameterHelpItems.Length; i++) { - if (dynamicParameterHelpItems[i].Properties["Name"] is null - || dynamicParameterHelpItems[i].Properties["Name"].Value is null) + if (dynamicParameterHelpItems[i].Properties["Name"] == null + || dynamicParameterHelpItems[i].Properties["Name"].Value == null) return; string name = ((PSObject)dynamicParameterHelpItems[i].Properties["Name"].Value).ToString(); diff --git a/src/System.Management.Automation/help/ProviderHelpProvider.cs b/src/System.Management.Automation/help/ProviderHelpProvider.cs index 1e7037cb540..b28dcf86398 100644 --- a/src/System.Management.Automation/help/ProviderHelpProvider.cs +++ b/src/System.Management.Automation/help/ProviderHelpProvider.cs @@ -120,10 +120,10 @@ internal override IEnumerable ExactMatchHelp(HelpRequest helpRequest) private static string GetProviderAssemblyPath(ProviderInfo providerInfo) { - if (providerInfo is null) + if (providerInfo == null) return null; - if (providerInfo.ImplementingType is null) + if (providerInfo.ImplementingType == null) return null; return Path.GetDirectoryName(providerInfo.ImplementingType.Assembly.Location); @@ -147,7 +147,7 @@ private static string GetProviderAssemblyPath(ProviderInfo providerInfo) /// ProviderInfo for which to locate help. private void LoadHelpFile(ProviderInfo providerInfo) { - if (providerInfo is null) + if (providerInfo == null) { throw PSTraceSource.NewArgumentNullException(nameof(providerInfo)); } @@ -217,7 +217,7 @@ private void LoadHelpFile(ProviderInfo providerInfo) } } - if (helpItemsNode is null) + if (helpItemsNode == null) return; using (this.HelpSystem.Trace(location)) @@ -298,7 +298,7 @@ internal override IEnumerable SearchHelp(HelpRequest helpRequest, bool PSSnapinQualifiedName snapinQualifiedNameForPattern = PSSnapinQualifiedName.GetInstance(pattern); - if (snapinQualifiedNameForPattern is null) + if (snapinQualifiedNameForPattern == null) { yield break; } @@ -377,7 +377,7 @@ internal override IEnumerable ProcessForwardedHelp(HelpInfo helpInfo, /// The help info object after processing. override internal HelpInfo ProcessForwardedHelp(HelpInfo helpInfo, HelpRequest helpRequest) { - if (helpInfo is null) + if (helpInfo == null) return null; if (helpInfo.HelpCategory != HelpCategory.Command) @@ -396,7 +396,7 @@ override internal HelpInfo ProcessForwardedHelp(HelpInfo helpInfo, HelpRequest h ProviderHelpInfo providerHelpInfo = (ProviderHelpInfo)this.ExactMatchHelp(providerHelpRequest); - if (providerHelpInfo is null) + if (providerHelpInfo == null) return null; CommandHelpInfo commandHelpInfo = (CommandHelpInfo)helpInfo; diff --git a/src/System.Management.Automation/help/RemoteHelpInfo.cs b/src/System.Management.Automation/help/RemoteHelpInfo.cs index e0823880a55..a80ba7a7736 100644 --- a/src/System.Management.Automation/help/RemoteHelpInfo.cs +++ b/src/System.Management.Automation/help/RemoteHelpInfo.cs @@ -42,7 +42,7 @@ internal RemoteHelpInfo( helpResults = powerShell.Invoke(); } - if ((helpResults is null) || (helpResults.Count == 0)) + if ((helpResults == null) || (helpResults.Count == 0)) { throw new Microsoft.PowerShell.Commands.HelpNotFoundException(remoteHelpTopic); } @@ -87,7 +87,7 @@ internal override PSObject FullHelp private string GetHelpProperty(string propertyName) { PSPropertyInfo property = _deserializedRemoteHelp.Properties[propertyName]; - if (property is null) + if (property == null) { return null; } diff --git a/src/System.Management.Automation/help/SaveHelpCommand.cs b/src/System.Management.Automation/help/SaveHelpCommand.cs index 26de687778b..3c4d18af00a 100644 --- a/src/System.Management.Automation/help/SaveHelpCommand.cs +++ b/src/System.Management.Automation/help/SaveHelpCommand.cs @@ -311,7 +311,7 @@ internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, newHelpInfo = _helpSystem.GetHelpInfo(_commandType, uri, module.ModuleName, module.ModuleGuid, culture); - if (newHelpInfo is null) + if (newHelpInfo == null) { throw new UpdatableHelpSystemException("UnableToRetrieveHelpInfoXml", StringUtil.Format(HelpDisplayStrings.UnableToRetrieveHelpInfoXml, culture), ErrorCategory.ResourceUnavailable, diff --git a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs index ff688dbf56f..e9f601aba52 100644 --- a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs +++ b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs @@ -60,7 +60,7 @@ public CultureInfo[] UICulture set { - if (value is null) return; + if (value == null) return; _language = new string[value.Length]; for (int index = 0; index < value.Length; index++) { @@ -443,7 +443,7 @@ internal void Process(IEnumerable moduleNames, IEnumerableModule objects given by the user. internal void Process(IEnumerable modules) { - if (modules is null || !modules.Any()) { return; } + if (modules == null || !modules.Any()) { return; } var helpModules = new Dictionary, UpdatableHelpModuleInfo>(); @@ -583,7 +583,7 @@ private void ProcessModule(UpdatableHelpModuleInfo module) // If -Language is not specified, we only install // one culture from the fallback chain - if (_language is null && installed) + if (_language == null && installed) { break; } @@ -644,7 +644,7 @@ internal bool IsUpdateNecessary(UpdatableHelpModuleInfo module, UpdatableHelpInf { Debug.Assert(module != null); - if (newHelpInfo is null) + if (newHelpInfo == null) { throw new UpdatableHelpSystemException("UnableToRetrieveHelpInfoXml", StringUtil.Format(HelpDisplayStrings.UnableToRetrieveHelpInfoXml, culture.Name), ErrorCategory.ResourceUnavailable, @@ -806,7 +806,7 @@ private IEnumerable RecursiveResolvePathHelper(string path) /// Path to validate. internal void ValidatePathProvider(PathInfo path) { - if (path.Provider is null || path.Provider.Name != FileSystemProvider.ProviderName) + if (path.Provider == null || path.Provider.Name != FileSystemProvider.ProviderName) { throw new PSArgumentException(StringUtil.Format(HelpDisplayStrings.ProviderIsNotFileSystem, path.Path)); diff --git a/src/System.Management.Automation/help/UpdatableHelpInfo.cs b/src/System.Management.Automation/help/UpdatableHelpInfo.cs index df59e49e45f..5af3fd57b6d 100644 --- a/src/System.Management.Automation/help/UpdatableHelpInfo.cs +++ b/src/System.Management.Automation/help/UpdatableHelpInfo.cs @@ -88,7 +88,7 @@ internal bool IsNewerVersion(UpdatableHelpInfo helpInfo, CultureInfo culture) Debug.Assert(v1 != null); - if (v2 is null) + if (v2 == null) { return true; } diff --git a/src/System.Management.Automation/help/UpdatableHelpSystem.cs b/src/System.Management.Automation/help/UpdatableHelpSystem.cs index e28b96a26a3..0a45b9a7605 100644 --- a/src/System.Management.Automation/help/UpdatableHelpSystem.cs +++ b/src/System.Management.Automation/help/UpdatableHelpSystem.cs @@ -1246,7 +1246,7 @@ private void ValidateAndCopyHelpContent(string sourcePath, Collection de { if (string.Equals(Path.GetExtension(file), ".xml", StringComparison.OrdinalIgnoreCase)) { - if (xsd is null) + if (xsd == null) { throw new ItemNotFoundException(StringUtil.Format(HelpDisplayStrings.HelpContentXsdNotFound, xsdPath)); } diff --git a/src/System.Management.Automation/help/UpdateHelpCommand.cs b/src/System.Management.Automation/help/UpdateHelpCommand.cs index 5936e6d91c3..bccd7418476 100644 --- a/src/System.Management.Automation/help/UpdateHelpCommand.cs +++ b/src/System.Management.Automation/help/UpdateHelpCommand.cs @@ -143,7 +143,7 @@ public SwitchParameter Recurse /// protected override void BeginProcessing() { - if (_path is null) + if (_path == null) { // Pull default source path from GP string defaultSourcePath = _helpSystem.GetDefaultSourcePath(); @@ -173,7 +173,7 @@ protected override void ProcessRecord() if (!_isInitialized) { - if (_path is null && Recurse.IsPresent) + if (_path == null && Recurse.IsPresent) { PSArgumentException e = new PSArgumentException(StringUtil.Format(HelpDisplayStrings.CannotSpecifyRecurseWithoutPath)); ThrowTerminatingError(e.ErrorRecord); @@ -337,7 +337,7 @@ internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, newHelpInfo = _helpSystem.GetHelpInfo(UpdatableHelpCommandType.UpdateHelpCommand, uri, module.ModuleName, module.ModuleGuid, culture); } - if (newHelpInfo is null) + if (newHelpInfo == null) { throw new UpdatableHelpSystemException("UnableToRetrieveHelpInfoXml", StringUtil.Format(HelpDisplayStrings.UnableToRetrieveHelpInfoXml, culture), ErrorCategory.ResourceUnavailable, diff --git a/src/System.Management.Automation/logging/LogProvider.cs b/src/System.Management.Automation/logging/LogProvider.cs index c27c246e91e..a46f181b262 100644 --- a/src/System.Management.Automation/logging/LogProvider.cs +++ b/src/System.Management.Automation/logging/LogProvider.cs @@ -145,14 +145,14 @@ private static class Strings /// protected static string GetPSLogUserData(ExecutionContext context) { - if (context is null) + if (context == null) { return string.Empty; } object logData = context.GetVariableValue(SpecialVariables.PSLogUserDataPath); - if (logData is null) + if (logData == null) { return string.Empty; } diff --git a/src/System.Management.Automation/logging/MshLog.cs b/src/System.Management.Automation/logging/MshLog.cs index a1f73699056..23c687b58ee 100644 --- a/src/System.Management.Automation/logging/MshLog.cs +++ b/src/System.Management.Automation/logging/MshLog.cs @@ -99,7 +99,7 @@ private static IEnumerable GetLogProvider(string shellId) /// private static IEnumerable GetLogProvider(ExecutionContext executionContext) { - if (executionContext is null) + if (executionContext == null) { throw PSTraceSource.NewArgumentNullException(nameof(executionContext)); } @@ -203,13 +203,13 @@ internal static void LogEngineHealthEvent(ExecutionContext executionContext, Dictionary additionalInfo, EngineState newEngineState) { - if (executionContext is null) + if (executionContext == null) { PSTraceSource.NewArgumentNullException(nameof(executionContext)); return; } - if (exception is null) + if (exception == null) { PSTraceSource.NewArgumentNullException(nameof(exception)); return; @@ -318,13 +318,13 @@ internal static void LogEngineHealthEvent(LogContext logContext, Dictionary additionalInfo ) { - if (logContext is null) + if (logContext == null) { PSTraceSource.NewArgumentNullException(nameof(logContext)); return; } - if (exception is null) + if (exception == null) { PSTraceSource.NewArgumentNullException(nameof(exception)); return; @@ -357,7 +357,7 @@ internal static void LogEngineLifecycleEvent(ExecutionContext executionContext, EngineState engineState, InvocationInfo invocationInfo) { - if (executionContext is null) + if (executionContext == null) { PSTraceSource.NewArgumentNullException(nameof(executionContext)); return; @@ -405,13 +405,13 @@ internal static void LogCommandHealthEvent(ExecutionContext executionContext, Severity severity ) { - if (executionContext is null) + if (executionContext == null) { PSTraceSource.NewArgumentNullException(nameof(executionContext)); return; } - if (exception is null) + if (exception == null) { PSTraceSource.NewArgumentNullException(nameof(exception)); return; @@ -446,13 +446,13 @@ internal static void LogCommandLifecycleEvent(ExecutionContext executionContext, CommandState commandState, InvocationInfo invocationInfo) { - if (executionContext is null) + if (executionContext == null) { PSTraceSource.NewArgumentNullException(nameof(executionContext)); return; } - if (invocationInfo is null) + if (invocationInfo == null) { PSTraceSource.NewArgumentNullException(nameof(invocationInfo)); return; @@ -488,7 +488,7 @@ internal static void LogCommandLifecycleEvent(ExecutionContext executionContext, CommandState commandState, string commandName) { - if (executionContext is null) + if (executionContext == null) { PSTraceSource.NewArgumentNullException(nameof(executionContext)); return; @@ -502,7 +502,7 @@ internal static void LogCommandLifecycleEvent(ExecutionContext executionContext, provider.LogCommandLifecycleEvent( () => { - if (logContext is null) + if (logContext == null) { logContext = GetLogContext(executionContext, null); logContext.CommandName = commandName; @@ -529,7 +529,7 @@ internal static void LogPipelineExecutionDetailEvent(ExecutionContext executionC InvocationInfo invocationInfo) { - if (executionContext is null) + if (executionContext == null) { PSTraceSource.NewArgumentNullException(nameof(executionContext)); return; @@ -560,7 +560,7 @@ internal static void LogPipelineExecutionDetailEvent(ExecutionContext executionC string scriptName, string commandLine) { - if (executionContext is null) + if (executionContext == null) { PSTraceSource.NewArgumentNullException(nameof(executionContext)); return; @@ -596,13 +596,13 @@ internal static void LogProviderHealthEvent(ExecutionContext executionContext, Severity severity ) { - if (executionContext is null) + if (executionContext == null) { PSTraceSource.NewArgumentNullException(nameof(executionContext)); return; } - if (exception is null) + if (exception == null) { PSTraceSource.NewArgumentNullException(nameof(exception)); return; @@ -637,7 +637,7 @@ internal static void LogProviderLifecycleEvent(ExecutionContext executionContext string providerName, ProviderState providerState) { - if (executionContext is null) + if (executionContext == null) { PSTraceSource.NewArgumentNullException(nameof(executionContext)); return; @@ -673,7 +673,7 @@ internal static void LogSettingsEvent(ExecutionContext executionContext, string previousValue, InvocationInfo invocationInfo) { - if (executionContext is null) + if (executionContext == null) { PSTraceSource.NewArgumentNullException(nameof(executionContext)); return; @@ -757,7 +757,7 @@ internal static LogContext GetLogContext(ExecutionContext executionContext, Invo /// private static LogContext GetLogContext(ExecutionContext executionContext, InvocationInfo invocationInfo, Severity severity) { - if (executionContext is null) + if (executionContext == null) return null; LogContext logContext = new LogContext(); @@ -793,7 +793,7 @@ private static LogContext GetLogContext(ExecutionContext executionContext, Invoc try { - if (executionContext.LogContextCache.User is null) + if (executionContext.LogContextCache.User == null) { logContext.User = Environment.UserDomainName + "\\" + Environment.UserName; executionContext.LogContextCache.User = logContext.User; @@ -817,7 +817,7 @@ private static LogContext GetLogContext(ExecutionContext executionContext, Invoc logContext.Time = DateTime.Now.ToString(CultureInfo.CurrentCulture); - if (invocationInfo is null) + if (invocationInfo == null) return logContext; logContext.ScriptName = invocationInfo.ScriptName; diff --git a/src/System.Management.Automation/namespaces/AliasProvider.cs b/src/System.Management.Automation/namespaces/AliasProvider.cs index 0d7749516a5..d6b99155630 100644 --- a/src/System.Management.Automation/namespaces/AliasProvider.cs +++ b/src/System.Management.Automation/namespaces/AliasProvider.cs @@ -190,7 +190,7 @@ internal override void SetSessionStateItem(string name, object value, bool write bool dynamicParametersSpecified = dynamicParameters != null && dynamicParameters.OptionsSet; - if (value is null) + if (value == null) { if (dynamicParametersSpecified) { diff --git a/src/System.Management.Automation/namespaces/CoreCommandContext.cs b/src/System.Management.Automation/namespaces/CoreCommandContext.cs index 5b31fa558d1..34cdb0d68b7 100644 --- a/src/System.Management.Automation/namespaces/CoreCommandContext.cs +++ b/src/System.Management.Automation/namespaces/CoreCommandContext.cs @@ -52,7 +52,7 @@ internal sealed class CmdletProviderContext /// internal CmdletProviderContext(ExecutionContext executionContext) { - if (executionContext is null) + if (executionContext == null) { throw PSTraceSource.NewArgumentNullException(nameof(executionContext)); } @@ -82,7 +82,7 @@ internal CmdletProviderContext(ExecutionContext executionContext) /// internal CmdletProviderContext(ExecutionContext executionContext, CommandOrigin origin) { - if (executionContext is null) + if (executionContext == null) { throw PSTraceSource.NewArgumentNullException(nameof(executionContext)); } @@ -116,7 +116,7 @@ internal CmdletProviderContext( PSDriveInfo drive) { // verify the command parameter - if (command is null) + if (command == null) { throw PSTraceSource.NewArgumentNullException(nameof(command)); } @@ -131,12 +131,12 @@ internal CmdletProviderContext( Drive = drive; - if (command.Host is null) + if (command.Host == null) { throw PSTraceSource.NewArgumentException("command.Host"); } - if (command.Context is null) + if (command.Context == null) { throw PSTraceSource.NewArgumentException("command.Context"); } @@ -170,7 +170,7 @@ internal CmdletProviderContext( PSCredential credentials) { // verify the command parameter - if (command is null) + if (command == null) { throw PSTraceSource.NewArgumentNullException(nameof(command)); } @@ -183,12 +183,12 @@ internal CmdletProviderContext( _credentials = credentials; } - if (command.Host is null) + if (command.Host == null) { throw PSTraceSource.NewArgumentException("command.Host"); } - if (command.Context is null) + if (command.Context == null) { throw PSTraceSource.NewArgumentException("command.Context"); } @@ -218,7 +218,7 @@ internal CmdletProviderContext( Cmdlet command) { // verify the command parameter - if (command is null) + if (command == null) { throw PSTraceSource.NewArgumentNullException(nameof(command)); } @@ -226,7 +226,7 @@ internal CmdletProviderContext( _command = command; Origin = command.CommandOrigin; - if (command.Context is null) + if (command.Context == null) { throw PSTraceSource.NewArgumentException("command.Context"); } @@ -254,7 +254,7 @@ internal CmdletProviderContext( internal CmdletProviderContext( CmdletProviderContext contextToCopyFrom) { - if (contextToCopyFrom is null) + if (contextToCopyFrom == null) { throw PSTraceSource.NewArgumentNullException(nameof(contextToCopyFrom)); } @@ -450,7 +450,7 @@ internal PSCredential Credential // If the username wasn't specified, use the drive credentials - if (_credentials is null && Drive != null) + if (_credentials == null && Drive != null) { result = Drive.Credential; } @@ -983,7 +983,7 @@ internal void ThrowFirstErrorOrDoNothing(bool wrapExceptionInProviderException) /// internal void WriteErrorsToContext(CmdletProviderContext errorContext) { - if (errorContext is null) + if (errorContext == null) { throw PSTraceSource.NewArgumentNullException(nameof(errorContext)); } diff --git a/src/System.Management.Automation/namespaces/EnvironmentProvider.cs b/src/System.Management.Automation/namespaces/EnvironmentProvider.cs index b22a3ecde9c..4f1fd8eb0b0 100644 --- a/src/System.Management.Automation/namespaces/EnvironmentProvider.cs +++ b/src/System.Management.Automation/namespaces/EnvironmentProvider.cs @@ -111,7 +111,7 @@ internal override void SetSessionStateItem(string name, object value, bool write !string.IsNullOrEmpty(name), "The caller should verify this parameter"); - if (value is null) + if (value == null) { Environment.SetEnvironmentVariable(name, null); } @@ -127,7 +127,7 @@ internal override void SetSessionStateItem(string name, object value, bool write } string stringValue = value as string; - if (stringValue is null) + if (stringValue == null) { // try using ETS to convert to a string. diff --git a/src/System.Management.Automation/namespaces/FileSystemContentStream.cs b/src/System.Management.Automation/namespaces/FileSystemContentStream.cs index 63770c59239..6a81206e221 100644 --- a/src/System.Management.Automation/namespaces/FileSystemContentStream.cs +++ b/src/System.Management.Automation/namespaces/FileSystemContentStream.cs @@ -564,7 +564,7 @@ private bool ReadByLine(bool waitChanges, List blocks, bool readBackward // Reading lines as strings string line = readBackward ? _backReader.ReadLine() : _reader.ReadLine(); - if (line is null) + if (line == null) { if (waitChanges) { @@ -574,7 +574,7 @@ private bool ReadByLine(bool waitChanges, List blocks, bool readBackward WaitForChanges(_path, _mode, _access, _share, _reader.CurrentEncoding); line = _reader.ReadLine(); } - while ((line is null) && (!_provider.Stopping)); + while ((line == null) && (!_provider.Stopping)); } } @@ -1075,7 +1075,7 @@ public IList Write(IList content) private void WriteObject(object content) { - if (content is null) + if (content == null) { return; } diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 3c82e1a4e11..a24b48c0ef3 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -512,7 +512,7 @@ protected override ProviderInfo Start(ProviderInfo providerInfo) protected override PSDriveInfo NewDrive(PSDriveInfo drive) { // verify parameters - if (drive is null) + if (drive == null) { throw PSTraceSource.NewArgumentNullException(nameof(drive)); } @@ -1909,7 +1909,7 @@ private void Dir( // b) the directory pointed to by the symlink has not already been visited, // preventing symlink loops. // c) it is not a reparse point with a target (not OneDrive or an AppX link). - if (tracker is null) + if (tracker == null) { if (InternalSymbolicLinkLinkCodeMethods.IsReparsePointWithTarget(recursiveDirectory)) { @@ -2971,7 +2971,7 @@ protected override void RemoveItem(string path, bool recurse) #endif FileSystemInfo fsinfo = GetFileSystemInfo(path, out bool iscontainer); - if (fsinfo is null) + if (fsinfo == null) { string error = StringUtil.Format(FileSystemProviderStrings.ItemDoesNotExist, path); Exception e = new IOException(error); @@ -3638,7 +3638,7 @@ protected override void CopyItem( _excludeMatcher = SessionStateUtilities.CreateWildcardsFromStrings(Exclude, WildcardOptions.IgnoreCase); // if the source and destination path are same (for a local copy) then flag it as error. - if ((toSession is null) && (fromSession is null) && InternalSymbolicLinkLinkCodeMethods.IsSameFileSystemItem(path, destinationPath)) + if ((toSession == null) && (fromSession == null) && InternalSymbolicLinkLinkCodeMethods.IsSameFileSystemItem(path, destinationPath)) { string error = StringUtil.Format(FileSystemProviderStrings.CopyError, path); Exception e = new IOException(error); @@ -3687,7 +3687,7 @@ private void CopyItemFromRemoteSession(string path, string destinationPath, bool ps.AddParameter("getPathItems", path); Hashtable op = SafeInvokeCommand.Invoke(ps, this, null); - if (op is null) + if (op == null) { Exception e = new IOException(string.Format(CultureInfo.InvariantCulture, FileSystemProviderStrings.CopyItemRemotelyFailedToReadFile, path)); WriteError(new ErrorRecord(e, "CopyItemRemotelyFailedToReadFile", ErrorCategory.WriteError, path)); @@ -3799,7 +3799,7 @@ private void CopyDirectoryInfoItem( // If the destination doesn't exist we will just try to copy to that new // path. - if (ps is null) + if (ps == null) { if (IsItemContainer(destination)) { @@ -3825,7 +3825,7 @@ private void CopyDirectoryInfoItem( { // Create the new directory // CreateDirectory does the WriteItemObject for the new DirectoryInfo - if (ps is null) + if (ps == null) { CreateDirectory(destination, true); } @@ -3842,7 +3842,7 @@ private void CopyDirectoryInfoItem( } destination = CreateDirectoryOnRemoteSession(destination, force, ps); - if (destination is null) + if (destination == null) { return; } @@ -3935,7 +3935,7 @@ private void CopyFileInfoItem(FileInfo file, string destinationPath, bool force, // If the destination is a container, add the file name // to the destination path. - if (ps is null) + if (ps == null) { if (IsItemContainer(destinationPath)) { @@ -3971,7 +3971,7 @@ private void CopyFileInfoItem(FileInfo file, string destinationPath, bool force, { try { - if (ps is null) + if (ps == null) { // Now copy the file // We assume that if we get called we want to make @@ -3992,7 +3992,7 @@ private void CopyFileInfoItem(FileInfo file, string destinationPath, bool force, { try { - if (ps is null) + if (ps == null) { // If the destination exists and force is specified, // mask of the readonly and hidden attributes and @@ -4082,7 +4082,7 @@ private void CopyDirectoryFromRemoteSession( ps.AddParameter("getPathDir", sourceDirectoryFullName); Hashtable op = SafeInvokeCommand.Invoke(ps, this, null); - if (op is null) + if (op == null) { Exception e = new IOException(string.Format( CultureInfo.InvariantCulture, @@ -4180,7 +4180,7 @@ private ArrayList GetRemoteSourceAlternateStreams(System.Management.Automation.P private void InitializeFunctionPSCopyFileFromRemoteSession(System.Management.Automation.PowerShell ps) { - if ((ps is null) || !ValidRemoteSessionForScripting(ps.Runspace)) + if ((ps == null) || !ValidRemoteSessionForScripting(ps.Runspace)) { return; } @@ -4191,7 +4191,7 @@ private void InitializeFunctionPSCopyFileFromRemoteSession(System.Management.Aut private void RemoveFunctionsPSCopyFileFromRemoteSession(System.Management.Automation.PowerShell ps) { - if ((ps is null) || !ValidRemoteSessionForScripting(ps.Runspace)) + if ((ps == null) || !ValidRemoteSessionForScripting(ps.Runspace)) { return; } @@ -4400,7 +4400,7 @@ private bool PerformCopyFileFromRemoteSession(string sourceFileFullName, FileInf Hashtable op = SafeInvokeCommand.Invoke(ps, this, null); // Check if there was an exception when reading the remote file. - if (op is null) + if (op == null) { errorWhileCopyRemoteFile = true; Exception e = new IOException(string.Format(CultureInfo.InvariantCulture, @@ -4497,7 +4497,7 @@ private bool PerformCopyFileFromRemoteSession(string sourceFileFullName, FileInf private void InitializeFunctionsPSCopyFileToRemoteSession(System.Management.Automation.PowerShell ps) { - if ((ps is null) || !ValidRemoteSessionForScripting(ps.Runspace)) { return; } + if ((ps == null) || !ValidRemoteSessionForScripting(ps.Runspace)) { return; } ps.AddScript(CopyFileRemoteUtils.AllCopyToRemoteScripts); SafeInvokeCommand.Invoke(ps, this, null, false); @@ -4505,7 +4505,7 @@ private void InitializeFunctionsPSCopyFileToRemoteSession(System.Management.Auto private void RemoveFunctionPSCopyFileToRemoteSession(System.Management.Automation.PowerShell ps) { - if ((ps is null) || !ValidRemoteSessionForScripting(ps.Runspace)) { return; } + if ((ps == null) || !ValidRemoteSessionForScripting(ps.Runspace)) { return; } string remoteScript = @" Microsoft.PowerShell.Management\Remove-Item function:PSCopyToSessionHelper -ea SilentlyContinue -Force @@ -4659,7 +4659,7 @@ private bool CopyFileStreamToRemoteSession(FileInfo file, string destinationPath toRead = (int)remainingFileSize; } - if (fragment is null) + if (fragment == null) { fragment = new byte[toRead]; } @@ -4712,7 +4712,7 @@ private bool CopyFileStreamToRemoteSession(FileInfo file, string destinationPath } Hashtable op = SafeInvokeCommand.Invoke(ps, this, null); - if (op is null || op["BytesWritten"] is null) + if (op == null || op["BytesWritten"] == null) { // write error to stream Exception e = new IOException(string.Format(CultureInfo.InvariantCulture, FileSystemProviderStrings.CopyItemRemotelyFailed, file)); @@ -4843,7 +4843,7 @@ private bool RemoteDestinationPathIsFile(string destination, System.Management.A Hashtable op = SafeInvokeCommand.Invoke(ps, this, null); - if (op is null || op["IsFileInfo"] is null) + if (op == null || op["IsFileInfo"] == null) { Exception e = new IOException(string.Format( CultureInfo.InvariantCulture, @@ -4867,7 +4867,7 @@ private string CreateDirectoryOnRemoteSession(string destination, bool force, Sy Hashtable op = SafeInvokeCommand.Invoke(ps, this, null); - // If op is null, SafeInvokeCommand.Invoke throwns an error. + // If op == null, SafeInvokeCommand.Invoke throwns an error. if (op["ExceptionThrown"] != null) { // If an error is thrown on the remote session, it is written via SafeInvokeCommand.Invoke. @@ -4875,7 +4875,7 @@ private string CreateDirectoryOnRemoteSession(string destination, bool force, Sy return null; } - if (force && (op["DirectoryPath"] is null)) + if (force && (op["DirectoryPath"] == null)) { Exception e = new IOException(string.Format(CultureInfo.InvariantCulture, FileSystemProviderStrings.CopyItemRemotelyFailedToCreateDirectory, @@ -5072,7 +5072,7 @@ protected override string NormalizeRelativePath( throw PSTraceSource.NewArgumentException(nameof(path)); } - if (basePath is null) + if (basePath == null) { basePath = string.Empty; } @@ -5162,12 +5162,12 @@ protected override string NormalizeRelativePath( // ensure the proper casing IEnumerable files = Directory.EnumerateFiles(directoryPath, leafName); - if (files is null || !files.Any()) + if (files == null || !files.Any()) { files = Directory.EnumerateDirectories(directoryPath, leafName); } - if (files is null || !files.Any()) + if (files == null || !files.Any()) { string error = StringUtil.Format(FileSystemProviderStrings.ItemDoesNotExist, path); Exception e = new IOException(error); @@ -5254,7 +5254,7 @@ protected override string NormalizeRelativePath( /// private string NormalizeRelativePathHelper(string path, string basePath) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -5264,7 +5264,7 @@ private string NormalizeRelativePathHelper(string path, string basePath) return string.Empty; } - if (basePath is null) + if (basePath == null) { basePath = string.Empty; } @@ -6180,7 +6180,7 @@ public void GetProperty(string path, Collection providerSpecificPickList { var fileSystemObject = GetFileSystemInfo(path, out bool isDirectory); - if (fileSystemObject is null) + if (fileSystemObject == null) { string error = StringUtil.Format(FileSystemProviderStrings.ItemDoesNotExist, path); Exception e = new IOException(error); @@ -6193,7 +6193,7 @@ public void GetProperty(string path, Collection providerSpecificPickList else { // Finally get the properties - if (providerSpecificPickList is null || providerSpecificPickList.Count == 0) + if (providerSpecificPickList == null || providerSpecificPickList.Count == 0) { result = PSObject.AsPSObject(fileSystemObject); } @@ -6211,7 +6211,7 @@ public void GetProperty(string path, Collection providerSpecificPickList if (member != null) { value = member.Value; - if (result is null) + if (result == null) { result = new PSObject(); } @@ -6305,7 +6305,7 @@ public void SetProperty(string path, PSObject propertyToSet) throw PSTraceSource.NewArgumentException(nameof(path)); } - if (propertyToSet is null) + if (propertyToSet == null) { throw PSTraceSource.NewArgumentNullException(nameof(propertyToSet)); } @@ -6478,7 +6478,7 @@ public void ClearProperty( path = NormalizePath(path); - if (propertiesToClear is null || + if (propertiesToClear == null || propertiesToClear.Count == 0) { throw PSTraceSource.NewArgumentNullException(nameof(propertiesToClear)); @@ -7424,7 +7424,7 @@ public static Hashtable Invoke(System.Management.Automation.PowerShell ps, FileS public static Hashtable Invoke(System.Management.Automation.PowerShell ps, FileSystemProvider fileSystemContext, CmdletProviderContext cmdletContext, bool shouldHaveOutput) { - bool useFileSystemProviderContext = (cmdletContext is null); + bool useFileSystemProviderContext = (cmdletContext == null); if (useFileSystemProviderContext) { @@ -8591,7 +8591,7 @@ public static class AlternateDataStreamUtilities /// The list of streams (and their size) in the file. internal static List GetStreams(string path) { - if (path is null) throw new ArgumentNullException(nameof(path)); + if (path == null) throw new ArgumentNullException(nameof(path)); List alternateStreams = new List(); @@ -8669,12 +8669,12 @@ internal static FileStream CreateFileStream(string path, string streamName, File /// True if the stream was successfully created, otherwise false. internal static bool TryCreateFileStream(string path, string streamName, FileMode mode, FileAccess access, FileShare share, out FileStream stream) { - if (path is null) + if (path == null) { throw new ArgumentNullException(nameof(path)); } - if (streamName is null) + if (streamName == null) { throw new ArgumentNullException(nameof(streamName)); } @@ -8704,8 +8704,8 @@ internal static bool TryCreateFileStream(string path, string streamName, FileMod /// The name of the alternate data stream to delete. internal static void DeleteFileStream(string path, string streamName) { - if (path is null) throw new ArgumentNullException(nameof(path)); - if (streamName is null) throw new ArgumentNullException(nameof(streamName)); + if (path == null) throw new ArgumentNullException(nameof(path)); + if (streamName == null) throw new ArgumentNullException(nameof(streamName)); string adjustedStreamName = streamName.Trim(); if (adjustedStreamName.IndexOf(':') != 0) diff --git a/src/System.Management.Automation/namespaces/FileSystemSecurity.cs b/src/System.Management.Automation/namespaces/FileSystemSecurity.cs index 083376c1bda..8a95b16ee8b 100644 --- a/src/System.Management.Automation/namespaces/FileSystemSecurity.cs +++ b/src/System.Management.Automation/namespaces/FileSystemSecurity.cs @@ -108,7 +108,7 @@ public void SetSecurityDescriptor( path = NormalizePath(path); - if (securityDescriptor is null) + if (securityDescriptor == null) { throw PSTraceSource.NewArgumentNullException(nameof(securityDescriptor)); } @@ -121,7 +121,7 @@ public void SetSecurityDescriptor( FileSystemSecurity sd = securityDescriptor as FileSystemSecurity; - if (sd is null) + if (sd == null) { throw PSTraceSource.NewArgumentException(nameof(securityDescriptor)); } diff --git a/src/System.Management.Automation/namespaces/FunctionProvider.cs b/src/System.Management.Automation/namespaces/FunctionProvider.cs index f042e973f0d..1843d1edff8 100644 --- a/src/System.Management.Automation/namespaces/FunctionProvider.cs +++ b/src/System.Management.Automation/namespaces/FunctionProvider.cs @@ -160,7 +160,7 @@ internal override void SetSessionStateItem(string name, object value, bool write bool dynamicParametersSpecified = dynamicParameters != null && dynamicParameters.OptionsSet; - if (value is null) + if (value == null) { // If the value wasn't specified but the options were, just set the // options on the existing function. diff --git a/src/System.Management.Automation/namespaces/LocationGlobber.cs b/src/System.Management.Automation/namespaces/LocationGlobber.cs index b238ed967aa..d5e60b652c9 100644 --- a/src/System.Management.Automation/namespaces/LocationGlobber.cs +++ b/src/System.Management.Automation/namespaces/LocationGlobber.cs @@ -56,7 +56,7 @@ internal sealed class LocationGlobber /// internal LocationGlobber(SessionState sessionState) { - if (sessionState is null) + if (sessionState == null) { throw PSTraceSource.NewArgumentNullException(nameof(sessionState)); } @@ -172,12 +172,12 @@ internal Collection GetGlobbedMonadPathsFromMonadPath( out CmdletProvider providerInstance) { providerInstance = null; - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } - if (context is null) + if (context == null) { throw PSTraceSource.NewArgumentNullException(nameof(context)); } @@ -226,8 +226,8 @@ internal Collection GetGlobbedMonadPathsFromMonadPath( if (!allowNonexistingPaths && result.Count < 1 && (!WildcardPattern.ContainsWildcardCharacters(path) || context.SuppressWildcardExpansion) && - (context.Include is null || context.Include.Count == 0) && - (context.Exclude is null || context.Exclude.Count == 0)) + (context.Include == null || context.Include.Count == 0) && + (context.Exclude == null || context.Exclude.Count == 0)) { // Since we are not globbing, throw an exception since // the path doesn't exist @@ -327,8 +327,8 @@ out CmdletProvider providerInstance if ((!allowNonexistingPaths) && stringResult.Count < 1 && !WildcardPattern.ContainsWildcardCharacters(providerPath) && - (context.Include is null || context.Include.Count == 0) && - (context.Exclude is null || context.Exclude.Count == 0)) + (context.Include == null || context.Include.Count == 0) && + (context.Exclude == null || context.Exclude.Count == 0)) { ItemNotFoundException pathNotFound = new ItemNotFoundException( @@ -542,8 +542,8 @@ private Collection ResolveDriveQualifiedPath( if ((!allowNonexistingPaths) && stringResult.Count < 1 && !WildcardPattern.ContainsWildcardCharacters(path) && - (context.Include is null || context.Include.Count == 0) && - (context.Exclude is null || context.Exclude.Count == 0)) + (context.Include == null || context.Include.Count == 0) && + (context.Exclude == null || context.Exclude.Count == 0)) { ItemNotFoundException pathNotFound = new ItemNotFoundException( @@ -661,7 +661,7 @@ internal Collection GetGlobbedProviderPathsFromMonadPath( out CmdletProvider providerInstance) { providerInstance = null; - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -736,12 +736,12 @@ internal Collection GetGlobbedProviderPathsFromMonadPath( out ProviderInfo provider, out CmdletProvider providerInstance) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } - if (context is null) + if (context == null) { throw PSTraceSource.NewArgumentNullException(nameof(context)); } @@ -759,7 +759,7 @@ internal Collection GetGlobbedProviderPathsFromMonadPath( PSDriveInfo drive = null; string providerPath = GetProviderPath(path, context, out provider, out drive); - if (providerPath is null) + if (providerPath == null) { providerInstance = null; s_tracer.WriteLine("provider returned a null path so return an empty array"); @@ -847,7 +847,7 @@ internal Collection GetGlobbedProviderPathsFromProviderPath( { providerInstance = null; - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -933,17 +933,17 @@ internal Collection GetGlobbedProviderPathsFromProviderPath( { providerInstance = null; - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } - if (providerId is null) + if (providerId == null) { throw PSTraceSource.NewArgumentNullException(nameof(providerId)); } - if (context is null) + if (context == null) { throw PSTraceSource.NewArgumentNullException(nameof(context)); } @@ -1055,7 +1055,7 @@ internal string GetProviderPath(string path) /// internal string GetProviderPath(string path, out ProviderInfo provider) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -1127,7 +1127,7 @@ internal string GetProviderPath(string path, out ProviderInfo provider) /// internal string GetProviderPath(string path, CmdletProviderContext context) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -1215,12 +1215,12 @@ internal string GetProviderPath( out ProviderInfo provider, out PSDriveInfo drive) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } - if (context is null) + if (context == null) { throw PSTraceSource.NewArgumentNullException(nameof(context)); } @@ -1372,7 +1372,7 @@ internal static bool IsProviderQualifiedPath(string path, out string providerId) { // Verify parameters - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -1470,7 +1470,7 @@ internal static bool IsAbsolutePath(string path) { // Verify parameters - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -1559,7 +1559,7 @@ internal bool IsAbsolutePath(string path, out string driveName) { // Verify parameters - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -1670,7 +1670,7 @@ internal bool IsAbsolutePath(string path, out string driveName) /// private static string RemoveGlobEscaping(string path) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -1712,7 +1712,7 @@ private static string RemoveGlobEscaping(string path) /// internal bool IsShellVirtualDrive(string driveName, out SessionStateScope scope) { - if (driveName is null) + if (driveName == null) { throw PSTraceSource.NewArgumentNullException(nameof(driveName)); } @@ -1815,7 +1815,7 @@ internal string GetDriveRootRelativePathFromPSPath( { // Verify parameters - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -1855,7 +1855,7 @@ internal string GetDriveRootRelativePathFromPSPath( // appears to be a drive (like HTTP://). The drive will not // actually exist, but this is not an absolute path. - if (_sessionState.Drive.Current is null) + if (_sessionState.Drive.Current == null) { throw; } @@ -1905,7 +1905,7 @@ internal string GetDriveRootRelativePathFromPSPath( workingDriveForPath = _sessionState.Drive.Current; } - if (workingDriveForPath is null) + if (workingDriveForPath == null) { ItemNotFoundException pathNotFound = new ItemNotFoundException( @@ -2044,12 +2044,12 @@ internal string GenerateRelativePath( { // Verify parameters - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } - if (drive is null) + if (drive == null) { throw PSTraceSource.NewArgumentNullException(nameof(drive)); } @@ -2317,12 +2317,12 @@ private string GetProviderSpecificPath( string workingPath, CmdletProviderContext context) { - if (drive is null) + if (drive == null) { throw PSTraceSource.NewArgumentNullException(nameof(drive)); } - if (workingPath is null) + if (workingPath == null) { throw PSTraceSource.NewArgumentNullException(nameof(workingPath)); } @@ -2376,7 +2376,7 @@ private string GetProviderSpecificPath( /// private static string ParseProviderPath(string path, out string providerId) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -2455,17 +2455,17 @@ internal Collection GetGlobbedProviderPathsFromProviderPath( ContainerCmdletProvider containerProvider, CmdletProviderContext context) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } - if (containerProvider is null) + if (containerProvider == null) { throw PSTraceSource.NewArgumentNullException(nameof(containerProvider)); } - if (context is null) + if (context == null) { throw PSTraceSource.NewArgumentNullException(nameof(context)); } @@ -2495,7 +2495,7 @@ internal Collection GetGlobbedProviderPathsFromProviderPath( /// internal static bool StringContainsGlobCharacters(string path) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -2632,17 +2632,17 @@ private Collection ExpandMshGlobPath( ContainerCmdletProvider provider, CmdletProviderContext context) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } - if (provider is null) + if (provider == null) { throw PSTraceSource.NewArgumentNullException(nameof(provider)); } - if (drive is null) + if (drive == null) { throw PSTraceSource.NewArgumentNullException(nameof(drive)); } @@ -2849,7 +2849,7 @@ private Collection ExpandMshGlobPath( s_pathResolutionTracer.WriteLine("{0} is not a container", dirs[index]); dirs.RemoveAt(index); } - else if (navigationProvider is null) + else if (navigationProvider == null) { Dbg.Diagnostics.Assert( navigationProvider != null, @@ -3057,12 +3057,12 @@ internal static string RemoveMshQualifier(string path, PSDriveInfo drive) /// internal static string GetDriveQualifiedPath(string path, PSDriveInfo drive) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } - if (drive is null) + if (drive == null) { throw PSTraceSource.NewArgumentNullException(nameof(drive)); } @@ -3200,12 +3200,12 @@ private static string RemoveDriveQualifier(string path) /// internal static string GetProviderQualifiedPath(string path, ProviderInfo provider) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } - if (provider is null) + if (provider == null) { throw PSTraceSource.NewArgumentNullException(nameof(provider)); } @@ -3340,12 +3340,12 @@ private List GenerateNewPSPathsWithGlobLeaf( ContainerCmdletProvider provider, CmdletProviderContext context) { - if (currentDirs is null) + if (currentDirs == null) { throw PSTraceSource.NewArgumentNullException(nameof(currentDirs)); } - if (provider is null) + if (provider == null) { throw PSTraceSource.NewArgumentNullException(nameof(provider)); } @@ -3409,7 +3409,7 @@ private List GenerateNewPSPathsWithGlobLeaf( provider, out mshQualifiedParentPath); - if (childNamesObjectArray is null) + if (childNamesObjectArray == null) { s_tracer.TraceError("GetChildNames returned a null array"); s_pathResolutionTracer.WriteLine("No child names returned for '{0}'", dir); @@ -3574,12 +3574,12 @@ internal Collection ExpandGlobPath( ContainerCmdletProvider provider, CmdletProviderContext context) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } - if (provider is null) + if (provider == null) { throw PSTraceSource.NewArgumentNullException(nameof(provider)); } @@ -3814,7 +3814,7 @@ internal Collection ExpandGlobPath( s_pathResolutionTracer.WriteLine("{0} is not a container", dirs[index]); dirs.RemoveAt(index); } - else if (navigationProvider is null) + else if (navigationProvider == null) { Dbg.Diagnostics.Assert( navigationProvider != null, @@ -3946,12 +3946,12 @@ internal List GenerateNewPathsWithGlobLeaf( ContainerCmdletProvider provider, CmdletProviderContext context) { - if (currentDirs is null) + if (currentDirs == null) { throw PSTraceSource.NewArgumentNullException(nameof(currentDirs)); } - if (provider is null) + if (provider == null) { throw PSTraceSource.NewArgumentNullException(nameof(provider)); } @@ -4006,7 +4006,7 @@ internal List GenerateNewPathsWithGlobLeaf( Collection childNamesObjectArray = GetChildNamesInDir(dir, leafElement, !isLastLeaf, context, true, null, provider, out unescapedDir); - if (childNamesObjectArray is null) + if (childNamesObjectArray == null) { s_tracer.TraceError("GetChildNames returned a null array"); @@ -4347,7 +4347,7 @@ private static bool IsChildNameAMatch( childName = baseObject as string; - if (childName is null) + if (childName == null) { s_tracer.TraceError("GetChildNames returned an object that wasn't a string"); break; @@ -4427,7 +4427,7 @@ private static bool IsChildNameAMatch( /// private static string ConvertMshEscapeToRegexEscape(string path) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -4517,7 +4517,7 @@ private static string ConvertMshEscapeToRegexEscape(string path) /// internal static bool IsHomePath(string path) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -4566,7 +4566,7 @@ internal static bool IsHomePath(string path) /// internal static bool IsProviderDirectPath(string path) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -4606,7 +4606,7 @@ internal static bool IsProviderDirectPath(string path) /// internal string GetHomeRelativePath(string path) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } diff --git a/src/System.Management.Automation/namespaces/NavigationProviderBase.cs b/src/System.Management.Automation/namespaces/NavigationProviderBase.cs index 62ce17619e5..42dd3b32b36 100644 --- a/src/System.Management.Automation/namespaces/NavigationProviderBase.cs +++ b/src/System.Management.Automation/namespaces/NavigationProviderBase.cs @@ -315,8 +315,8 @@ protected string MakePath(string parent, string child, bool childIsLeaf) { string result = null; - if (parent is null && - child is null) + if (parent == null && + child == null) { throw PSTraceSource.NewArgumentException(nameof(parent)); } @@ -410,7 +410,7 @@ protected virtual string GetParentPath(string path, string root) throw PSTraceSource.NewArgumentException(nameof(path)); } - if (root is null) + if (root == null) { if (PSDriveInfo != null) { @@ -506,7 +506,7 @@ internal string ContractRelativePath( { Context = context; - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -516,7 +516,7 @@ internal string ContractRelativePath( return string.Empty; } - if (basePath is null) + if (basePath == null) { basePath = string.Empty; } diff --git a/src/System.Management.Automation/namespaces/PathInfo.cs b/src/System.Management.Automation/namespaces/PathInfo.cs index 4e8720253ed..cd91845f84c 100644 --- a/src/System.Management.Automation/namespaces/PathInfo.cs +++ b/src/System.Management.Automation/namespaces/PathInfo.cs @@ -65,7 +65,7 @@ public string ProviderPath { get { - if (_providerPath is null) + if (_providerPath == null) { // Construct the providerPath @@ -105,7 +105,7 @@ public override string ToString() { string result = _path; - if (_drive is null || + if (_drive == null || _drive.Hidden) { // For hidden drives just return the current location @@ -143,17 +143,17 @@ public override string ToString() /// internal PathInfo(PSDriveInfo drive, ProviderInfo provider, string path, SessionState sessionState) { - if (provider is null) + if (provider == null) { throw PSTraceSource.NewArgumentNullException(nameof(provider)); } - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } - if (sessionState is null) + if (sessionState == null) { throw PSTraceSource.NewArgumentNullException(nameof(sessionState)); } diff --git a/src/System.Management.Automation/namespaces/ProviderBase.cs b/src/System.Management.Automation/namespaces/ProviderBase.cs index 47cf392f4f8..326d4d51b04 100644 --- a/src/System.Management.Automation/namespaces/ProviderBase.cs +++ b/src/System.Management.Automation/namespaces/ProviderBase.cs @@ -96,7 +96,7 @@ public abstract partial class CmdletProvider : IResourceSupplier /// internal void SetProviderInformation(ProviderInfo providerInfoToSet) { - if (providerInfoToSet is null) + if (providerInfoToSet == null) { throw PSTraceSource.NewArgumentNullException(nameof(providerInfoToSet)); } @@ -136,7 +136,7 @@ internal CmdletProviderContext Context set { - if (value is null) + if (value == null) { throw PSTraceSource.NewArgumentNullException("value"); } @@ -261,7 +261,7 @@ internal void GetProperty( IPropertyCmdletProvider propertyProvider = this as IPropertyCmdletProvider; - if (propertyProvider is null) + if (propertyProvider == null) { throw PSTraceSource.NewNotSupportedException( @@ -301,7 +301,7 @@ internal object GetPropertyDynamicParameters( IPropertyCmdletProvider propertyProvider = this as IPropertyCmdletProvider; - if (propertyProvider is null) + if (propertyProvider == null) { return null; } @@ -332,7 +332,7 @@ internal void SetProperty( IPropertyCmdletProvider propertyProvider = this as IPropertyCmdletProvider; - if (propertyProvider is null) + if (propertyProvider == null) { throw PSTraceSource.NewNotSupportedException( @@ -372,7 +372,7 @@ internal object SetPropertyDynamicParameters( IPropertyCmdletProvider propertyProvider = this as IPropertyCmdletProvider; - if (propertyProvider is null) + if (propertyProvider == null) { return null; } @@ -406,7 +406,7 @@ internal void ClearProperty( IPropertyCmdletProvider propertyProvider = this as IPropertyCmdletProvider; - if (propertyProvider is null) + if (propertyProvider == null) { throw PSTraceSource.NewNotSupportedException( @@ -446,7 +446,7 @@ internal object ClearPropertyDynamicParameters( IPropertyCmdletProvider propertyProvider = this as IPropertyCmdletProvider; - if (propertyProvider is null) + if (propertyProvider == null) { return null; } @@ -492,7 +492,7 @@ internal void NewProperty( IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider; - if (propertyProvider is null) + if (propertyProvider == null) { throw PSTraceSource.NewNotSupportedException( @@ -539,7 +539,7 @@ internal object NewPropertyDynamicParameters( IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider; - if (propertyProvider is null) + if (propertyProvider == null) { return null; } @@ -573,7 +573,7 @@ internal void RemoveProperty( IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider; - if (propertyProvider is null) + if (propertyProvider == null) { throw PSTraceSource.NewNotSupportedException( @@ -612,7 +612,7 @@ internal object RemovePropertyDynamicParameters( IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider; - if (propertyProvider is null) + if (propertyProvider == null) { return null; } @@ -650,7 +650,7 @@ internal void RenameProperty( IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider; - if (propertyProvider is null) + if (propertyProvider == null) { throw PSTraceSource.NewNotSupportedException( @@ -693,7 +693,7 @@ internal object RenamePropertyDynamicParameters( IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider; - if (propertyProvider is null) + if (propertyProvider == null) { return null; } @@ -735,7 +735,7 @@ internal void CopyProperty( IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider; - if (propertyProvider is null) + if (propertyProvider == null) { throw PSTraceSource.NewNotSupportedException( @@ -782,7 +782,7 @@ internal object CopyPropertyDynamicParameters( IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider; - if (propertyProvider is null) + if (propertyProvider == null) { return null; } @@ -824,7 +824,7 @@ internal void MoveProperty( IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider; - if (propertyProvider is null) + if (propertyProvider == null) { throw PSTraceSource.NewNotSupportedException( @@ -871,7 +871,7 @@ internal object MovePropertyDynamicParameters( IDynamicPropertyCmdletProvider propertyProvider = this as IDynamicPropertyCmdletProvider; - if (propertyProvider is null) + if (propertyProvider == null) { return null; } @@ -904,7 +904,7 @@ internal IContentReader GetContentReader( IContentCmdletProvider contentProvider = this as IContentCmdletProvider; - if (contentProvider is null) + if (contentProvider == null) { throw PSTraceSource.NewNotSupportedException( @@ -939,7 +939,7 @@ internal object GetContentReaderDynamicParameters( IContentCmdletProvider contentProvider = this as IContentCmdletProvider; - if (contentProvider is null) + if (contentProvider == null) { return null; } @@ -968,7 +968,7 @@ internal IContentWriter GetContentWriter( IContentCmdletProvider contentProvider = this as IContentCmdletProvider; - if (contentProvider is null) + if (contentProvider == null) { throw PSTraceSource.NewNotSupportedException( @@ -1003,7 +1003,7 @@ internal object GetContentWriterDynamicParameters( IContentCmdletProvider contentProvider = this as IContentCmdletProvider; - if (contentProvider is null) + if (contentProvider == null) { return null; } @@ -1029,7 +1029,7 @@ internal void ClearContent( IContentCmdletProvider contentProvider = this as IContentCmdletProvider; - if (contentProvider is null) + if (contentProvider == null) { throw PSTraceSource.NewNotSupportedException( @@ -1064,7 +1064,7 @@ internal object ClearContentDynamicParameters( IContentCmdletProvider contentProvider = this as IContentCmdletProvider; - if (contentProvider is null) + if (contentProvider == null) { return null; } @@ -1450,7 +1450,7 @@ public virtual string GetResourceString(string baseName, string resourceId) throw PSTraceSource.NewArgumentException(nameof(baseName), GetErrorText.ResourceBaseNameFailure, baseName); } - if (retValue is null) + if (retValue == null) { throw PSTraceSource.NewArgumentException(nameof(resourceId), GetErrorText.ResourceIdFailure, resourceId); } @@ -1466,7 +1466,7 @@ public void ThrowTerminatingError(ErrorRecord errorRecord) { using (PSTransactionManager.GetEngineProtectionScope()) { - if (errorRecord is null) + if (errorRecord == null) { throw PSTraceSource.NewArgumentNullException(nameof(errorRecord)); } @@ -1617,7 +1617,7 @@ public bool TransactionAvailable() { using (PSTransactionManager.GetEngineProtectionScope()) { - if (Context is null) + if (Context == null) return false; else return Context.TransactionAvailable(); @@ -1632,7 +1632,7 @@ public PSTransactionContext CurrentPSTransaction { get { - if (Context is null) + if (Context == null) return null; else return Context.CurrentPSTransaction; @@ -1675,7 +1675,7 @@ public void WriteProgress(ProgressRecord progressRecord) Context != null, "The context should always be set"); - if (progressRecord is null) + if (progressRecord == null) { throw PSTraceSource.NewArgumentNullException(nameof(progressRecord)); } @@ -1799,7 +1799,7 @@ private PSObject WrapOutputInPSObject( object item, string path) { - if (item is null) + if (item == null) { throw PSTraceSource.NewArgumentNullException(nameof(item)); } @@ -1998,7 +1998,7 @@ public void WriteError(ErrorRecord errorRecord) Context != null, "The context should always be set"); - if (errorRecord is null) + if (errorRecord == null) { throw PSTraceSource.NewArgumentNullException(nameof(errorRecord)); } diff --git a/src/System.Management.Automation/namespaces/ProviderBaseSecurity.cs b/src/System.Management.Automation/namespaces/ProviderBaseSecurity.cs index efed102d0e6..c232b769fb3 100644 --- a/src/System.Management.Automation/namespaces/ProviderBaseSecurity.cs +++ b/src/System.Management.Automation/namespaces/ProviderBaseSecurity.cs @@ -87,7 +87,7 @@ internal void SetSecurityDescriptor( private static void CheckIfSecurityDescriptorInterfaceIsSupported(ISecurityDescriptorCmdletProvider permissionProvider) { - if (permissionProvider is null) + if (permissionProvider == null) { throw PSTraceSource.NewNotSupportedException( diff --git a/src/System.Management.Automation/namespaces/RegistryProvider.cs b/src/System.Management.Automation/namespaces/RegistryProvider.cs index df66402197d..cb2963f40c7 100644 --- a/src/System.Management.Automation/namespaces/RegistryProvider.cs +++ b/src/System.Management.Automation/namespaces/RegistryProvider.cs @@ -110,7 +110,7 @@ public sealed partial class RegistryProvider : /// --> protected override PSDriveInfo NewDrive(PSDriveInfo drive) { - if (drive is null) + if (drive == null) { throw PSTraceSource.NewArgumentNullException(nameof(drive)); } @@ -202,7 +202,7 @@ protected override bool IsValidPath(string path) break; } - if (GetHiveRoot(root) is null) + if (GetHiveRoot(root) == null) { result = false; } @@ -225,7 +225,7 @@ protected override void GetItem(string path) IRegistryWrapper result = GetRegkeyForPathWriteIfError(path, false); - if (result is null) + if (result == null) { return; } @@ -271,7 +271,7 @@ protected override void SetItem(string path, object value) IRegistryWrapper key = GetRegkeyForPathWriteIfError(path, true); - if (key is null) + if (key == null) { return; } @@ -434,7 +434,7 @@ protected override void ClearItem(string path) IRegistryWrapper key = GetRegkeyForPathWriteIfError(path, true); - if (key is null) + if (key == null) { return; } @@ -531,7 +531,7 @@ protected override void GetChildItems( { s_tracer.WriteLine("recurse = {0}, depth = {1}", recurse, depth); - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -557,7 +557,7 @@ protected override void GetChildItems( IRegistryWrapper key = GetRegkeyForPathWriteIfError(path, false); - if (key is null) + if (key == null) { return; } @@ -678,7 +678,7 @@ protected override void GetChildNames( string path, ReturnContainers returnContainers) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -704,7 +704,7 @@ protected override void GetChildNames( IRegistryWrapper key = GetRegkeyForPathWriteIfError(path, false); - if (key is null) + if (key == null) { return; } @@ -999,7 +999,7 @@ protected override void NewItem( // Get the key at the specified path IRegistryWrapper key = GetRegkeyForPathWriteIfError(parentPath, true); - if (key is null) + if (key == null) { return; } @@ -1114,7 +1114,7 @@ protected override void RemoveItem( IRegistryWrapper key = GetRegkeyForPathWriteIfError(parentPath, true); - if (key is null) + if (key == null) { return; } @@ -1184,7 +1184,7 @@ protected override bool ItemExists(string path) { bool result = false; - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -1238,7 +1238,7 @@ protected override bool HasChildItems(string path) { bool result = false; - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -1311,7 +1311,7 @@ protected override void CopyItem( IRegistryWrapper key = GetRegkeyForPathWriteIfError(path, false); - if (key is null) + if (key == null) { return; } @@ -1389,7 +1389,7 @@ private bool CopyRegistryKey( string destinationName = GetChildName(path); string destinationParent = destination; - if (newParentKey is null) + if (newParentKey == null) { destinationParent = GetParentPath(destination, null); destinationName = GetChildName(destination); @@ -1397,7 +1397,7 @@ private bool CopyRegistryKey( newParentKey = GetRegkeyForPathWriteIfError(destinationParent, true); } - if (newParentKey is null) + if (newParentKey == null) { // The key was not found. // An error should have been written by GetRegkeyForPathWriteIfError @@ -1584,7 +1584,7 @@ private bool ErrorIfDestinationIsSourceOrChildOfSource( /// protected override bool IsItemContainer(string path) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -1678,7 +1678,7 @@ private void MoveRegistryItem(string path, string destination) IRegistryWrapper key = GetRegkeyForPathWriteIfError(path, false); - if (key is null) + if (key == null) { return; } @@ -1783,7 +1783,7 @@ public void GetProperty( string path, Collection providerSpecificPickList) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -1802,7 +1802,7 @@ public void GetProperty( false, out key, out filteredPropertyCollection); - if (key is null) + if (key == null) { return; } @@ -1851,7 +1851,7 @@ public void SetProperty( string path, PSObject propertyValue) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -1861,14 +1861,14 @@ public void SetProperty( return; } - if (propertyValue is null) + if (propertyValue == null) { throw PSTraceSource.NewArgumentNullException(nameof(propertyValue)); } IRegistryWrapper key = GetRegkeyForPathWriteIfError(path, true); - if (key is null) + if (key == null) { return; } @@ -1976,7 +1976,7 @@ public void ClearProperty( string path, Collection propertyToClear) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -1995,7 +1995,7 @@ public void ClearProperty( true, out key, out filteredPropertyCollection); - if (key is null) + if (key == null) { return; } @@ -2120,7 +2120,7 @@ public void NewProperty( string type, object value) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -2132,7 +2132,7 @@ public void NewProperty( IRegistryWrapper key = GetRegkeyForPathWriteIfError(path, true); - if (key is null) + if (key == null) { return; } @@ -2164,7 +2164,7 @@ public void NewProperty( { // Check to see if the property already exists // or overwrite if frce is on - if (Force || key.GetValue(propertyName) is null) + if (Force || key.GetValue(propertyName) == null) { // Create the value SetRegistryValue(key, propertyName, value, kind, path); @@ -2232,7 +2232,7 @@ public void RemoveProperty( string path, string propertyName) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -2244,7 +2244,7 @@ public void RemoveProperty( IRegistryWrapper key = GetRegkeyForPathWriteIfError(path, true); - if (key is null) + if (key == null) { return; } @@ -2335,7 +2335,7 @@ public void RenameProperty( string sourceProperty, string destinationProperty) { - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -2347,7 +2347,7 @@ public void RenameProperty( IRegistryWrapper key = GetRegkeyForPathWriteIfError(path, true); - if (key is null) + if (key == null) { return; } @@ -2424,12 +2424,12 @@ public void CopyProperty( string destinationPath, string destinationProperty) { - if (sourcePath is null) + if (sourcePath == null) { throw PSTraceSource.NewArgumentNullException(nameof(sourcePath)); } - if (destinationPath is null) + if (destinationPath == null) { throw PSTraceSource.NewArgumentNullException(nameof(destinationPath)); } @@ -2441,13 +2441,13 @@ public void CopyProperty( IRegistryWrapper key = GetRegkeyForPathWriteIfError(sourcePath, false); - if (key is null) + if (key == null) { return; } IRegistryWrapper destinationKey = GetRegkeyForPathWriteIfError(destinationPath, true); - if (destinationKey is null) + if (destinationKey == null) { return; } @@ -2524,12 +2524,12 @@ public void MoveProperty( string destinationPath, string destinationProperty) { - if (sourcePath is null) + if (sourcePath == null) { throw PSTraceSource.NewArgumentNullException(nameof(sourcePath)); } - if (destinationPath is null) + if (destinationPath == null) { throw PSTraceSource.NewArgumentNullException(nameof(destinationPath)); } @@ -2541,13 +2541,13 @@ public void MoveProperty( IRegistryWrapper key = GetRegkeyForPathWriteIfError(sourcePath, true); - if (key is null) + if (key == null) { return; } IRegistryWrapper destinationKey = GetRegkeyForPathWriteIfError(destinationPath, true); - if (destinationKey is null) + if (destinationKey == null) { return; } @@ -2985,14 +2985,14 @@ private void GetFilteredRegistryKeyProperties(string path, filteredCollection = new Collection(); key = GetRegkeyForPathWriteIfError(path, writeAccess); - if (key is null) + if (key == null) { return; } // If properties were not specified, get all the values - if (propertyNames is null) + if (propertyNames == null) { propertyNames = new Collection(); } @@ -3197,7 +3197,7 @@ private object ResetRegistryKeyValue(IRegistryWrapper key, string valueName) private bool IsHiveContainer(string path) { bool result = false; - if (path is null) + if (path == null) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } @@ -3357,7 +3357,7 @@ private bool CreateIntermediateKeys(string path) IRegistryWrapper rootKey = GetHiveRoot(keyRoot); - if (remainingPath.Length == 0 || rootKey is null) + if (remainingPath.Length == 0 || rootKey == null) { throw PSTraceSource.NewArgumentException(nameof(path)); } @@ -3439,7 +3439,7 @@ private IRegistryWrapper GetRegkeyForPathWriteIfError(string path, bool writeAcc { result = GetRegkeyForPath(path, writeAccess); - if (result is null) + if (result == null) { // The key was not found, write out an error. @@ -3543,7 +3543,7 @@ private IRegistryWrapper GetRegkeyForPath(string path, bool writeAccess) IRegistryWrapper resultRoot = GetHiveRoot(keyRoot); - if (remainingPath.Length == 0 || resultRoot is null) + if (remainingPath.Length == 0 || resultRoot == null) { result = resultRoot; break; @@ -3559,7 +3559,7 @@ private IRegistryWrapper GetRegkeyForPath(string path, bool writeAccess) } // If we could not open the key, see if we can find the subkey that matches. - if (result is null) + if (result == null) { IRegistryWrapper currentKey = resultRoot; IRegistryWrapper tempKey = null; @@ -3894,7 +3894,7 @@ private static object ConvertValueToKind(object value, RegistryValueKind kind) /// Corresponding RegistryValueKind. private static RegistryValueKind GetValueKindFromObject(object value) { - if (value is null) + if (value == null) { throw PSTraceSource.NewArgumentNullException(nameof(value)); } @@ -4004,7 +4004,7 @@ private void WriteRegistryItemObject( IRegistryWrapper key, string path) { - if (key is null) + if (key == null) { Dbg.Diagnostics.Assert( key != null, diff --git a/src/System.Management.Automation/namespaces/RegistrySecurity.cs b/src/System.Management.Automation/namespaces/RegistrySecurity.cs index bf878bd595d..04f25d7f06f 100644 --- a/src/System.Management.Automation/namespaces/RegistrySecurity.cs +++ b/src/System.Management.Automation/namespaces/RegistrySecurity.cs @@ -96,7 +96,7 @@ public void SetSecurityDescriptor( throw PSTraceSource.NewArgumentException(nameof(path)); } - if (securityDescriptor is null) + if (securityDescriptor == null) { throw PSTraceSource.NewArgumentNullException(nameof(securityDescriptor)); } @@ -108,7 +108,7 @@ public void SetSecurityDescriptor( { sd = securityDescriptor as TransactedRegistrySecurity; - if (sd is null) + if (sd == null) { throw PSTraceSource.NewArgumentException(nameof(securityDescriptor)); } @@ -117,7 +117,7 @@ public void SetSecurityDescriptor( { sd = securityDescriptor as RegistrySecurity; - if (sd is null) + if (sd == null) { throw PSTraceSource.NewArgumentException(nameof(securityDescriptor)); } diff --git a/src/System.Management.Automation/namespaces/RegistryWrapper.cs b/src/System.Management.Automation/namespaces/RegistryWrapper.cs index 8999cff37d0..6f0c3e3d66f 100644 --- a/src/System.Management.Automation/namespaces/RegistryWrapper.cs +++ b/src/System.Management.Automation/namespaces/RegistryWrapper.cs @@ -154,7 +154,7 @@ public string[] GetSubKeyNames() public IRegistryWrapper CreateSubKey(string subkey) { RegistryKey newKey = _regKey.CreateSubKey(subkey); - if (newKey is null) + if (newKey == null) return null; else return new RegistryWrapper(newKey); @@ -163,7 +163,7 @@ public IRegistryWrapper CreateSubKey(string subkey) public IRegistryWrapper OpenSubKey(string name, bool writable) { RegistryKey newKey = _regKey.OpenSubKey(name, writable); - if (newKey is null) + if (newKey == null) return null; else return new RegistryWrapper(newKey); @@ -305,7 +305,7 @@ public IRegistryWrapper CreateSubKey(string subkey) using (_provider.CurrentPSTransaction) { TransactedRegistryKey newKey = _txRegKey.CreateSubKey(subkey); - if (newKey is null) + if (newKey == null) return null; else return new TransactedRegistryWrapper(newKey, _provider); @@ -317,7 +317,7 @@ public IRegistryWrapper OpenSubKey(string name, bool writable) using (_provider.CurrentPSTransaction) { TransactedRegistryKey newKey = _txRegKey.OpenSubKey(name, writable); - if (newKey is null) + if (newKey == null) return null; else return new TransactedRegistryWrapper(newKey, _provider); diff --git a/src/System.Management.Automation/namespaces/SessionStateProviderBase.cs b/src/System.Management.Automation/namespaces/SessionStateProviderBase.cs index 198f53e2631..33b043ce919 100644 --- a/src/System.Management.Automation/namespaces/SessionStateProviderBase.cs +++ b/src/System.Management.Automation/namespaces/SessionStateProviderBase.cs @@ -691,7 +691,7 @@ protected override void NewItem(string path, string type, object newItem) return; } - if (newItem is null) + if (newItem == null) { ArgumentNullException argException = PSTraceSource.NewArgumentNullException("value"); @@ -1107,7 +1107,7 @@ internal SessionStateProviderBaseContentReaderWriter(string path, SessionStatePr throw PSTraceSource.NewArgumentException(nameof(path)); } - if (provider is null) + if (provider == null) { throw PSTraceSource.NewArgumentNullException(nameof(provider)); } @@ -1173,7 +1173,7 @@ public IList Read(long readCount) /// public IList Write(IList content) { - if (content is null) + if (content == null) { throw PSTraceSource.NewArgumentNullException(nameof(content)); } diff --git a/src/System.Management.Automation/namespaces/StackInfo.cs b/src/System.Management.Automation/namespaces/StackInfo.cs index 1611cda627e..887285c37fe 100644 --- a/src/System.Management.Automation/namespaces/StackInfo.cs +++ b/src/System.Management.Automation/namespaces/StackInfo.cs @@ -27,7 +27,7 @@ public sealed class PathInfoStack : Stack /// internal PathInfoStack(string stackName, Stack locationStack) : base() { - if (locationStack is null) + if (locationStack == null) { throw PSTraceSource.NewArgumentNullException(nameof(locationStack)); } diff --git a/src/System.Management.Automation/namespaces/VariableProvider.cs b/src/System.Management.Automation/namespaces/VariableProvider.cs index 705e1b65edd..5da5351ebad 100644 --- a/src/System.Management.Automation/namespaces/VariableProvider.cs +++ b/src/System.Management.Automation/namespaces/VariableProvider.cs @@ -111,7 +111,7 @@ internal override void SetSessionStateItem(string name, object value, bool write if (value != null) { variable = value as PSVariable; - if (variable is null) + if (variable == null) { variable = new PSVariable(name, value); } diff --git a/src/System.Management.Automation/security/Authenticode.cs b/src/System.Management.Automation/security/Authenticode.cs index 524399b7aa6..cf5e559f830 100644 --- a/src/System.Management.Automation/security/Authenticode.cs +++ b/src/System.Management.Automation/security/Authenticode.cs @@ -273,7 +273,7 @@ internal static Signature GetSignature(string fileName, string fileContent) { Signature signature = null; - if (fileContent is null) + if (fileContent == null) { // First, try to get the signature from the catalog signature APIs. signature = GetSignatureFromCatalog(fileName); @@ -281,7 +281,7 @@ internal static Signature GetSignature(string fileName, string fileContent) // If there is no signature or it is invalid, go by the file content // with the older WinVerifyTrust APIs - if ((signature is null) || (signature.Status != SignatureStatus.Valid)) + if ((signature == null) || (signature.Status != SignatureStatus.Valid)) { signature = GetSignatureFromWinVerifyTrust(fileName, fileContent); } @@ -438,7 +438,7 @@ private static Signature GetSignatureFromWinVerifyTrust(string fileName, string NativeMethods.WINTRUST_DATA wtd; DWORD error = Win32Errors.E_FAIL; - if (fileContent is null) + if (fileContent == null) { Utils.CheckArgForNullOrEmpty(fileName, "fileName"); SecuritySupport.CheckIfFileExists(fileName); @@ -492,7 +492,7 @@ private static DWORD GetWinTrustData(string fileName, string fileContent, NativeMethods.WINTRUST_DATA wtd; - if (fileContent is null) + if (fileContent == null) { NativeMethods.WINTRUST_FILE_INFO wfi = NativeMethods.InitWintrustFileInfoStruct(fileName); wtd = NativeMethods.InitWintrustDataStructFromFile(wfi); @@ -589,7 +589,7 @@ private static Signature GetSignatureFromWintrustData( Diagnostics.Assert(error != 0 || signature != null, "GetSignatureFromWintrustData: general crypto failure"); - if ((signature is null) && (error != 0)) + if ((signature == null) && (error != 0)) { signature = new Signature(filePath, error); } diff --git a/src/System.Management.Automation/security/CredentialParameter.cs b/src/System.Management.Automation/security/CredentialParameter.cs index 4524428074e..ad9463b9df2 100644 --- a/src/System.Management.Automation/security/CredentialParameter.cs +++ b/src/System.Management.Automation/security/CredentialParameter.cs @@ -34,14 +34,14 @@ public override object Transform(EngineIntrinsics engineIntrinsics, object input bool shouldPrompt = false; bool confirmPassword = false; - if ((engineIntrinsics is null) || - (engineIntrinsics.Host is null) || - (engineIntrinsics.Host.UI is null)) + if ((engineIntrinsics == null) || + (engineIntrinsics.Host == null) || + (engineIntrinsics.Host.UI == null)) { throw PSTraceSource.NewArgumentNullException(nameof(engineIntrinsics)); } - if (inputData is null) + if (inputData == null) { shouldPrompt = true; } @@ -51,14 +51,14 @@ public override object Transform(EngineIntrinsics engineIntrinsics, object input cred = LanguagePrimitives.FromObjectAs(inputData); // Try to coerce the username from the string - if (cred is null) + if (cred == null) { shouldPrompt = true; userName = LanguagePrimitives.FromObjectAs(inputData); // If we couldn't get the username (as a string,) // throw an exception - if (userName is null) + if (userName == null) { throw new PSArgumentException("userName"); } diff --git a/src/System.Management.Automation/security/MshSignature.cs b/src/System.Management.Automation/security/MshSignature.cs index 00fbfbf33c9..df20f7d0e63 100644 --- a/src/System.Management.Automation/security/MshSignature.cs +++ b/src/System.Management.Automation/security/MshSignature.cs @@ -376,9 +376,9 @@ private static string GetSignatureStatusMessage(SignatureStatus status, break; } - if (message is null) + if (message == null) { - if (arg is null) + if (arg == null) { message = resourceString; } diff --git a/src/System.Management.Automation/security/SecureStringHelper.cs b/src/System.Management.Automation/security/SecureStringHelper.cs index ad5646d59cf..e6180dc39b7 100644 --- a/src/System.Management.Automation/security/SecureStringHelper.cs +++ b/src/System.Management.Automation/security/SecureStringHelper.cs @@ -263,7 +263,7 @@ internal static EncryptionResult Encrypt(SecureString input, byte[] key, byte[] // randomized by default. // Aes aes = Aes.Create(); - if (iv is null) + if (iv == null) iv = aes.IV; encryptor = aes.CreateEncryptor(key, iv); @@ -430,7 +430,7 @@ internal static class ProtectedData /// public static byte[] Protect(byte[] userData, byte[] optionalEntropy, DataProtectionScope scope) { - if (userData is null) + if (userData == null) { throw new ArgumentNullException(nameof(userData)); } @@ -518,7 +518,7 @@ public static byte[] Protect(byte[] userData, byte[] optionalEntropy, DataProtec /// public static byte[] Unprotect(byte[] encryptedData, byte[] optionalEntropy, DataProtectionScope scope) { - if (encryptedData is null) + if (encryptedData == null) { throw new ArgumentNullException(nameof(encryptedData)); } diff --git a/src/System.Management.Automation/security/SecurityManager.cs b/src/System.Management.Automation/security/SecurityManager.cs index d2a6e621460..f6ae0fdf1f3 100644 --- a/src/System.Management.Automation/security/SecurityManager.cs +++ b/src/System.Management.Automation/security/SecurityManager.cs @@ -611,7 +611,7 @@ protected internal override bool ShouldRun(CommandInfo commandInfo, case CommandTypes.ExternalScript: ExternalScriptInfo si = commandInfo as ExternalScriptInfo; - if (si is null) + if (si == null) { reason = PSTraceSource.NewArgumentException("scriptInfo"); } @@ -640,14 +640,14 @@ private RunPromptDecision AuthenticodePrompt(string path, Signature signature, PSHost host) { - if ((host is null) || (host.UI is null)) + if ((host == null) || (host.UI == null)) { return RunPromptDecision.DoNotRun; } RunPromptDecision decision = RunPromptDecision.DoNotRun; - if (signature is null) + if (signature == null) { return decision; } @@ -673,7 +673,7 @@ private RunPromptDecision AuthenticodePrompt(string path, string promptText; - if (signature.SignerCertificate is null) + if (signature.SignerCertificate == null) { promptText = StringUtil.Format(Authenticode.AuthenticodePromptText_UnknownPublisher, @@ -711,7 +711,7 @@ private RunPromptDecision AuthenticodePrompt(string path, private RunPromptDecision RemoteFilePrompt(string path, PSHost host) { - if ((host is null) || (host.UI is null)) + if ((host == null) || (host.UI == null)) { return RunPromptDecision.DoNotRun; } diff --git a/src/System.Management.Automation/security/SecuritySupport.cs b/src/System.Management.Automation/security/SecuritySupport.cs index 40b8770b456..90d4a71d73b 100644 --- a/src/System.Management.Automation/security/SecuritySupport.cs +++ b/src/System.Management.Automation/security/SecuritySupport.cs @@ -868,7 +868,7 @@ internal static string Encrypt(byte[] contentBytes, CmsMessageRecipient[] recipi { error = null; - if ((contentBytes is null) || (contentBytes.Length == 0)) + if ((contentBytes == null) || (contentBytes.Length == 0)) { return string.Empty; } @@ -1099,7 +1099,7 @@ private void ResolveFromBase64Encoding(ResolutionPurpose purpose, out ErrorRecor } // Didn't have the sigil - if (messageBytes is null) + if (messageBytes == null) { return; } diff --git a/src/System.Management.Automation/security/wldpNativeMethods.cs b/src/System.Management.Automation/security/wldpNativeMethods.cs index d89f140e837..608503b932f 100644 --- a/src/System.Management.Automation/security/wldpNativeMethods.cs +++ b/src/System.Management.Automation/security/wldpNativeMethods.cs @@ -48,11 +48,11 @@ private SystemPolicy() /// An EnforcementMode that describes the system policy. public static SystemEnforcementMode GetSystemLockdownPolicy() { - if (s_allowDebugOverridePolicy || (s_systemLockdownPolicy is null)) + if (s_allowDebugOverridePolicy || (s_systemLockdownPolicy == null)) { lock (s_systemLockdownPolicyLock) { - if (s_allowDebugOverridePolicy || (s_systemLockdownPolicy is null)) + if (s_allowDebugOverridePolicy || (s_systemLockdownPolicy == null)) { s_systemLockdownPolicy = GetLockdownPolicy(null, null); } diff --git a/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs b/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs index 9a0a433e278..33ef4a0cb9d 100644 --- a/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs +++ b/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs @@ -108,32 +108,32 @@ string vendorFallback throw PSTraceSource.NewArgumentNullException(nameof(moduleName)); } - if (psVersion is null) + if (psVersion == null) { throw PSTraceSource.NewArgumentNullException(nameof(psVersion)); } - if (version is null) + if (version == null) { version = new Version("0.0"); } - if (types is null) + if (types == null) { types = new Collection(); } - if (formats is null) + if (formats == null) { formats = new Collection(); } - if (descriptionFallback is null) + if (descriptionFallback == null) { descriptionFallback = string.Empty; } - if (vendorFallback is null) + if (vendorFallback == null) { vendorFallback = string.Empty; } @@ -272,7 +272,7 @@ public string Description { get { - if (_description is null) + if (_description == null) { LoadIndirectResources(); } @@ -291,7 +291,7 @@ public string Vendor { get { - if (_vendor is null) + if (_vendor == null) { LoadIndirectResources(); } @@ -480,7 +480,7 @@ internal static Collection ReadAll() RegistryKey monadRootKey = GetMonadRootKey(); string[] versions = monadRootKey.GetSubKeyNames(); - if (versions is null) + if (versions == null) { return allMshSnapins; } @@ -695,7 +695,7 @@ private static PSSnapInInfo ReadOne(RegistryKey mshSnapInRoot, string mshsnapinI RegistryKey mshsnapinKey; mshsnapinKey = mshSnapInRoot.OpenSubKey(mshsnapinId); - if (mshsnapinKey is null) + if (mshsnapinKey == null) { s_mshsnapinTracer.TraceError("Error opening registry key {0}\\{1}.", mshSnapInRoot.Name, mshsnapinId); throw PSTraceSource.NewArgumentException(nameof(mshsnapinId), MshSnapinInfo.MshSnapinDoesNotExist, mshsnapinId); @@ -708,14 +708,14 @@ private static PSSnapInInfo ReadOne(RegistryKey mshSnapInRoot, string mshsnapinI Version version = ReadVersionValue(mshsnapinKey, RegistryStrings.MshSnapin_Version, false); string description = ReadStringValue(mshsnapinKey, RegistryStrings.MshSnapin_Description, false); - if (description is null) + if (description == null) { s_mshsnapinTracer.WriteLine("No description is specified for mshsnapin {0}. Using empty string for description.", mshsnapinId); description = string.Empty; } string vendor = ReadStringValue(mshsnapinKey, RegistryStrings.MshSnapin_Vendor, false); - if (vendor is null) + if (vendor == null) { s_mshsnapinTracer.WriteLine("No vendor is specified for mshsnapin {0}. Using empty string for description.", mshsnapinId); vendor = string.Empty; @@ -752,7 +752,7 @@ private static PSSnapInInfo ReadOne(RegistryKey mshSnapInRoot, string mshsnapinI private static Collection ReadMultiStringValue(RegistryKey mshsnapinKey, string name, bool mandatory) { object value = mshsnapinKey.GetValue(name); - if (value is null) + if (value == null) { // If this key should be present..throw error if (mandatory) @@ -770,7 +770,7 @@ private static Collection ReadMultiStringValue(RegistryKey mshsnapinKey, // value cannot be null here... string[] msv = value as string[]; - if (msv is null) + if (msv == null) { // Check if the value is in string format string singleValue = value as string; @@ -781,7 +781,7 @@ private static Collection ReadMultiStringValue(RegistryKey mshsnapinKey, } } - if (msv is null) + if (msv == null) { if (mandatory) { @@ -816,7 +816,7 @@ internal static string ReadStringValue(RegistryKey mshsnapinKey, string name, bo Dbg.Assert(mshsnapinKey != null, "Caller should validate the parameter"); object value = mshsnapinKey.GetValue(name); - if (value is null && mandatory) + if (value == null && mandatory) { s_mshsnapinTracer.TraceError("Mandatory property {0} not specified for registry key {1}", name, mshsnapinKey.Name); @@ -839,7 +839,7 @@ internal static string ReadStringValue(RegistryKey mshsnapinKey, string name, bo internal static Version ReadVersionValue(RegistryKey mshsnapinKey, string name, bool mandatory) { string temp = ReadStringValue(mshsnapinKey, name, mandatory); - if (temp is null) + if (temp == null) { s_mshsnapinTracer.TraceError("Cannot read value for property {0} in registry key {1}", name, mshsnapinKey.ToString()); @@ -1124,7 +1124,7 @@ private static void SetSnapInLoggingInformation(PSSnapInInfo psSnapInInfo, Modul internal static RegistryKey GetMonadRootKey() { RegistryKey rootKey = Registry.LocalMachine.OpenSubKey(RegistryStrings.MonadRootKeyPath); - if (rootKey is null) + if (rootKey == null) { // This should never occur because this code is running // because monad is installed. { well this can occur if someone @@ -1155,13 +1155,13 @@ internal static RegistryKey GetPSEngineKey(string psVersion) Dbg.Assert(versionRootKey != null, "Version Rootkey of Monad installation is not present"); RegistryKey psEngineParentKey = rootKey.OpenSubKey(psVersion); - if (psEngineParentKey is null) + if (psEngineParentKey == null) { throw PSTraceSource.NewArgumentException("monad", MshSnapinInfo.MonadEngineRegistryAccessFailed); } RegistryKey psEngineKey = psEngineParentKey.OpenSubKey(RegistryStrings.MonadEngineKey); - if (psEngineKey is null) + if (psEngineKey == null) { throw PSTraceSource.NewArgumentException("monad", MshSnapinInfo.MonadEngineRegistryAccessFailed); } @@ -1190,7 +1190,7 @@ internal static string versionKey = PSVersionInfo.GetRegistryVersionKeyForSnapinDiscovery(psVersion); RegistryKey versionRoot = rootKey.OpenSubKey(versionKey); - if (versionRoot is null) + if (versionRoot == null) { throw PSTraceSource.NewArgumentException(nameof(psVersion), MshSnapinInfo.SpecifiedVersionNotFound, versionKey); } @@ -1217,7 +1217,7 @@ private static Dbg.Assert(versionRootKey != null, "caller should validate the parameter"); RegistryKey mshsnapinRoot = versionRootKey.OpenSubKey(RegistryStrings.MshSnapinKey); - if (mshsnapinRoot is null) + if (mshsnapinRoot == null) { throw PSTraceSource.NewArgumentException(nameof(psVersion), MshSnapinInfo.NoMshSnapinPresentForVersion, psVersion); } @@ -1244,7 +1244,7 @@ internal static RegistryKey monadRootKey = GetMonadRootKey(); RegistryKey versionRootKey = GetVersionRootKey(monadRootKey, psVersion); RegistryKey mshsnapinRoot = versionRootKey.OpenSubKey(RegistryStrings.MshSnapinKey); - if (mshsnapinRoot is null) + if (mshsnapinRoot == null) { throw PSTraceSource.NewArgumentException(nameof(psVersion), MshSnapinInfo.NoMshSnapinPresentForVersion, psVersion); } @@ -1292,11 +1292,11 @@ private static IList DefaultMshSnapins { get { - if (s_defaultMshSnapins is null) + if (s_defaultMshSnapins == null) { lock (s_syncObject) { - if (s_defaultMshSnapins is null) + if (s_defaultMshSnapins == null) { s_defaultMshSnapins = new List() { diff --git a/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs b/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs index 29ae4aa5e5c..9ee9588be65 100644 --- a/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs +++ b/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs @@ -132,7 +132,7 @@ public override ErrorRecord ErrorRecord { get { - if (_errorRecord is null) + if (_errorRecord == null) { _isErrorRecordOriginallyNull = true; _errorRecord = new ErrorRecord( @@ -190,7 +190,7 @@ protected PSSnapInException(SerializationInfo info, [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) { throw PSTraceSource.NewArgumentNullException(nameof(info)); } diff --git a/src/System.Management.Automation/utils/ClrFacade.cs b/src/System.Management.Automation/utils/ClrFacade.cs index 2d93a1bb67d..0638891eaa2 100644 --- a/src/System.Management.Automation/utils/ClrFacade.cs +++ b/src/System.Management.Automation/utils/ClrFacade.cs @@ -35,7 +35,7 @@ internal static class ClrFacade /// static ClrFacade() { - if (PowerShellAssemblyLoadContext.Instance is null) + if (PowerShellAssemblyLoadContext.Instance == null) { PowerShellAssemblyLoadContext.InitializeSingleton(string.Empty); } @@ -113,7 +113,7 @@ private static IEnumerable GetPSVisibleAssemblies() /// internal static Encoding GetDefaultEncoding() { - if (s_defaultEncoding is null) + if (s_defaultEncoding == null) { // load all available encodings EncodingRegisterProvider(); @@ -131,7 +131,7 @@ internal static Encoding GetDefaultEncoding() /// internal static Encoding GetOEMEncoding() { - if (s_oemEncoding is null) + if (s_oemEncoding == null) { // load all available encodings EncodingRegisterProvider(); @@ -150,7 +150,7 @@ internal static Encoding GetOEMEncoding() private static void EncodingRegisterProvider() { - if (s_defaultEncoding is null && s_oemEncoding is null) + if (s_defaultEncoding == null && s_oemEncoding == null) { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); } diff --git a/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs b/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs index ecc9a45cf03..c7dc2cb2587 100644 --- a/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs +++ b/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs @@ -85,7 +85,7 @@ protected CommandNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { - if (info is null) + if (info == null) { throw new PSArgumentNullException(nameof(info)); } @@ -105,7 +105,7 @@ protected CommandNotFoundException(SerializationInfo info, [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) { throw new PSArgumentNullException(nameof(info)); } @@ -123,7 +123,7 @@ public override ErrorRecord ErrorRecord { get { - if (_errorRecord is null) + if (_errorRecord == null) { _errorRecord = new ErrorRecord( new ParentContainsErrorRecordException(this), @@ -392,7 +392,7 @@ protected ScriptRequiresException(SerializationInfo info, [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) { throw new PSArgumentNullException(nameof(info)); } @@ -468,7 +468,7 @@ private static string BuildMessage( bool forSnapins) { StringBuilder sb = new StringBuilder(); - if (missingItems is null) + if (missingItems == null) { throw PSTraceSource.NewArgumentNullException(nameof(missingItems)); } diff --git a/src/System.Management.Automation/utils/CryptoUtils.cs b/src/System.Management.Automation/utils/CryptoUtils.cs index 80c48b58827..4b747eeab82 100644 --- a/src/System.Management.Automation/utils/CryptoUtils.cs +++ b/src/System.Management.Automation/utils/CryptoUtils.cs @@ -97,7 +97,7 @@ internal static RSA FromCapiPublicKeyBlob(byte[] blob) private static RSA FromCapiPublicKeyBlob(byte[] blob, int offset) { - if (blob is null) + if (blob == null) { throw new ArgumentNullException(nameof(blob)); } @@ -123,7 +123,7 @@ private static RSA FromCapiPublicKeyBlob(byte[] blob, int offset) private static RSAParameters GetParametersFromCapiPublicKeyBlob(byte[] blob, int offset) { - if (blob is null) + if (blob == null) { throw new ArgumentNullException(nameof(blob)); } @@ -175,7 +175,7 @@ private static RSAParameters GetParametersFromCapiPublicKeyBlob(byte[] blob, int internal static byte[] ToCapiPublicKeyBlob(RSA rsa) { - if (rsa is null) + if (rsa == null) { throw new ArgumentNullException(nameof(rsa)); } @@ -221,7 +221,7 @@ internal static byte[] ToCapiPublicKeyBlob(RSA rsa) internal static byte[] FromCapiSimpleKeyBlob(byte[] blob) { - if (blob is null) + if (blob == null) { throw new ArgumentNullException(nameof(blob)); } @@ -237,7 +237,7 @@ internal static byte[] FromCapiSimpleKeyBlob(byte[] blob) internal static byte[] ToCapiSimpleKeyBlob(byte[] encryptedKey) { - if (encryptedKey is null) + if (encryptedKey == null) { throw new ArgumentNullException(nameof(encryptedKey)); } diff --git a/src/System.Management.Automation/utils/ExecutionExceptions.cs b/src/System.Management.Automation/utils/ExecutionExceptions.cs index d9da7cc787e..2b7fcd7cff4 100644 --- a/src/System.Management.Automation/utils/ExecutionExceptions.cs +++ b/src/System.Management.Automation/utils/ExecutionExceptions.cs @@ -31,7 +31,7 @@ public class CmdletInvocationException : RuntimeException internal CmdletInvocationException(ErrorRecord errorRecord) : base(RetrieveMessage(errorRecord), RetrieveException(errorRecord)) { - if (errorRecord is null) + if (errorRecord == null) { throw new ArgumentNullException(nameof(errorRecord)); } @@ -56,7 +56,7 @@ internal CmdletInvocationException(Exception innerException, InvocationInfo invocationInfo) : base(RetrieveMessage(innerException), innerException) { - if (innerException is null) + if (innerException == null) { throw new ArgumentNullException(nameof(innerException)); } @@ -140,7 +140,7 @@ protected CmdletInvocationException(SerializationInfo info, [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) { throw new PSArgumentNullException(nameof(info)); } @@ -163,7 +163,7 @@ public override ErrorRecord ErrorRecord { get { - if (_errorRecord is null) + if (_errorRecord == null) { _errorRecord = new ErrorRecord( new ParentContainsErrorRecordException(this), @@ -206,7 +206,7 @@ internal CmdletProviderInvocationException( InvocationInfo myInvocation) : base(GetInnerException(innerException), myInvocation) { - if (innerException is null) + if (innerException == null) { throw new ArgumentNullException(nameof(innerException)); } @@ -287,7 +287,7 @@ public ProviderInfo ProviderInfo { get { - return (_providerInvocationException is null) + return (_providerInvocationException == null) ? null : _providerInvocationException.ProviderInfo; } @@ -298,7 +298,7 @@ public ProviderInfo ProviderInfo #region Internal private static Exception GetInnerException(Exception e) { - return (e is null) ? null : e.InnerException; + return (e == null) ? null : e.InnerException; } #endregion Internal } @@ -471,7 +471,7 @@ public ActionPreferenceStopException() internal ActionPreferenceStopException(ErrorRecord error) : this(RetrieveMessage(error)) { - if (error is null) + if (error == null) { throw new ArgumentNullException(nameof(error)); } @@ -499,7 +499,7 @@ internal ActionPreferenceStopException(InvocationInfo invocationInfo, string message) : this(invocationInfo, message) { - if (errorRecord is null) + if (errorRecord == null) { throw new ArgumentNullException(nameof(errorRecord)); } @@ -723,7 +723,7 @@ public override string Message /// Context. public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) { throw new PSArgumentNullException(nameof(info)); } @@ -898,7 +898,7 @@ public ErrorRecord ErrorRecord { get { - if (_errorRecord is null) + if (_errorRecord == null) { _errorRecord = new ErrorRecord( new ParentContainsErrorRecordException(this), @@ -1008,7 +1008,7 @@ public ErrorRecord ErrorRecord { get { - if (_errorRecord is null) + if (_errorRecord == null) { _errorRecord = new ErrorRecord( new ParentContainsErrorRecordException(this), diff --git a/src/System.Management.Automation/utils/ExtensionMethods.cs b/src/System.Management.Automation/utils/ExtensionMethods.cs index 94b9da1f98d..127c9a226cf 100644 --- a/src/System.Management.Automation/utils/ExtensionMethods.cs +++ b/src/System.Management.Automation/utils/ExtensionMethods.cs @@ -39,7 +39,7 @@ internal static IEnumerable Prepend(this IEnumerable collection, T elem internal static int SequenceGetHashCode(this IEnumerable xs) { // algorithm based on https://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode - if (xs is null) + if (xs == null) { return 82460653; // random number } diff --git a/src/System.Management.Automation/utils/MshArgumentException.cs b/src/System.Management.Automation/utils/MshArgumentException.cs index 68ac7c7fbb2..26980059c00 100644 --- a/src/System.Management.Automation/utils/MshArgumentException.cs +++ b/src/System.Management.Automation/utils/MshArgumentException.cs @@ -86,7 +86,7 @@ protected PSArgumentException(SerializationInfo info, [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) { throw new PSArgumentNullException(nameof(info)); } @@ -123,7 +123,7 @@ public ErrorRecord ErrorRecord { get { - if (_errorRecord is null) + if (_errorRecord == null) { _errorRecord = new ErrorRecord( new ParentContainsErrorRecordException(this), diff --git a/src/System.Management.Automation/utils/MshArgumentNullException.cs b/src/System.Management.Automation/utils/MshArgumentNullException.cs index a2009e9229f..03ab45654a3 100644 --- a/src/System.Management.Automation/utils/MshArgumentNullException.cs +++ b/src/System.Management.Automation/utils/MshArgumentNullException.cs @@ -97,7 +97,7 @@ protected PSArgumentNullException(SerializationInfo info, [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) { throw new PSArgumentNullException(nameof(info)); } @@ -121,7 +121,7 @@ public ErrorRecord ErrorRecord { get { - if (_errorRecord is null) + if (_errorRecord == null) { _errorRecord = new ErrorRecord( new ParentContainsErrorRecordException(this), diff --git a/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs b/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs index 6f3be3bf2e5..a6bb0dfd3ff 100644 --- a/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs +++ b/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs @@ -84,7 +84,7 @@ protected PSArgumentOutOfRangeException(SerializationInfo info, [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) { throw new PSArgumentNullException(nameof(info)); } @@ -119,7 +119,7 @@ public ErrorRecord ErrorRecord { get { - if (_errorRecord is null) + if (_errorRecord == null) { _errorRecord = new ErrorRecord( new ParentContainsErrorRecordException(this), diff --git a/src/System.Management.Automation/utils/MshInvalidOperationException.cs b/src/System.Management.Automation/utils/MshInvalidOperationException.cs index 5af6c55a734..0889fee33df 100644 --- a/src/System.Management.Automation/utils/MshInvalidOperationException.cs +++ b/src/System.Management.Automation/utils/MshInvalidOperationException.cs @@ -55,7 +55,7 @@ protected PSInvalidOperationException(SerializationInfo info, [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) { throw new PSArgumentNullException(nameof(info)); } @@ -117,7 +117,7 @@ public ErrorRecord ErrorRecord { get { - if (_errorRecord is null) + if (_errorRecord == null) { _errorRecord = new ErrorRecord( new ParentContainsErrorRecordException(this), diff --git a/src/System.Management.Automation/utils/MshNotImplementedException.cs b/src/System.Management.Automation/utils/MshNotImplementedException.cs index fac4a0aa7cd..e6a1128a38d 100644 --- a/src/System.Management.Automation/utils/MshNotImplementedException.cs +++ b/src/System.Management.Automation/utils/MshNotImplementedException.cs @@ -55,7 +55,7 @@ protected PSNotImplementedException(SerializationInfo info, [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) { throw new PSArgumentNullException(nameof(info)); } @@ -100,7 +100,7 @@ public ErrorRecord ErrorRecord { get { - if (_errorRecord is null) + if (_errorRecord == null) { _errorRecord = new ErrorRecord( new ParentContainsErrorRecordException(this), diff --git a/src/System.Management.Automation/utils/MshNotSupportedException.cs b/src/System.Management.Automation/utils/MshNotSupportedException.cs index 50f7a7303b3..e6847ba6d16 100644 --- a/src/System.Management.Automation/utils/MshNotSupportedException.cs +++ b/src/System.Management.Automation/utils/MshNotSupportedException.cs @@ -55,7 +55,7 @@ protected PSNotSupportedException(SerializationInfo info, [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) { throw new PSArgumentNullException(nameof(info)); } @@ -100,7 +100,7 @@ public ErrorRecord ErrorRecord { get { - if (_errorRecord is null) + if (_errorRecord == null) { _errorRecord = new ErrorRecord( new ParentContainsErrorRecordException(this), diff --git a/src/System.Management.Automation/utils/MshObjectDisposedException.cs b/src/System.Management.Automation/utils/MshObjectDisposedException.cs index cfa91a38132..93cf76100bb 100644 --- a/src/System.Management.Automation/utils/MshObjectDisposedException.cs +++ b/src/System.Management.Automation/utils/MshObjectDisposedException.cs @@ -83,7 +83,7 @@ protected PSObjectDisposedException(SerializationInfo info, [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) { throw new PSArgumentNullException(nameof(info)); } @@ -106,7 +106,7 @@ public ErrorRecord ErrorRecord { get { - if (_errorRecord is null) + if (_errorRecord == null) { _errorRecord = new ErrorRecord( new ParentContainsErrorRecordException(this), diff --git a/src/System.Management.Automation/utils/MshTraceSource.cs b/src/System.Management.Automation/utils/MshTraceSource.cs index 3afb3124748..9bb0cfbcc3d 100644 --- a/src/System.Management.Automation/utils/MshTraceSource.cs +++ b/src/System.Management.Automation/utils/MshTraceSource.cs @@ -116,7 +116,7 @@ internal static PSTraceSource GetTracer( // If it's not already in the catalog, see if we can find it in the // pre-configured trace source list - if (result is null) + if (result == null) { string keyName = name; if (!PSTraceSource.PreConfiguredTraceSource.ContainsKey(keyName)) @@ -158,7 +158,7 @@ internal static PSTraceSource GetTracer( // a StructuredTraceSource should be able to do so even with the PSTraceSource // instance. - if (result is null) + if (result == null) { result = PSTraceSource.GetNewTraceSource(name, description, traceHeaders); PSTraceSource.TraceCatalog[result.FullName] = result; diff --git a/src/System.Management.Automation/utils/ObjectReader.cs b/src/System.Management.Automation/utils/ObjectReader.cs index e7200600a0c..deb056a180e 100644 --- a/src/System.Management.Automation/utils/ObjectReader.cs +++ b/src/System.Management.Automation/utils/ObjectReader.cs @@ -25,7 +25,7 @@ internal abstract class ObjectReaderBase : PipelineReader, IDisposable /// Thrown if the specified stream is null. public ObjectReaderBase([In, Out] ObjectStreamBase stream) { - if (stream is null) + if (stream == null) { throw new ArgumentNullException(nameof(stream), "stream may not be null"); } @@ -44,7 +44,7 @@ public override event EventHandler DataReady { lock (_monitorObject) { - bool firstRegistrant = (InternalDataReady is null); + bool firstRegistrant = (InternalDataReady == null); InternalDataReady += value; if (firstRegistrant) { @@ -58,7 +58,7 @@ public override event EventHandler DataReady lock (_monitorObject) { InternalDataReady -= value; - if (InternalDataReady is null) + if (InternalDataReady == null) { _stream.DataReady -= this.OnDataReady; } @@ -450,7 +450,7 @@ protected override void Dispose(bool disposing) #region Private private static PSObject MakePSObject(object o) { - if (o is null) + if (o == null) return null; return PSObject.AsPSObject(o); @@ -463,7 +463,7 @@ private static PSObject MakePSObject(object o) private static Collection MakePSObjectCollection( Collection coll) { - if (coll is null) + if (coll == null) return null; Collection retval = new Collection(); foreach (object o in coll) diff --git a/src/System.Management.Automation/utils/ObjectStream.cs b/src/System.Management.Automation/utils/ObjectStream.cs index 6526365778a..eccfdfad901 100644 --- a/src/System.Management.Automation/utils/ObjectStream.cs +++ b/src/System.Management.Automation/utils/ObjectStream.cs @@ -609,7 +609,7 @@ internal override WaitHandle ReadHandle lock (_monitorObject) { - if (_readWaitHandle is null) + if (_readWaitHandle == null) { // Create the handle signaled if there are objects in the stream // or the stream has been closed. The closed scenario addresses @@ -642,7 +642,7 @@ internal override WaitHandle WriteHandle lock (_monitorObject) { - if (_writeWaitHandle is null) + if (_writeWaitHandle == null) { _writeWaitHandle = new ManualResetEvent(_objects.Count < _capacity || !_isOpen); } @@ -665,7 +665,7 @@ internal override PipelineReader ObjectReader lock (_monitorObject) { - if (_reader is null) + if (_reader == null) { // Always return an object reader, even if the stream // is closed. This is to address requesting the object reader @@ -695,7 +695,7 @@ internal override PipelineReader PSObjectReader lock (_monitorObject) { - if (_mshreader is null) + if (_mshreader == null) { // Always return an object reader, even if the stream // is closed. This is to address requesting the object reader @@ -726,7 +726,7 @@ internal override PipelineWriter ObjectWriter lock (_monitorObject) { - if (_writer is null) + if (_writer == null) { _writer = new ObjectWriter(this) as PipelineWriter; } @@ -1351,7 +1351,7 @@ internal override int Write(object obj, bool enumerateCollection) enumerable = LanguagePrimitives.GetEnumerable(obj); } - if (enumerable is null) + if (enumerable == null) a.Add(obj); else { @@ -1581,7 +1581,7 @@ internal sealed class PSDataCollectionStream : ObjectStreamBase /// internal PSDataCollectionStream(Guid psInstanceId, PSDataCollection storeToUse) { - if (storeToUse is null) + if (storeToUse == null) { throw PSTraceSource.NewArgumentNullException(nameof(storeToUse)); } @@ -1682,11 +1682,11 @@ internal override PipelineReader ObjectReader { get { - if (_objectReader is null) + if (_objectReader == null) { lock (_syncObject) { - if (_objectReader is null) + if (_objectReader == null) { _objectReader = new PSDataCollectionReader(this); } @@ -1707,11 +1707,11 @@ internal override PipelineReader ObjectReader /// the object that this stream writes belongs to internal PipelineReader GetObjectReaderForPipeline(string computerName, Guid runspaceId) { - if (_objectReaderForPipeline is null) + if (_objectReaderForPipeline == null) { lock (_syncObject) { - if (_objectReaderForPipeline is null) + if (_objectReaderForPipeline == null) { _objectReaderForPipeline = new PSDataCollectionPipelineReader(this, computerName, runspaceId); @@ -1729,11 +1729,11 @@ internal override PipelineReader PSObjectReader { get { - if (_psobjectReader is null) + if (_psobjectReader == null) { lock (_syncObject) { - if (_psobjectReader is null) + if (_psobjectReader == null) { _psobjectReader = new PSDataCollectionReader(this); } @@ -1754,11 +1754,11 @@ internal override PipelineReader PSObjectReader /// the object that this stream writes belongs to internal PipelineReader GetPSObjectReaderForPipeline(string computerName, Guid runspaceId) { - if (_psobjectReaderForPipeline is null) + if (_psobjectReaderForPipeline == null) { lock (_syncObject) { - if (_psobjectReaderForPipeline is null) + if (_psobjectReaderForPipeline == null) { _psobjectReaderForPipeline = new PSDataCollectionPipelineReader(this, computerName, runspaceId); @@ -1780,11 +1780,11 @@ internal override PipelineWriter ObjectWriter { get { - if (_writer is null) + if (_writer == null) { lock (_syncObject) { - if (_writer is null) + if (_writer == null) { _writer = new PSDataCollectionWriter(this) as PipelineWriter; } @@ -1845,7 +1845,7 @@ internal override int Write(object obj, bool enumerateCollection) enumerable = LanguagePrimitives.GetEnumerable(obj); } - if (enumerable is null) + if (enumerable == null) { objectsToAdd.Add((T)LanguagePrimitives.ConvertTo(obj, typeof(T), Globalization.CultureInfo.InvariantCulture)); diff --git a/src/System.Management.Automation/utils/ObjectWriter.cs b/src/System.Management.Automation/utils/ObjectWriter.cs index 08e609684c5..d4fe3493b78 100644 --- a/src/System.Management.Automation/utils/ObjectWriter.cs +++ b/src/System.Management.Automation/utils/ObjectWriter.cs @@ -23,7 +23,7 @@ internal class ObjectWriter : PipelineWriter /// Thrown if the specified stream is null. public ObjectWriter([In, Out] ObjectStreamBase stream) { - if (stream is null) + if (stream == null) { throw new ArgumentNullException(nameof(stream)); } diff --git a/src/System.Management.Automation/utils/PSTelemetryWrapper.cs b/src/System.Management.Automation/utils/PSTelemetryWrapper.cs index 12932d07fc3..8e9da553f24 100644 --- a/src/System.Management.Automation/utils/PSTelemetryWrapper.cs +++ b/src/System.Management.Automation/utils/PSTelemetryWrapper.cs @@ -30,7 +30,7 @@ static TelemetryWrapper() var diagnosticsTracingAssembly = typeof(EventSource).Assembly; Type eventSourceSettingsType = diagnosticsTracingAssembly.GetType("System.Diagnostics.Tracing.EventSourceSettings"); - if (eventSourceSettingsType is null) + if (eventSourceSettingsType == null) { // Probably on CLR 4.5. return; diff --git a/src/System.Management.Automation/utils/ParameterBinderExceptions.cs b/src/System.Management.Automation/utils/ParameterBinderExceptions.cs index ca5a241c86f..903bdc4076c 100644 --- a/src/System.Management.Automation/utils/ParameterBinderExceptions.cs +++ b/src/System.Management.Automation/utils/ParameterBinderExceptions.cs @@ -105,7 +105,7 @@ internal ParameterBindingException( _parameterType = parameterType; _typeSpecified = typeSpecified; - if ((errorPosition is null) && (_invocationInfo != null)) + if ((errorPosition == null) && (_invocationInfo != null)) { errorPosition = invocationInfo.ScriptPosition; } @@ -192,7 +192,7 @@ internal ParameterBindingException( params object[] args) : base(errorCategory, invocationInfo, errorPosition, errorId, null, innerException) { - if (invocationInfo is null) + if (invocationInfo == null) { throw PSTraceSource.NewArgumentNullException(nameof(invocationInfo)); } @@ -213,7 +213,7 @@ internal ParameterBindingException( _parameterType = parameterType; _typeSpecified = typeSpecified; - if (errorPosition is null) + if (errorPosition == null) { errorPosition = invocationInfo.ScriptPosition; } @@ -246,7 +246,7 @@ internal ParameterBindingException( params object[] args) : base(string.Empty, innerException) { - if (pbex is null) + if (pbex == null) { throw PSTraceSource.NewArgumentNullException(nameof(pbex)); } @@ -325,7 +325,7 @@ protected ParameterBindingException( [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) { throw new PSArgumentNullException(nameof(info)); } diff --git a/src/System.Management.Automation/utils/ParserException.cs b/src/System.Management.Automation/utils/ParserException.cs index b0aad85c5fc..22010873d9f 100644 --- a/src/System.Management.Automation/utils/ParserException.cs +++ b/src/System.Management.Automation/utils/ParserException.cs @@ -46,7 +46,7 @@ protected ParseException(SerializationInfo info, /// public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) { throw new PSArgumentNullException(nameof(info)); } @@ -131,7 +131,7 @@ public ParseException(string message, Justification = "ErrorRecord is not overridden in classes deriving from ParseException")] public ParseException(Language.ParseError[] errors) { - if ((errors is null) || (errors.Length == 0)) + if ((errors == null) || (errors.Length == 0)) { throw new ArgumentNullException(nameof(errors)); } @@ -154,7 +154,7 @@ public override string Message { get { - if (_errors is null) + if (_errors == null) { return base.Message; } diff --git a/src/System.Management.Automation/utils/PowerShellETWTracer.cs b/src/System.Management.Automation/utils/PowerShellETWTracer.cs index 2812830af7a..0dc4b2f08f8 100644 --- a/src/System.Management.Automation/utils/PowerShellETWTracer.cs +++ b/src/System.Management.Automation/utils/PowerShellETWTracer.cs @@ -858,7 +858,7 @@ private bool Trace(PowerShellTraceEvent traceEvent, PowerShellTraceLevel level, { for (int i = 0; i < args.Length; i++) { - if (args[i] is null) + if (args[i] == null) { args[i] = string.Empty; } @@ -1136,7 +1136,7 @@ public void WriteMessage(string className, string methodName, Guid workflowId, s PSOpcode.Method, PSTask.None, PSKeyword.UseAlwaysAnalytic, className, methodName, workflowId.ToString(), - parameters is null ? message : StringUtil.Format(message, parameters), + parameters == null ? message : StringUtil.Format(message, parameters), string.Empty, // Job string.Empty, // Activity name string.Empty, // Activity GUID @@ -1187,7 +1187,7 @@ public void WriteMessage(string className, string methodName, Guid workflowId, J PSOpcode.Method, PSTask.None, PSKeyword.UseAlwaysAnalytic, className, methodName, workflowId.ToString(), - parameters is null ? message : StringUtil.Format(message, parameters), + parameters == null ? message : StringUtil.Format(message, parameters), sb.ToString(),// Job string.Empty, // Activity name string.Empty, // Activity GUID @@ -1457,7 +1457,7 @@ public void WriteMessage(string className, string methodName, Guid workflowId, s PSOpcode.Method, PSTask.None, PSKeyword.UseAlwaysAnalytic, className, methodName, workflowId.ToString(), - parameters is null ? message : StringUtil.Format(message, parameters), + parameters == null ? message : StringUtil.Format(message, parameters), string.Empty, // Job activityName, activityId.ToString(), diff --git a/src/System.Management.Automation/utils/PowerShellExecutionHelper.cs b/src/System.Management.Automation/utils/PowerShellExecutionHelper.cs index e8947b64449..d6d845c7281 100644 --- a/src/System.Management.Automation/utils/PowerShellExecutionHelper.cs +++ b/src/System.Management.Automation/utils/PowerShellExecutionHelper.cs @@ -16,7 +16,7 @@ internal class PowerShellExecutionHelper // Used by the ISE internal PowerShellExecutionHelper(PowerShell powershell) { - if (powershell is null) + if (powershell == null) { throw PSTraceSource.NewArgumentNullException(nameof(powershell)); } @@ -57,7 +57,7 @@ internal bool ExecuteCommandAndGetResultAsBool() Exception exceptionThrown; Collection streamResults = ExecuteCurrentPowerShell(out exceptionThrown); - if (exceptionThrown != null || streamResults is null || streamResults.Count == 0) + if (exceptionThrown != null || streamResults == null || streamResults.Count == 0) { return false; } @@ -71,13 +71,13 @@ internal string ExecuteCommandAndGetResultAsString() Exception exceptionThrown; Collection streamResults = ExecuteCurrentPowerShell(out exceptionThrown); - if (exceptionThrown != null || streamResults is null || streamResults.Count == 0) + if (exceptionThrown != null || streamResults == null || streamResults.Count == 0) { return null; } // we got back one or more objects. Pick off the first result. - if (streamResults[0] is null) + if (streamResults[0] == null) return string.Empty; // And convert the base object into a string. We can't use the proxied @@ -177,7 +177,7 @@ internal Collection ExecuteCurrentPowerShell(out Exception exceptionTh /// The result of the conversion... internal static string SafeToString(object obj) { - if (obj is null) + if (obj == null) { return string.Empty; } @@ -215,7 +215,7 @@ internal static string SafeToString(object obj) /// The object to convert to a string... internal static void SafeAddToStringList(List list, object obj) { - if (list is null) + if (list == null) return; string result = SafeToString(obj); if (!string.IsNullOrEmpty(result)) diff --git a/src/System.Management.Automation/utils/PsUtils.cs b/src/System.Management.Automation/utils/PsUtils.cs index dc735a92049..5866e3d52f9 100644 --- a/src/System.Management.Automation/utils/PsUtils.cs +++ b/src/System.Management.Automation/utils/PsUtils.cs @@ -302,7 +302,7 @@ internal static Hashtable EvaluatePowerShellDataFile( if (string.IsNullOrEmpty(psDataFilePath)) { throw PSTraceSource.NewArgumentNullException(nameof(psDataFilePath)); } - if (context is null) { throw PSTraceSource.NewArgumentNullException(nameof(context)); } + if (context == null) { throw PSTraceSource.NewArgumentNullException(nameof(context)); } string resolvedPath; if (skipPathValidation) @@ -327,7 +327,7 @@ internal static Hashtable EvaluatePowerShellDataFile( var resolvedPaths = context.SessionState.Path.GetResolvedProviderPathFromPSPath(psDataFilePath, out provider); // ConfigPath should be resolved as FileSystem provider - if (provider is null || !Microsoft.PowerShell.Commands.FileSystemProvider.ProviderName.Equals(provider.Name, StringComparison.OrdinalIgnoreCase)) + if (provider == null || !Microsoft.PowerShell.Commands.FileSystemProvider.ProviderName.Equals(provider.Name, StringComparison.OrdinalIgnoreCase)) { isPathValid = false; } @@ -387,7 +387,7 @@ internal static Hashtable EvaluatePowerShellDataFile( } var retResult = evaluationResult as Hashtable; - if (retResult is null) + if (retResult == null) { throw PSTraceSource.NewInvalidOperationException( ParserStrings.InvalidPowerShellDataFile, @@ -485,7 +485,7 @@ internal static string StringToBase64String(string input) { // NTRAID#Windows Out Of Band Releases-926471-2005/12/27-JonN // shell crashes if you pass an empty script block to a native command - if (input is null) + if (input == null) { throw PSTraceSource.NewArgumentNullException(nameof(input)); } @@ -540,7 +540,7 @@ internal static object[] Base64ToArgsConverter(string base64) } PSObject mo = dso as PSObject; - if (mo is null) + if (mo == null) { // This helper function should move the host. Provide appropriate error message. // Format of args parameter is not correct. @@ -548,7 +548,7 @@ internal static object[] Base64ToArgsConverter(string base64) } var argsList = mo.BaseObject as ArrayList; - if (argsList is null) + if (argsList == null) { // This helper function should move the host. Provide appropriate error message. // Format of args parameter is not correct. diff --git a/src/System.Management.Automation/utils/ResourceManagerCache.cs b/src/System.Management.Automation/utils/ResourceManagerCache.cs index 7b081edb33c..302fd0c48cf 100644 --- a/src/System.Management.Automation/utils/ResourceManagerCache.cs +++ b/src/System.Management.Automation/utils/ResourceManagerCache.cs @@ -41,7 +41,7 @@ internal static ResourceManager GetResourceManager( Assembly assembly, string baseName) { - if (assembly is null) + if (assembly == null) { throw PSTraceSource.NewArgumentNullException(nameof(assembly)); } @@ -69,7 +69,7 @@ internal static ResourceManager GetResourceManager( } // If it's not in the cache, create it an add it. - if (manager is null) + if (manager == null) { manager = InitRMWithAssembly(baseName, assembly); @@ -152,7 +152,7 @@ internal static string GetResourceString( string baseName, string resourceId) { - if (assembly is null) + if (assembly == null) { throw PSTraceSource.NewArgumentNullException(nameof(assembly)); } diff --git a/src/System.Management.Automation/utils/RuntimeException.cs b/src/System.Management.Automation/utils/RuntimeException.cs index 120edd8228e..fe5a6c3b4be 100644 --- a/src/System.Management.Automation/utils/RuntimeException.cs +++ b/src/System.Management.Automation/utils/RuntimeException.cs @@ -58,7 +58,7 @@ protected RuntimeException(SerializationInfo info, [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) { throw new PSArgumentNullException(nameof(info)); } @@ -118,12 +118,12 @@ internal RuntimeException(ErrorCategory errorCategory, SetErrorCategory(errorCategory); SetErrorId(errorIdAndResourceId); - if ((errorPosition is null) && (invocationInfo != null)) + if ((errorPosition == null) && (invocationInfo != null)) { errorPosition = invocationInfo.ScriptPosition; } - if (invocationInfo is null) return; + if (invocationInfo == null) return; _errorRecord = new ErrorRecord( new ParentContainsErrorRecordException(this), _errorId, @@ -153,7 +153,7 @@ public virtual ErrorRecord ErrorRecord { get { - if (_errorRecord is null) + if (_errorRecord == null) { _errorRecord = new ErrorRecord( new ParentContainsErrorRecordException(this), @@ -224,7 +224,7 @@ internal void SetTargetObject(object targetObject) #region Internal internal static string RetrieveMessage(ErrorRecord errorRecord) { - if (errorRecord is null) + if (errorRecord == null) return string.Empty; if (null != errorRecord.ErrorDetails && !string.IsNullOrEmpty(errorRecord.ErrorDetails.Message)) @@ -232,24 +232,24 @@ internal static string RetrieveMessage(ErrorRecord errorRecord) return errorRecord.ErrorDetails.Message; } - if (errorRecord.Exception is null) + if (errorRecord.Exception == null) return string.Empty; return errorRecord.Exception.Message; } internal static string RetrieveMessage(Exception e) { - if (e is null) + if (e == null) return string.Empty; IContainsErrorRecord icer = e as IContainsErrorRecord; - if (icer is null) + if (icer == null) return e.Message; ErrorRecord er = icer.ErrorRecord; - if (er is null) + if (er == null) return e.Message; ErrorDetails ed = er.ErrorDetails; - if (ed is null) + if (ed == null) return e.Message; string detailsMessage = ed.Message; return (string.IsNullOrEmpty(detailsMessage)) ? e.Message : detailsMessage; @@ -257,7 +257,7 @@ internal static string RetrieveMessage(Exception e) internal static Exception RetrieveException(ErrorRecord errorRecord) { - if (errorRecord is null) + if (errorRecord == null) return null; return errorRecord.Exception; } diff --git a/src/System.Management.Automation/utils/SessionStateExceptions.cs b/src/System.Management.Automation/utils/SessionStateExceptions.cs index 1f90aa2b944..acf3d9b8306 100644 --- a/src/System.Management.Automation/utils/SessionStateExceptions.cs +++ b/src/System.Management.Automation/utils/SessionStateExceptions.cs @@ -96,7 +96,7 @@ internal ProviderInvocationException(ProviderInfo provider, ErrorRecord errorRec : base(RuntimeException.RetrieveMessage(errorRecord), RuntimeException.RetrieveException(errorRecord)) { - if (errorRecord is null) + if (errorRecord == null) { throw new ArgumentNullException(nameof(errorRecord)); } @@ -235,7 +235,7 @@ public override ErrorRecord ErrorRecord { get { - if (_errorRecord is null) + if (_errorRecord == null) { _errorRecord = new ErrorRecord( new ParentContainsErrorRecordException(this), @@ -260,7 +260,7 @@ private static string RetrieveMessage( string path, Exception innerException) { - if (innerException is null) + if (innerException == null) { Diagnostics.Assert(false, "ProviderInvocationException.RetrieveMessage needs innerException"); @@ -274,7 +274,7 @@ private static string RetrieveMessage( return RuntimeException.RetrieveMessage(innerException); } - if (provider is null) + if (provider == null) { Diagnostics.Assert(false, "ProviderInvocationException.RetrieveMessage needs provider"); @@ -291,7 +291,7 @@ private static string RetrieveMessage( string result = null; - if (path is null) + if (path == null) { result = string.Format( @@ -480,7 +480,7 @@ protected SessionStateException(SerializationInfo info, [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) + if (info == null) { throw new PSArgumentNullException(nameof(info)); } @@ -499,7 +499,7 @@ public override ErrorRecord ErrorRecord { get { - if (_errorRecord is null) + if (_errorRecord == null) { _errorRecord = new ErrorRecord( new ParentContainsErrorRecordException(this), diff --git a/src/System.Management.Automation/utils/StringUtil.cs b/src/System.Management.Automation/utils/StringUtil.cs index 469c7a2c024..9a95407df76 100644 --- a/src/System.Management.Automation/utils/StringUtil.cs +++ b/src/System.Management.Automation/utils/StringUtil.cs @@ -76,7 +76,7 @@ internal static string Padding(int countOfSpaces) var result = IndentCache[countOfSpaces]; - if (result is null) + if (result == null) { Interlocked.CompareExchange(ref IndentCache[countOfSpaces], new string(' ', countOfSpaces), null); result = IndentCache[countOfSpaces]; @@ -96,7 +96,7 @@ internal static string DashPadding(int count) var result = DashCache[count]; - if (result is null) + if (result == null) { Interlocked.CompareExchange(ref DashCache[count], new string('-', count), null); result = DashCache[count]; diff --git a/src/System.Management.Automation/utils/StructuredTraceSource.cs b/src/System.Management.Automation/utils/StructuredTraceSource.cs index fb898310059..c464a27cbaa 100644 --- a/src/System.Management.Automation/utils/StructuredTraceSource.cs +++ b/src/System.Management.Automation/utils/StructuredTraceSource.cs @@ -1084,7 +1084,7 @@ internal void WriteLine(object arg) { if ((_flags & PSTraceSourceOptions.WriteLine) != PSTraceSourceOptions.None) { - WriteLine("{0}", arg is null ? "null" : arg.ToString()); + WriteLine("{0}", arg == null ? "null" : arg.ToString()); } } diff --git a/src/System.Management.Automation/utils/tracing/EtwActivity.cs b/src/System.Management.Automation/utils/tracing/EtwActivity.cs index 577c6f72d4d..2bd8a57fbeb 100644 --- a/src/System.Management.Automation/utils/tracing/EtwActivity.cs +++ b/src/System.Management.Automation/utils/tracing/EtwActivity.cs @@ -120,12 +120,12 @@ private class CorrelatedCallback /// public CorrelatedCallback(EtwActivity tracer, CallbackNoParameter callback) { - if (callback is null) + if (callback == null) { throw new ArgumentNullException(nameof(callback)); } - if (tracer is null) + if (tracer == null) { throw new ArgumentNullException(nameof(tracer)); } @@ -142,12 +142,12 @@ public CorrelatedCallback(EtwActivity tracer, CallbackNoParameter callback) /// public CorrelatedCallback(EtwActivity tracer, CallbackWithState callback) { - if (callback is null) + if (callback == null) { throw new ArgumentNullException(nameof(callback)); } - if (tracer is null) + if (tracer == null) { throw new ArgumentNullException(nameof(tracer)); } @@ -164,12 +164,12 @@ public CorrelatedCallback(EtwActivity tracer, CallbackWithState callback) /// public CorrelatedCallback(EtwActivity tracer, AsyncCallback callback) { - if (callback is null) + if (callback == null) { throw new ArgumentNullException(nameof(callback)); } - if (tracer is null) + if (tracer == null) { throw new ArgumentNullException(nameof(tracer)); } @@ -191,12 +191,12 @@ public CorrelatedCallback(EtwActivity tracer, AsyncCallback callback) /// public CorrelatedCallback(EtwActivity tracer, CallbackWithStateAndArgs callback) { - if (callback is null) + if (callback == null) { throw new ArgumentNullException(nameof(callback)); } - if (tracer is null) + if (tracer == null) { throw new ArgumentNullException(nameof(tracer)); } @@ -378,7 +378,7 @@ public void Correlate() /// public CallbackNoParameter Correlate(CallbackNoParameter callback) { - if (callback is null) + if (callback == null) { throw new ArgumentNullException(nameof(callback)); } @@ -393,7 +393,7 @@ public CallbackNoParameter Correlate(CallbackNoParameter callback) /// public CallbackWithState Correlate(CallbackWithState callback) { - if (callback is null) + if (callback == null) { throw new ArgumentNullException(nameof(callback)); } @@ -408,7 +408,7 @@ public CallbackWithState Correlate(CallbackWithState callback) /// public AsyncCallback Correlate(AsyncCallback callback) { - if (callback is null) + if (callback == null) { throw new ArgumentNullException(nameof(callback)); } @@ -424,7 +424,7 @@ public AsyncCallback Correlate(AsyncCallback callback) /// public CallbackWithStateAndArgs Correlate(CallbackWithStateAndArgs callback) { - if (callback is null) + if (callback == null) { throw new ArgumentNullException(nameof(callback)); } @@ -473,7 +473,7 @@ protected void WriteEvent(EventDescriptor ed, params object[] payload) { for (int i = 0; i < payload.Length; i++) { - if (payload[i] is null) + if (payload[i] == null) { payload[i] = string.Empty; } diff --git a/src/System.Management.Automation/utils/tracing/EtwActivityReverterMethodInvoker.cs b/src/System.Management.Automation/utils/tracing/EtwActivityReverterMethodInvoker.cs index 09e9103bddd..db63b2727d3 100644 --- a/src/System.Management.Automation/utils/tracing/EtwActivityReverterMethodInvoker.cs +++ b/src/System.Management.Automation/utils/tracing/EtwActivityReverterMethodInvoker.cs @@ -20,7 +20,7 @@ internal class EtwActivityReverterMethodInvoker : public EtwActivityReverterMethodInvoker(IEtwEventCorrelator eventCorrelator) { - if (eventCorrelator is null) + if (eventCorrelator == null) { throw new ArgumentNullException(nameof(eventCorrelator)); } diff --git a/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs b/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs index 2cbe61e91a4..7e4e81abe06 100644 --- a/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs +++ b/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs @@ -61,7 +61,7 @@ public class EtwEventCorrelator : /// during activity correlation. public EtwEventCorrelator(EventProvider transferProvider, EventDescriptor transferEvent) { - if (transferProvider is null) + if (transferProvider == null) { throw new ArgumentNullException(nameof(transferProvider)); } diff --git a/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs b/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs index 0b9c972196c..173c5b8379a 100755 --- a/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs +++ b/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs @@ -219,7 +219,7 @@ internal override void LogSettingsEvent(LogContext logContext, string variableNa { StringBuilder payload = new StringBuilder(); - if (previousValue is null) + if (previousValue == null) { payload.AppendLine(StringUtil.Format(EtwLoggingStrings.SettingChangeNoPrevious, variableName, value)); } diff --git a/src/System.Management.Automation/utils/tracing/PSSysLogProvider.cs b/src/System.Management.Automation/utils/tracing/PSSysLogProvider.cs index 8e15f10345c..5f698f1b912 100755 --- a/src/System.Management.Automation/utils/tracing/PSSysLogProvider.cs +++ b/src/System.Management.Automation/utils/tracing/PSSysLogProvider.cs @@ -48,7 +48,7 @@ private static StringBuilder PayloadBuilder { get { - if (t_payloadBuilder is null) + if (t_payloadBuilder == null) { // NOTE: Thread static fields must be explicitly initialized for each thread. t_payloadBuilder = new StringBuilder(200); @@ -259,7 +259,7 @@ internal override void LogSettingsEvent(LogContext logContext, string variableNa StringBuilder payload = PayloadBuilder; payload.Clear(); - if (previousValue is null) + if (previousValue == null) { payload.AppendLine(StringUtil.Format(EtwLoggingStrings.SettingChangeNoPrevious, variableName, value)); } diff --git a/src/System.Management.Automation/utils/tracing/SysLogProvider.cs b/src/System.Management.Automation/utils/tracing/SysLogProvider.cs index 67aeab35d4a..54bd39a38ad 100755 --- a/src/System.Management.Automation/utils/tracing/SysLogProvider.cs +++ b/src/System.Management.Automation/utils/tracing/SysLogProvider.cs @@ -129,7 +129,7 @@ private static StringBuilder MessageBuilder { get { - if (t_messageBuilder is null) + if (t_messageBuilder == null) { // NOTE: Thread static fields must be explicitly initialized for each thread. t_messageBuilder = new StringBuilder(200); @@ -252,7 +252,7 @@ private static void GetEventMessage(StringBuilder sb, PSEventId eventId, params int parameterCount; string resourceName = EventResource.GetMessage((int) eventId, out parameterCount); - if (resourceName is null) + if (resourceName == null) { // If an event id was specified that is not found in the event resource lookup table, // use a placeholder message that includes the event id. diff --git a/src/System.Management.Automation/utils/tracing/Tracing.cs b/src/System.Management.Automation/utils/tracing/Tracing.cs index 5b436d6fd04..70338b28c7a 100644 --- a/src/System.Management.Automation/utils/tracing/Tracing.cs +++ b/src/System.Management.Automation/utils/tracing/Tracing.cs @@ -17,7 +17,7 @@ public sealed partial class Tracer : System.Management.Automation.Tracing.EtwAct [EtwEvent(0xc000)] public void DebugMessage(Exception exception) { - if (exception is null) + if (exception == null) return; DebugMessage(GetExceptionString(exception)); @@ -30,7 +30,7 @@ public void DebugMessage(Exception exception) /// public static string GetExceptionString(Exception exception) { - if (exception is null) + if (exception == null) return string.Empty; StringBuilder sb = new StringBuilder(); @@ -44,7 +44,7 @@ public static string GetExceptionString(Exception exception) private static bool WriteExceptionText(StringBuilder sb, Exception e) { - if (e is null) + if (e == null) return false; sb.Append(e.GetType().Name); diff --git a/test/xUnit/csharp/test_PSConfiguration.cs b/test/xUnit/csharp/test_PSConfiguration.cs index 7744044338a..45e057bea75 100644 --- a/test/xUnit/csharp/test_PSConfiguration.cs +++ b/test/xUnit/csharp/test_PSConfiguration.cs @@ -124,7 +124,7 @@ internal PowerShellPolicies CurrentUserPolicies internal void CompareScriptExecution(ScriptExecution a, ScriptExecution b) { - if (a is null) + if (a == null) { Assert.Null(b); } @@ -137,7 +137,7 @@ internal void CompareScriptExecution(ScriptExecution a, ScriptExecution b) internal void CompareScriptBlockLogging(ScriptBlockLogging a, ScriptBlockLogging b) { - if (a is null) + if (a == null) { Assert.Null(b); } @@ -150,14 +150,14 @@ internal void CompareScriptBlockLogging(ScriptBlockLogging a, ScriptBlockLogging internal void CompareModuleLogging(ModuleLogging a, ModuleLogging b) { - if (a is null) + if (a == null) { Assert.Null(b); } else { Assert.Equal(a.EnableModuleLogging, b.EnableModuleLogging); - if (a.ModuleNames is null) + if (a.ModuleNames == null) { Assert.Null(b.ModuleNames); } @@ -174,14 +174,14 @@ internal void CompareModuleLogging(ModuleLogging a, ModuleLogging b) internal void CompareProtectedEventLogging(ProtectedEventLogging a, ProtectedEventLogging b) { - if (a is null) + if (a == null) { Assert.Null(b); } else { Assert.Equal(a.EnableProtectedEventLogging, b.EnableProtectedEventLogging); - if (a.EncryptionCertificate is null) + if (a.EncryptionCertificate == null) { Assert.Null(b.EncryptionCertificate); } @@ -198,7 +198,7 @@ internal void CompareProtectedEventLogging(ProtectedEventLogging a, ProtectedEve internal void CompareTranscription(Transcription a, Transcription b) { - if (a is null) + if (a == null) { Assert.Null(b); } @@ -212,7 +212,7 @@ internal void CompareTranscription(Transcription a, Transcription b) internal void CompareUpdatableHelp(UpdatableHelp a, UpdatableHelp b) { - if (a is null) + if (a == null) { Assert.Null(b); } @@ -224,7 +224,7 @@ internal void CompareUpdatableHelp(UpdatableHelp a, UpdatableHelp b) internal void CompareConsoleSessionConfiguration(ConsoleSessionConfiguration a, ConsoleSessionConfiguration b) { - if (a is null) + if (a == null) { Assert.Null(b); }